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), [])
相关推荐
vyuvyucd2 分钟前
C++引用:高效编程的别名利器
算法
xkxnq2 分钟前
第一阶段:Vue 基础入门(第 15天)
前端·javascript·vue.js
程序员小假25 分钟前
我们来说一下无锁队列 Disruptor 的原理
java·后端
鱼跃鹰飞27 分钟前
Leetcode1891:割绳子
数据结构·算法
️停云️27 分钟前
【滑动窗口与双指针】不定长滑动窗口
c++·算法·leetcode·剪枝·哈希
资生算法程序员_畅想家_剑魔39 分钟前
Kotlin常见技术分享-02-相对于Java 的核心优势-协程
java·开发语言·kotlin
ProgramHan42 分钟前
Spring Boot 3.2 新特性:虚拟线程的落地实践
java·jvm·spring boot
nbsaas-boot1 小时前
Go vs Java 的三阶段切换路线图
java·开发语言·golang
anyup1 小时前
2026第一站:分享我在高德大赛现场学到的技术、产品与心得
前端·架构·harmonyos
码农小韩1 小时前
基于Linux的C++学习——指针
linux·开发语言·c++·学习·算法