Arrays
Data Types
Write a program that removes the element at the nth index in the provided array, and returns the new array.
If the number provided is not an index in the array, return the original array.
For Example:
remove([1, 2, 3], 2) => [1, 2]
remove(["dog", "cat", "bat", "parrot", "monkey"], 4) => ["dog", "cat", "bat", "parrot"]
function remove (arr, n) {
if (n < 0 || n >= arr.length) return arr;
arr.splice(n, 1);
return arr;
}
// TODO: Replace examples and use TDD development by writing your own tests
// These are some CW specific test methods available:
// Test.expect(boolean, [optional] message)
// Test.assertEquals(actual, expected, [optional] message)
// Test.assertSimilar(actual, expected, [optional] message)
// Test.assertNotEquals(actual, expected, [optional] message)
// NodeJS assert is also automatically required for you.
// assert(true)
// assert.strictEqual({a: 1}, {a: 1})
// assert.deepEqual({a: [{b: 1}]}, {a: [{b: 1}]})
// You can also use Chai (http://chaijs.com/) by requiring it yourself
// var expect = require("chai").expect;
// var assert = require("chai").assert;
// require("chai").should();
describe("Solution", function(){
it("should remove the correct element", function(){
Test.assertSimilar(remove([1, 2, 3], 2), [1, 2], "Wrong! Try again.");
Test.assertSimilar(remove([1, 2, 3, 4, 5, 6, 2, 1, 5, 3], 8), [1, 2, 3, 4, 5, 6, 2, 1, 3], "Wrong! Try again.");
Test.assertSimilar(remove(["1,2,3,4,5", "test", 7, {obj: "obj"}, [8,2,5]], 3), ["1,2,3,4,5", "test", 7, [8,2,5]], "Wrong! Try again.");
Test.assertSimilar(remove(["dog", "cat", "bat", "parrot", "monkey"], 4), ["dog", "cat", "bat", "parrot"], "Wrong! Try again.");
});
it("should return original array if index is out of range", function(){
Test.assertSimilar(remove([1, 2, 3], 20), [1, 2, 3], "Wrong! Try again.");
Test.assertSimilar(remove([1, 2, 3, 4, 5, 6, 2, 1, 5, 3], 17), [1, 2, 3, 4, 5, 6, 2, 1, 5, 3], "Wrong! Try again.");
Test.assertSimilar(remove(["1,2,3,4,5", "test", 7, {obj: "obj"}, [8,2,5]], -19), ["1,2,3,4,5", "test", 7, {obj: "obj"}, [8,2,5]], "Wrong! Try again.");
Test.assertSimilar(remove(["dog", "cat", "bat", "parrot", "monkey"], -1), ["dog", "cat", "bat", "parrot", "monkey"], "Wrong! Try again.");
});
});