Arrays
Fundamentals
Multiply Every Element
Create a function called multiplyArray
that takes two inputs:
- An array of integers (
arr
). - A single integer (
n
).
Your task is to return a new array where each number in the original array is multiplied by n
.
If the input array is empty, the function should return an empty array.
Examples:
multiplyArray([1, 2, 3], 2);
// Output: [2, 4, 6]
multiplyArray([], 5);
// Output: []
multiplyArray([0, 10, -10], 0);
// Output: [0, 0, 0]
Notes:
- The input array can contain positive numbers, negative numbers, or zero.
function multiplyArray(arr, n) {
return arr.map((num) => num * n);
}
const chai = require("chai");
const assert = chai.assert;
describe("multiplyArray", function () {
it("should handle basic cases", function () {
assert.deepEqual(multiplyArray([1, 2, 3], 2), [2, 4, 6]);
assert.deepEqual(multiplyArray([5, -3, 7], 3), [15, -9, 21]);
assert.deepEqual(multiplyArray([], 10), []);
assert.deepEqual(multiplyArray([0, 1, -1], 0).map(v => Object.is(v, -0) ? 0 : v), [0, 0, 0]); // Handle -0
});
it("should handle mixed numbers", function () {
assert.deepEqual(multiplyArray([0, 1, -1, 2, -2], 3).map(v => Object.is(v, -0) ? 0 : v), [0, 3, -3, 6, -6]); // Handle -0
assert.deepEqual(multiplyArray([-100, 0, 100], -1).map(v => Object.is(v, -0) ? 0 : v), [100, 0, -100]); // Handle -0
});
it("should handle large numbers", function () {
assert.deepEqual(multiplyArray([1000000, 2000000, 3000000], 2), [2000000, 4000000, 6000000]);
assert.deepEqual(multiplyArray([10, 20, 30], -100000), [-1000000, -2000000, -3000000]);
});
it("should handle edge cases", function () {
// Multiplying by 0
assert.deepEqual(multiplyArray([1, 2, 3, 4, 5], 0), [0, 0, 0, 0, 0]);
// Empty array
assert.deepEqual(multiplyArray([], 5), []);
// Single-element array
assert.deepEqual(multiplyArray([42], 1), [42]);
assert.deepEqual(multiplyArray([-42], 2), [-84]);
});
it("should handle large arrays", function () {
const largeArray = Array(1000).fill(1); // Array of 1000 ones
const largeArrayExpected = Array(1000).fill(10); // Each element multiplied by 10
assert.deepEqual(multiplyArray(largeArray, 10), largeArrayExpected);
});
it("should handle special edge cases gracefully", function () {
// Multiplying by negative fractions
assert.deepEqual(multiplyArray([2, 4, 6], -0.5), [-1, -2, -3]);
// Handling an array of all zeros
assert.deepEqual(multiplyArray([0, 0, 0], 100), [0, 0, 0]);
});
});