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), [])
相关推荐
装不满的克莱因瓶2 分钟前
Servlet 到 Spring MVC 架构演进:Java Web 开发二十年技术变迁史
java·spring·servlet·架构·springmvc
周末也要写八哥2 分钟前
浅谈:C++中cpp 14 ~ cpp 17
开发语言·c++·算法
z落落9 分钟前
C# 静态成员 vs 非静态成员(调用规则+内存特点)+只读和常量 const常量 / readonly / static readonly 三者终极区别
java·开发语言·c#
java1234_小锋15 分钟前
LangChain4j 开发Java Agent智能体- 整合SpringBoot4
java·开发语言·langchain4j
Hoey18 分钟前
虚拟 DOM 和 DIFF 算法
前端·vue.js
basketball61618 分钟前
C++进阶:3. unique_ptr 现代C++内存管理的基石
java·jvm·c++
bkspiderx20 分钟前
HTTP协议:Web通信的“通用语言”解析
前端·网络协议·http
云水一下21 分钟前
模块系统与 npm——万物皆模块
前端·npm·node.js
许彰午23 分钟前
13_HashMap底层原理详解
算法·哈希算法
GIOTTO情23 分钟前
基于 NLP 情感加权算法的智能舆情处置系统架构与落地实现
人工智能·算法·自然语言处理