简体   繁体   中英

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?

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;
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM