[JS] lodash

Goni·2022년 4월 13일
0

javascript

목록 보기
3/4

프로젝트 진행하면서 유용했던 라이브러리 정리2


lodash

공식문서: https://lodash.com/docs/4.17.15

  • js에서 다루는 함수들을 조금 더 직관적이고 쉽게 사용하도록 지원한다.
  • 복잡한 구조를 가진 객체도 쉽게 다룰 수 있다.
  • 함수들을 많이 알면 더욱 효율적으로 쓸 수 있을 것 같다. 지속적으로 유용한 함수들을 추가해야겠다.
  • 필요한 함수 찾기 전에 lodash에서 지원하는게 있는지 먼저 찾아봐야겠다.


For Array

_.fill(array(Array), value(*), start = 0, end = array.length)

return: (Array)

  • array를 value만큼 채운 array를 반환(새로운 배열 X)
let array = [1, 2, 3];

_.fill(array, 0);               // array: [0, 0, 0]
_.fill(Array(3), 1);            // [1, 1, 1]
_.fill([1, 2, 3, 4], '*', 1, 3) // [1, '*', '*', 4];


.findIndex(array(Array), predicate=_.identity, fromIndex = 0)

return: (number)

  • match되는 객체의 index 반환

비슷한 함수
findLastIndex(https://lodash.com/docs/4.17.15#findLastIndex)
indexOf(https://lodash.com/docs/4.17.15#indexOf)

const arr = {
    { 'name': 'A', 'active': true },
    { 'name': 'B', 'active': true },
    { 'name': 'C', 'active': false }
}

_.findIndex(arr, d => return d.name === 'B');       // 1
_.findIndex(arr, { 'name': 'A', 'active': true});   // 0
_.findIndex(arr, ['active', true]);                 // 0


For Collection

  • Array와 비슷하게 순회하는 기능들은 다 있다고 보면 될 것 같다.
  • Array와 다른 점만 익혀두면 좋을 것 같다

.forEach(collection(Array | Object), iteratee=_.identity)

return: (*) collection

  • collection 순회
_.forEach([1, 2], val => console.log(val))  // ouput: 1, 2
_.forEach([{'a': 1 }, { 'b': 2 }], (val, key) => console.log(key)) // output: a, b


.sortBy(collection(Array | Object), [iteratee=[_.identity]](Function | Function[]))

return: (Array) new sorted Array

  • collection 오름차순 정렬
const users = [
  { 'user': 'fred',   'age': 48 },
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 40 },
  { 'user': 'barney', 'age': 34 }
];

_.sortBy(users, [(d) => d.user])    //  return: [['barney', 36], ['barney', 34], ['fred', 48], ['fred',40]]
_.sortBy(users, ['user', 'age'])    //  return: [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]]


For Function

_.debounce(func(Function), wait = 0, options = {})

_.throttle(func, [wait=0], [options={}])

options.leading = false:
options.maxWait = false: 기다릴 수 있는 최대 시간
options.trailing = true:

return: (Function) new debounced or throttled function

  • 효율적인 이벤트 처리

debounce / throttle 개념

  • 연속적으로 발생하는 이벤트를 하나의 그룹으로 묶어 처리하는 방법
  • 마지막(debounce) 혹은 처음(throttle)에 연속된 함수를 처리하는 방식

debounce / throttle 예시

스크롤 휠을 이용한 지도 확대/축소
검색어 입력 시 자동완성 및 연관 검색어 노출
피드 방식의 데이터 노출

// resize 이벤트 유동적 - 마지막 처리
jQuery(window).on('resize', _.debounce(calculateLayout, 150));

// scroll 이벤트 유동적 - 처음 처리
jQuery(window).on('scroll', _.throttle(updatePosition, 100));


_.delay(func(Function), wait = 0, [args])

args: func의 매개변수

return: (number) timer id

_.delay((text) => console.log('text), 1000, 'later')    //  output: 1초 후 text 출력


For Lang

_.cloneDeep(value)

return: value(*) deep cloned value

비슷한 함수

_.clone(value)

헷갈렸던 점

  • 얕은 복사와 깊은 복사를 간과해서 개발할 때 많이 꼬였었다.... 항상 이점 유의해야겠다
const arr = [1, 2];
let cArr = _.clone(arr);
console.log(arr === cArr);  // output: true

cArr = _.cloneDeep(arr);
console.log(arr === cArr);  // output: false


이 외에 대부분의 배열, 객체, 데이터를 다루는 js 함수들을 지원하는 것 같다.
필요할 때 docs 참고해서 활용해야겠다!

0개의 댓글