April 23, 2019

lodash 的程式碼實現

員工訓練之一


文 / 西打藍 Siddharam

lodash


這次來挑選常用的 lodash function,嘗試自己手寫。
lodash 的 GitHub 有他們的實作方式,練習過後可以去比較兩邊程式碼有何差異。

練習


(1) dropRight(array, 從右邊移除多少個數)

_.dropRight([1, 2, 3], 2);
// => [1]


function drop (array, count) {
  return array.slice(0, array.length-count)
}

drop([1,2,3,4,5,6,7,8], 2)
//  [1, 2, 3, 4, 5, 6]



(2) findIndex(array, 找到符合條件的 index)

var users = [
{ 'user': 'barney', 'active': false },
{ 'user': 'fred', 'active': false },
{ 'user': 'pebbles', 'active': true }
];

_.findIndex(users, function(o) { return o.user == 'barney'; });
// => 0

_.findIndex(users, { 'user': 'fred', 'active': false });
// => 1


var users = [ 
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': true }
]

function findIndex(array, types){
    for(let i=0; i < array.length; i++){
        if(array[i].user == types.user && array[i].active == types.active){
            return i
        }
    } 
}

findIndex(users, { 'user': 'barney', 'active': false })
// 0



(3) pull(array, 去除哪些 value)

var array = ['a', 'b', 'c', 'a', 'b', 'c'];
_.pull(array, 'a', 'c');
// => ['b', 'b']


function pull(array, ...remove){
  let newArray = [];
  for(let i=0; i < array.length; i++){
    for(let j=0 ; j < remove.length; j++){
       if(array[i] == remove[j]){
           newArray.push(i)
       }
    }
  }
for(let k=newArray.length; k>0; k--){ array.splice(newArray[k-1],1) } return array }
pull(['a','c','e','g','h','a'],'a','b','c','j','z') // ["e", "g", "h"]


(4) reverse(反轉哪些 array)

var array = [1, 2, 3];
_.reverse(array);
// => [3, 2, 1]


function reverse(array){
  let newArray = [];
  for(let i=array.length; i>0; i--){
    newArray.push(array[i-1])
  }
  return newArray
}
reverse(['1','2','3','4']) // ["4", "3", "2", "1"]

(5) shuffle(array 洗牌)

_.shuffle([1, 2, 3, 4]);
// => [4, 1, 3, 2]


function shuffle(array){ for(let i=0 ; i < array.length; i++){ var rand = Math.floor(Math.random() * array.length) var temp = array[rand] array[rand] = array[i] array[i] = temp } return array }
shuffle([1,2,3,4,5]) // [1, 3, 5, 4, 2] random




閱讀量




聯絡與合作


有文字採訪、網站開發,或是諮詢需求,皆可至個人網站參考作品,並聯繫 IG

或是想分享心情、聊聊天、交朋友,可以來秘密通道找我唷。

Email: frank@siddharam.com

訂閱: