Underscore #3

GunWยท2019๋…„ 5์›” 3์ผ
0
post-custom-banner

๐Ÿ‘จ๐Ÿปโ€๐Ÿ’ป UnderScore

indongyoo ๋‹˜์˜ ๋ธ”๋กœ๊ทธ๋ฅผ ๋ณด๋ฉด์„œ ์—ฐ์Šตํ•ด๋ณด์ž!
๋ฉ”์†Œ๋“œ๋งŒ ๋ด์„œ๋Š” ์–ด์ฐจํ”ผ ๋จธ๋ฆฌ์— ๋“ค์–ด์˜ค์ง€ ์•Š๋Š”๋‹ค!!!๐Ÿคฆ๐Ÿปโ€๐Ÿคฆ๐Ÿปโ€๐Ÿคฆ๐Ÿปโ€
์–ด์ฐจํ”ผ ์›๋ž˜ ์žˆ๋˜ ๋ฉ”์†Œ๋“œ๋“ค์„ ํ™œ์šฉํ•˜๋ฏ€๋กœ ์˜๋ฏธ๋Š” ๊ฐ์ด ์˜ค๋‹ˆ๊นŒ...?!


_.each

๋ญ”๊ฐ€ forEach์™€ ๋งค์šฐ ๋น„์Šทํ•˜๊ฒŒ ์ƒ๊ฒผ๋‹ค.

const _ = require('underscore');

// _.each : each์™€ ๋น„์Šทํ•˜๊ฒŒ ๋™์ž‘ํ•˜์ง€๋งŒ ์กฐ๊ธˆ ๋‹ค๋ฅด๋‹ค.
_.each([1,2,3], (val, i, list) => {
    console.log(val, i, list);
});
// 1 0 [ 1, 2, 3 ]
// 2 1 [ 1, 2, 3 ]
// 3 2 [ 1, 2, 3 ]

// _.each์™€ forEach์˜ ์ฐจ์ด์ 
// 1. forEach์˜ ๋ฆฌํ„ด๊ฐ’์€ undefiend์ด๋‹ค.
let res = [1,2,3].forEach((val, i, list) => (val, i, list));
console.log(res); // undefined

// 2. ๊ฐ์ฒด์—๋„ ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•˜๋‹ค.
_.each({a: 1, b: 2}, (val, key, obj) => console.log(val, key, obj));
// 1 'a' { a: 1, b: 2 }
// 2 'b' { a: 1, b: 2 }

.reject, .contains, _.isArray

  • _.reject : filter์™€ ๋น„์Šทํ•œ ๋™์ž‘์„ ํ•œ๋‹ค. ํ•˜์ง€๋งŒ ์—ญ์‹œ immutable!
  • _.contains : ์˜๋ฏธ ๊ทธ๋Œ€๋กœ ํฌํ•จํ•˜๋ฉด true
  • _.isArray : ๋ฐฐ์—ด์ด๋ฉด true
const list = [1, 2, 3, 4, 5];
console.log(_.reject(list, (num) => num % 2 === 0)); // [ 1, 3, 5 ]
console.log(_.contains([1, 2, 3], 3));  // true
console.log(_.isArray([1, 2, 3]))       // true

_.pluck

์•„๋ž˜์ฒ˜๋Ÿผ ๋ฐฐ์—ด ๋‚ด๋ถ€์˜ ๊ฐ’๋“ค์ด key/value ์Œ์œผ๋กœ ๊ตฌ์„ฑ๋œ ๊ฐ์ฒด์ผ ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.
๋‘ ๋ฒˆ์งธ ์ธ์ž์˜ key๊ฐ’์œผ๋กœ ์ ‘๊ทผํ•˜์—ฌ value๋“ค์„ ๋ฐฐ์—ด๋กœ ๋ฆฌํ„ดํ•œ๋‹ค.

const brand = [
  { id: 1, name: "LMC"},
  { id: 2, name: "AderError"},
  { id: 3, name: "Covernat"},
  { id: 4, name: "Apple"},
  { id: 5, name: "Supreme"},
  { id: 6, name: "Nike"},
  { id: 7, name: "Liful"}];
console.log(_.pluck(brand, 'name')); 
// [ 'LMC', 'AderError', 'Covernat', 'Apple', 'Supreme', 'Nike', 'Liful' ]

_.negate

๋ฐ›์•„๋‘” ํ•จ์ˆ˜๋ฅผ ์‹คํ–‰ํ•˜์—ฌ ๋‚˜์˜จ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜๋Œ€๋กœ ๋ฐ”๊พธ๋Š” ํ•จ์ˆ˜์ด๋‹ค.
๊ฒฐ๊ณผ๋งŒ ๋’ค์ง‘๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ ํ•จ์ˆ˜๋ฅผ ์‹คํ–‰ํ•œ ํ›„์˜ ๊ฒฐ๊ณผ๋ฅผ ๋’ค์ง‘๋Š” ๊ฒƒ์ด๋‹ค.

const isZero = (n) => n === 0;
console.log(isZero(0));
// true
const isNotZero = _.negate(isZero);
console.log(isNotZero(0));
// false

_.noop

undefined๋งŒ ๋ฆฌํ„ดํ•˜๋Š” ํ•จ์ˆ˜...!

console.log(_.noop());
console.log(_.noop(100));
console.log(_.noop([],[]));

๐Ÿ› Chaining

์ฒด์ด๋‹์œผ๋กœ ์‚ฌ์šฉํ•ด ๋ด…์‹œ๋‹ค...๐Ÿ˜†
_.chain์„ ์‚ฌ์šฉํ•˜๋ฉด ๋งˆ์ง€๋ง‰ .value()๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ์ „๊นŒ์ง€ ๋ฉ”์†Œ๋“œ๋ฅผ ๊ณ„์† ์‹คํ–‰ํ•  ์ˆ˜ ์žˆ๋‹ค.

// functional
const arr = _.filter(
    _.map([1,2,3], n => n * 2), n => n <= 4
);
console.log(arr) // [ 2, 4 ]

// Chaining
const arr2 = _.chain([1, 2, 3])
.map(n => n * 2)
.filter(n => n <= 4)
.value();
console.log(arr2) // [ 2, 4 ]
profile
ggit
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€