How to Square numbers in Array
How to Square numbers in Array
Example:
Input: myArray = [1,2,3]
Output: [1, 4, 9]
Can be done using Array.prototype.map() which always creates a new array
Solution using Javascript:
function squareNumbersArray(myArray) {
const result = myArray.map((number) => {
if (typeof number !== 'number') {
throw new Error('My custom error');
}
return number * number;
})
return result;
}
Test Cases
describe('squareNumbersArray', () => {
test('should throw an error if array of numbers is not passed as argument', () => {
const myArray = [1, 2, 'string', 4];
expect(() => squareNumbersArray(myArray)).toThrow('My custom error');
});
test('should return square array', () => {
const myArray = [1,2,3];
expect(squareNumbersArray(myArray)).toEqual([1, 4, 9]);
});
});