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

你可能感兴趣的:(#,Edabit,java,javascript,算法,前端)