0052【Edabit ★☆☆☆☆☆】Learn Lodash: _.drop, Drop the First Elements of an Array

0052【Edabit ★☆☆☆☆☆】Learn Lodash: _.drop, Drop the First Elements of an Array

arrays

Instructions

According to the lodash documentation, _.drop creates a slice of an array with n elements dropped from the beginning.

Your challenge is to write your own version using vanilla JavaScript.

Examples
javascript 复制代码
drop([1, 2, 3], 1) // [2, 3]
drop([1, 2, 3], 2) // [3]
drop([1, 2, 3], 5) // []
drop([1, 2, 3], 0) // [1, 2, 3]
Notes
  • Do not attempt to import lodash; you are simply writing your own version.
Solutions
javascript 复制代码
function drop(arr, val = 1) {
    while(val-->0){
        arr.shift();
    }
    return arr;
}
TestCases
javascript 复制代码
let Test = (function(){
    return {
        assertEquals:function(actual,expected){
            if(actual !== expected){
                let errorMsg = `actual is ${actual},${expected} is expected`;
                throw new Error(errorMsg);
            }
        },
        assertSimilar:function(actual,expected){
            if(actual.length != expected.length){
                throw new Error(`length is not equals, ${actual},${expected}`);
            }
            for(let a of actual){
                if(!expected.includes(a)){
                    throw new Error(`missing ${a}`);
                }
            }
        }
    }
})();

Test.assertSimilar(drop([1, 2, 3], 2), [3])
Test.assertSimilar(drop([1, 2, 3], 5), [])
Test.assertSimilar(drop([1, 2, 3], 0), [1, 2, 3])
Test.assertSimilar(drop(["banana", "orange", "watermelon", "mango"], 2), ["watermelon", "mango"])
Test.assertSimilar(drop([], 2), [])
相关推荐
bing_15812 分钟前
Spring Boot 项目中什么时候会抛出 FeignException?
java·spring boot·后端
lingxiao1688824 分钟前
双目立体视觉
图像处理·算法·机器学习·计算机视觉
JNU freshman28 分钟前
和为target问题汇总
算法
2401_8590490832 分钟前
MSPM0--Timer(一口一口喂版)
arm开发·单片机·mcu·算法
不爱吃饭爱吃菜34 分钟前
uniapp微信小程序-长按按钮百度语音识别回显文字
前端·javascript·vue.js·百度·微信小程序·uni-app·语音识别
寂空_38 分钟前
【算法笔记】ACM数论基础模板
c++·笔记·算法
Java&Develop43 分钟前
springboot + mysql8降低版本到 mysql5.7
java·spring boot·后端
sg_knight1 小时前
从单体架构到微服务:架构演进之路
java·spring boot·spring·spring cloud·微服务·云原生·架构
ggabb1 小时前
当九九乘法口诀“出海”英国:文化碰撞下的数学教育变革
算法
爱coding的橙子1 小时前
每日算法刷题计划Day7 5.15:leetcode滑动窗口4道题,用时1h
算法·leetcode