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), [])
相关推荐
Mapmost几秒前
让 AI 真正看懂世界—构建具备空间理解力的智能体
前端
橙 子_16 分钟前
我本以为代码是逻辑,直到遇见了HTML的“形”与“意”【一】
前端·html
mit6.82417 分钟前
py期中实验选题:实现天气预测
python·算法
xuehaikj19 分钟前
YOLOv8多场景人物识别定位与改进ASF-DySample算法详解
算法·yolo·目标跟踪
二川bro21 分钟前
第51节:Three.js源码解析 - 核心架构设计
开发语言·javascript·ecmascript
Kisang.22 分钟前
【HarmonyOS】ArkWeb——从入门到入土
前端·华为·typescript·harmonyos·鸿蒙
-大头.25 分钟前
响应式编程实战:WebFlux与RSocket深度解析
java·开发语言
沉默璇年28 分钟前
tgz包批量下载脚本
前端
Wenhao.35 分钟前
LeetCode 救生艇
算法·leetcode·golang
超级无敌大学霸36 分钟前
二分查找和辗转相除法
c语言·算法