一天一個仿lodash函數實現-intersection

intersection

這個和前面寫的difference反過來,difference是求未出現過的,intersection是求出現過的,所以實現起來就比較簡單了。

function intersection(arr, ...rest){
  const left = rest.reduce((pre, cur)=>{
    return pre.concat(cur.map(item=>iteratee(item)))
  }, []);
  return arr.filter(item=>left.includes(item))
}

function intersectionBy(arr, ...rest){
  const iterateeKey = rest[rest.length-1]
  const iteratee = typeof iterateeKey === 'string'?(item)=>item[iterateeKey]:iterateeKey;
  const left = rest.slice(0, rest.length-1).reduce((pre, cur)=>{
    return pre.concat(cur.map(item=>iteratee(item)))
  }, []);
  return arr.filter(item => {
    return left.includes(iteratee(item))
  })
}

function intersectionWith(arr, ...rest){
  const comparator = rest[rest.length - 1]
  const left = rest.slice(0, rest.length-1).reduce((pre, cur)=>{
    return pre.concat(cur)
  }, []);
  return arr.filter(item => {
    for(let i=0;i<left.length;i++) {
      if(comparator(left[i], item)) {
        return true;
      }
    }
    return false
  })
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章