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), [])