0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

reject,pluck,reduceを書いてみる

Last updated at Posted at 2025-10-17

前回までは、size,each,map,filterを書いたので、今回は前回書いたコードを流用して別の関数を書いてみます。

reject

  • 第二引数に渡されたテストをパスしなかったものだけを配列に入れて返す(filterの逆)
    _.reject = (collection,test) => { return_.filter(collection,(val)=>{      return !test(val));       };

pluck

  • 第二引数にオブジェクトのkeyを渡し、
    keyに対応する値を返す
    [{name:naoki},{age:10}]のような形

_.pluc = (collection,key) => { return _.map(collection,(obj) =>{ return val[key]; });

reduce

  • 第一引数accumulatorに第二引数currentValueを累積していく関数
    第三引数には、初期値initialValueを入れる

`_.reduce = (collection,iterator,initialValue)=>{
let accumulator = initialValue;
if(initialValue !== undefined) {
_.each(collection,(val,key) => {
accumulator =iterator(accumulator,val)
});

}else {
let count = 0;
_.each(collection,(val) => {
if(count === 0) => {
accumulator = val
}else {
accumulator = iterator(accumulator,val);
}
count ++;
});
}
return result;
};`

accumulator = iterator(accumulator,val)になる理由

  • letで定義したグローバル変数としてのaccumulatorは、引数としてiteratorに渡した時、別の変数として扱われる(コピー)

-iteratorは、結果を返すだけなので、グローバル変数であるaccumulatorの値を書き換えることで結果を更新できる

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?