findIndex 🔖



lodash

  • A modern JavaScript utility library delivering modularity, performance, & extras
  • https://github.com/lodash/lodash

    1. findIndex


    findIndexは、配列、標準(関数、同じobj、属性値など)と検索するインデックス開始(Optional)を入れることで検索される関数です.
    すなわち、次のusersを入力してindexを検索すると、次のコメントのように関数を返すことができます.
     var users = [
     { 'user': 'barney',  'active': false },
     { 'user': 'fred',    'active': false },
     { 'user': 'pebbles', 'active': true }];
         * _.findIndex(users, function(o) { return o.user == 'barney'; });
         * // => 0
         *
         * // The `_.matches` iteratee shorthand.
         * _.findIndex(users, { 'user': 'fred', 'active': false });
         * // => 1
         *
         * // The `_.matchesProperty` iteratee shorthand.
         * _.findIndex(users, ['active', false]);
         * // => 0
         *
         * // The `_.property` iteratee shorthand.
         * _.findIndex(users, 'active');
         * // => 2
         */

    完全なコード💜

    function findIndex(array, predicate, fromIndex) {
      var length = array == null ? 0 : array.length;
      if (!length) {
        return -1;
      }
      var index = fromIndex == null ? 0 : toInteger(fromIndex);
      if (index < 0) {
        index = nativeMax(length + index, 0); // Math.max()
      }
      return baseFindIndex(array, getIteratee(predicate, 3), index);
    }

    部分コード💜

        function findIndex(array, predicate, fromIndex) {
          // array 가 유효한지 검증해주는 여러가지 요소 
          var length = array == null ? 0 : array.length;
          
          // length 자체가 false이면 요소가 있는지 검증이 안되므로 없다는 -1 을 리턴 
          if (!length) {
            return -1;
          }
          
          // index 자체가 안들어 올땐 0번째 index 부터 볼수 있도록 
          var index = fromIndex == null ? 0 : toInteger(fromIndex);
          
          // index에 0 보다 작은 수가 들어오면, 길이만큼을 더한뒤에도 음수이면 0으로 양수이면 해당 index 기준으로 적용해준다.
          if (index < 0) {
            index = nativeMax(length + index, 0); 
          }
          // Math.max(length + index, 0)와 같다고 보면된다.
          
          // 그러고 난뒤 baseFindIndex함수를 호출한다. 
          
          return baseFindIndex(array, getIteratee(predicate, 3), index);
        }
    findIndexを理解するために、2つの知らなければならない関数getIterateebaseFindIndexを見てみましょう.

    2. baseFindIndex()

  • findIndex関数はbaseFindIndexを呼び出します.
  •   function baseFindIndex(array, predicate, fromIndex, fromRight) {
        var length = array.length,
            // index는 fromRight에 parameter를 넣어줬다면 1을 더해주고 아니면 -1을 해준다음 더해준다. 빼주는 이유는 아래 while문에서 더해주면서 loop을 돌아야 하기 때문이다! 
            index = fromIndex + (fromRight ? 1 : -1);
    
        // while문을 도는 기준은 오른쪽부터 기준이라면 index에서 하나씩 빼면서, 왼쪽에서부터 오른쪽이라면 index에 1을 더하면서 배열의 길이 전까지 돌아준다 .
        while ((fromRight ? index-- : ++index < length)) {
          //if문이 true일때 index를 return 하고 없으면 -1을 리턴한다. 
          if (predicate(array[index], index, array)) {
            return index;
          }
        }
        return -1;
      }

    3. getIteratee()

    
        function getIteratee() {
          var result = lodash.iteratee || iteratee;
          
          //baseIteratee를 리턴하는 함수이고 arguments를 받으면 baseIteratee(a,b) 이런식으로 baseIteratee를 호출하게 된다. 
          result = result === iteratee ? baseIteratee : result;
          return arguments.length ? result(arguments[0], arguments[1]) : result;
        }

    4. baseIteratee(value)

        function baseIteratee(value) {
          if (typeof value == 'function') {
            return value;
          }
          if (value == null) {
            return identity;
          }
          // object가 들어올때 value가 array형식일때 
          if (typeof value == 'object') {
            return isArray(value)
            // 
              ? baseMatchesProperty(value[0], value[1])
            // 
              : baseMatches(value);
          }
          // 
          return property(value);
        }
    // 수정중......