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), [])
相关推荐
涂兵兵_青石疏影4 分钟前
beginPath-vs-save详解
前端
陈振wx:zchen20085 分钟前
前端-面试题-JavaScript
javascript·前端面试题
ん贤11 分钟前
加密算法(对称、非对称、哈希、签名...)
算法·哈希算法
泽_浪里白条16 分钟前
我在 Superset 6.x 做自定义图表 + Embedded SDK 集成的实战复盘(附踩坑清单)
前端·数据可视化
JAVA面经实录91724 分钟前
企业级java+LangChain4j-RAG系统 限流熔断降级
java·开发语言·分布式·langchain
Drug29 分钟前
Struts2 从入门到放弃?不,这些核心知识你依然需要掌握
java
幽络源小助理34 分钟前
小六壬排盘工具源码 自适应双端 纯原生HTML+JS
前端·javascript·html
Slow菜鸟36 分钟前
Codex CLI 教程(五)| AI 驱动项目从零到一:面向 Java 全栈工程师打造个人 ECC(V2版)
java·开发语言·人工智能
superior tigre40 分钟前
78 子集
算法·leetcode·深度优先·回溯
天威?*44 分钟前
bitset的数据结构用法
算法·动态规划