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), [])
相关推荐
云烟成雨TD21 小时前
Spring AI Alibaba 1.x 系列【6】ReactAgent 同步执行 & 流式执行
java·人工智能·spring
小O的算法实验室21 小时前
2026年ASOC,基于深度强化学习的无人机三维复杂环境分层自适应导航规划方法,深度解析+性能实测
算法·无人机·论文复现·智能算法·智能算法改进
于慨21 小时前
Lambda 表达式、方法引用(Method Reference)语法
java·前端·servlet
石小石Orz21 小时前
油猴脚本实现生产环境加载本地qiankun子应用
前端·架构
swg32132121 小时前
Spring Boot 3.X Oauth2 认证服务与资源服务
java·spring boot·后端
从前慢丶21 小时前
前端交互规范(Web 端)
前端
gelald1 天前
SpringBoot - 自动配置原理
java·spring boot·后端
@yanyu6661 天前
07-引入element布局及spring boot完善后端
javascript·vue.js·spring boot
殷紫川1 天前
深入理解 AQS:从架构到实现,解锁 Java 并发编程的核心密钥
java
一轮弯弯的明月1 天前
贝尔数求集合划分方案总数
java·笔记·蓝桥杯·学习心得