ikemonn's blog

技術ネタをちょこちょこと

【Underscore.js】_.findを読んだ

jashkenas/underscore_.findを読んだ。

概要

リストを走査し、渡した関数がtrueとなる最初の要素を返す。 条件を満たす要素がない場合はundefinedを返す。 trueとなる要素が見つかった時点で、リストの走査は終わる。

var list = [1, 2, 5, 6, 7];
var even = _.find (list, function(num){
    return num % 2 === 0;
});
console.log(even); // 2

 ソースコード

  // Return the first value which passes a truth test. Aliased as `detect`.
  _.find = _.detect = function(obj, predicate, context) {
    var key;
    if (isArrayLike(obj)) {
      key = _.findIndex(obj, predicate, context);
    } else {
      key = _.findKey(obj, predicate, context);
    }
    if (key !== void 0 && key !== -1) return obj[key];
  };


_.findIndex = createPredicateIndexFinder(1);

// Generator function to create the findIndex and findLastIndex functions
  function createPredicateIndexFinder(dir) {
    return function(array, predicate, context) {
      predicate = cb(predicate, context);
      var length = getLength(array);
      var index = dir > 0 ? 0 : length - 1;
      for (; index >= 0 && index < length; index += dir) {
        if (predicate(array[index], index, array)) return index;
      }
      return -1;
    };
  }


_.findKey = function(obj, predicate, context) {
    predicate = cb(predicate, context);
    var keys = _.keys(obj), key;
    for (var i = 0, length = keys.length; i < length; i++) {
      key = keys[i];
      if (predicate(obj[key], key, obj)) return key;
    }
  };

void 0 はundefinedを返す。

 参考

jashkenas/underscore