hashkrl

Detect empty pick() from hash in KRL


I have a bunch of data in a hash and I am picking from it. Sometimes there will be data there to pick and sometimes there won't. What is the best way to know when there was something found by the pick operator and when there wasn't so I can react to that in my code?


Solution

  • The pick operator will take a second optional parameter that will make it so that it always returns the results in an array. This means that if something is picked, the length of the array will be greater than 0, otherwise it will be 0. You can then use that to do what you are wanting to do.

    Example code/app taken from http://kynetxappaday.wordpress.com/2011/01/04/day-30-detecting-empty-pick/

    ruleset a60x526 {
      meta {
        name "hash-pick-detect"
        description <<
          hash-pick-detect
        >>
        author "Mike Grace"
        logging on
      }
    
      global {
        dataHash = {
          "one": {
            "name": "Mike"
          }, // number
          "two": {
            "random": 8
          }, // number
          "three": {
            "name": "Alex"
          } // number
    
        }; // dataHash
    
      } // global
    
      rule detect_the_pick {
        select when pageview ".*"
        foreach dataHash setting (key, value)
        pre {
          userName = value.pick("$.name", true);
          length = userName.length();
        }
        if (length > 0) then {
          notify("Key: #{key}","Name: #{userName}<br/>Length: #{length}") with sticky = true;
        }
        notfired {
          raise explicit event empty_pick
            with pickedKey = key;
        }
      }
    
      rule empty_pick_found {
        select when explicit empty_pick
        pre {
          pickedKey = event:param("pickedKey");
          results =<<
            Key: #{pickedKey}<br/>
            doesn't have a name associated with it to pick from
          >>; //' fixing syntax highlighting
        }
        {
          notify("An empty pick was detected",results) with sticky = true;
        }
      }
    }