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), [])
相关推荐
NanLing1 分钟前
【纯前端推理】纯端侧 AI 对象检测:用浏览器就能跑的深度学习模型
前端
小小小小王王王2 分钟前
求猪肉价格最大值
数据结构·c++·算法
呆呆的心3 分钟前
前端必学:从盒模型到定位,一篇搞定页面布局核心 🧩
前端·css
小飞悟3 分钟前
前端高手才知道的秘密:Blob 居然这么强大!
前端·javascript·html
小old弟3 分钟前
用Sass循环实现炫彩文字跑马灯效果
前端
code_YuJun3 分钟前
Promise 基础使用
前端·javascript·promise
Codebee4 分钟前
OneCode自主UI设计体系:架构解析与核心实现
前端·javascript·前端框架
GIS之路7 分钟前
GIS 空间关系:九交模型
前端
邢同学爱折腾8 分钟前
当前端轮播图遇上Electron: 变身一款丝滑的 图片查看器
javascript·electron
xiguolangzi14 分钟前
vue3+element-plus el-table列的显隐、列宽 持久化
前端·javascript·vue.js