본문 바로가기

development/myLib

[Lodash][Array] _.compact

_.compact(array)

Creates an array with all falsey values removed. The values false, null, 0, "", undefined, and NaN are falsey.

Since

    0.1.0

 

Arguments

      array(Array): The array to compact.

 

Returns

    (Array): Returns the new array of filtered values.

 

Example

_.compact([0, 1, false, 2, '', 3]);
// => [1, 2, 3]

 

마인드맵

_.compact  메서드를 활용해서 false 형태의 값을 제거한 새로운 배열을 반환합니다.

  1. 새로운 배열반환 ( false 없음 )
  2. if 문을 이용해 배열의 각 요소별로 값이 존재하는 형태로 필터한다.
  3. 성능개선, 소스단순화? 실행부 함수와 호출부 함수를 분리하고 호출할 대상을 정리해서 실행부는 분기없이 실행만 전담하도록 관심사 분할.
    - 하나의 함수에서 변수생성, 조건 분기, 실행을 하는 소스 분할.
    - 각각 함수로 분할, 필터하는 함수를 이용한 유효성을 보증해서 실행부에서는 값이 없는 경우에 대한 관심사 제거

 

Source

/**
     * Creates an array with all falsey values removed. The values `false`, `null`,
     * `0`, `""`, `undefined`, and `NaN` are falsey.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Array
     * @param {Array} array The array to compact.
     * @returns {Array} Returns the new array of filtered values.
     * @example
     *
     * _.compact([0, 1, false, 2, '', 3]);
     * // => [1, 2, 3]
     */
    function compact(array) {
      var index = -1,
          length = array == null ? 0 : array.length,
          resIndex = 0,
          result = [];

      while (++index < length) {
        var value = array[index];
        if (value) {
          result[resIndex++] = value;
        }
      }
      return result;
    }

 

'development > myLib' 카테고리의 다른 글

[Lodash][Array] _.concat  (0) 2020.05.03
[Lodash][Array] _.chunk  (0) 2020.05.01
라이브러리 분석 시작하기  (0) 2020.05.01