一天一个仿lodash函数实现-drop

drop

将数组头部的n个元素丢弃,返回一个新的数组

// 默认n为1
function drop(arr, n = 1) {
  if(n<0){
    throw new Error('n must be positive');
  }
  return arr.slice(n);
}

dropRight

和drop差不多,但是是从尾部开始

function dropRight(arr, n = 1) {
  if(n<0){
    throw new Error('n must be positive');
  }
  const endIndex = arr.length - n;
  // 考虑为负数时,返回空数组即可
  return arr.slice(0, endIndex>0?endIndex:0);
}

dropRightWhile

和dropRight差不多,但是是通过判断函数一旦返回false,就停止drop元素

(这次不考虑shorthand了)

function dropRightWhile(arr, predicate) {
  let end = arr.length;
  for(let i = arr.length-1;i>=0;i--){
    if(predicate(arr[i])){
      continue;
    }else{
      end = i+1;
    }
  }
  return arr.slice(0, end)
}

dropWhile

function dropWhile(arr, predicate) {
  let start = 0;
  for(let i = 0;i<arr.length;i++){
    if(predicate(arr[i])){
      continue;
    }else{
      start = i;
    }
  }
  return arr.slice(start)
}
posted @ 2022-06-12 10:27  Dont  阅读(37)  评论(0编辑  收藏  举报