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.文章来源:https://www.toymoban.com/news/detail-735664.htmlYour challenge is to write your own version using vanilla JavaScript.文章来源地址https://www.toymoban.com/news/detail-735664.html
Examples
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
function drop(arr, val = 1) {
while(val-->0){
arr.shift();
}
return arr;
}
TestCases
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), [])
到了这里,关于0052【Edabit ★☆☆☆☆☆】Learn Lodash: _.drop, Drop the First Elements of an Array的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!