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?

contains,every,extendを書いてみる

Posted at

contains

  • 配列やオブジェクトにtargetが含まれているかをtrue/falseで返すもの

_.contains = (collection,target) => { return _.reduce(collection,(wasFound,item) => { if(wasFound){ return true; }else { return item === target; } }, false ); };

  • 初期値である第三引数にfalseを入れる
  • wasFoundがtrueかfalseかを判定し、一度でもtrueが入るとtrueを返し続けるので、最終的な値は、trueになる。つまり、targetが存在すればtrueが返る

every

  • コレクションの全ての要素に対して与えられたテストが通るかを確かめる

_.every = (collection,test) => { return _.reduce(collection,(wasFound,item) => { if(!wasFound) { return false; }else { return test(item); } }, true ); };

より短く書くと

_.every = (collection,test) => { return _.reduce(collection,(wasFound,item) => { wasFound && test(item); }, true ); };

extend

最初のオブジェクトに対して、その他のオブジェクトを結合する

_.extend = (...objs) => {for(let i = 1; i < objs.length; i++) { _.each(obj[i],(val,key) => { objs[0][key] = val; }); } return obj[0] };

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?