|
| 1 | +## [Array Helpers](https://www.codewars.com/kata/525d50d2037b7acd6e000534) |
| 2 | + |
| 3 | +- This kata is designed to test your ability to extend the functionality of built-in classes. In this case, we want you to extend the built-in Array class with the following methods: square(), cube(), average(), sum(), even() and odd(). |
| 4 | + |
| 5 | +#### Explanation: |
| 6 | + |
| 7 | +- `square()` must return a copy of the array, containing all values squared |
| 8 | +- `cube()` must return a copy of the array, containing all values cubed |
| 9 | +- `average()` must return the average of all array values; on an empty array must return NaN (note: the empty array is not tested in Ruby!) |
| 10 | +- `sum()` must return the sum of all array values |
| 11 | +- `even()` must return an array of all even numbers |
| 12 | +- `odd()` must return an array of all odd numbers 2 _ 2 _ 1 |
| 13 | + |
| 14 | +Note: the original array must not be changed in any case! |
| 15 | + |
| 16 | +#### Examples: |
| 17 | + |
| 18 | +```js |
| 19 | +var numbers = [1, 2, 3, 4, 5]; |
| 20 | + |
| 21 | +numbers.square(); // must return [1, 4, 9, 16, 25] |
| 22 | +numbers.cube(); // must return [1, 8, 27, 64, 125] |
| 23 | +numbers.average(); // must return 3 |
| 24 | +numbers.sum(); // must return 15 |
| 25 | +numbers.even(); // must return [2, 4] |
| 26 | +numbers.odd(); // must return [1, 3, 5] |
| 27 | +``` |
| 28 | + |
| 29 | +#### Solution: |
| 30 | + |
| 31 | +```js |
| 32 | +// Square every number in the array |
| 33 | +Array.prototype.square = function () { |
| 34 | + return this.map((num) => num * num); |
| 35 | +}; |
| 36 | + |
| 37 | +// Cube every number in the array |
| 38 | +Array.prototype.cube = function () { |
| 39 | + return this.map((num) => Math.pow(num, 3)); |
| 40 | +}; |
| 41 | + |
| 42 | +// Calculate the average of the numbers in the array |
| 43 | +Array.prototype.average = function () { |
| 44 | + if (this.length === 0) return NaN; |
| 45 | + return this.sum() / this.length; |
| 46 | +}; |
| 47 | + |
| 48 | +// Sum up all numbers in the array |
| 49 | +Array.prototype.sum = function () { |
| 50 | + return this.reduce((acc, num) => acc + num, 0); |
| 51 | +}; |
| 52 | + |
| 53 | +// Get all even numbers from the array |
| 54 | +Array.prototype.even = function () { |
| 55 | + return this.filter((num) => num % 2 === 0); |
| 56 | +}; |
| 57 | + |
| 58 | +// Get all odd numbers from the array |
| 59 | +Array.prototype.odd = function () { |
| 60 | + return this.filter((num) => num % 2 !== 0); |
| 61 | +}; |
| 62 | + |
| 63 | +let numbers = [1, 2, 3, 4, 5]; |
| 64 | + |
| 65 | +console.log(numbers.square()); // [1, 4, 9, 16, 25] |
| 66 | +console.log(numbers.cube()); // [1, 8, 27, 64, 125] |
| 67 | +console.log(numbers.average()); // 3 |
| 68 | +console.log(numbers.sum()); // 15 |
| 69 | +console.log(numbers.even()); // [2, 4] |
| 70 | +console.log(numbers.odd()); // [1, 3, 5] |
| 71 | +``` |
0 commit comments