Files
30-seconds-of-code/snippets/sumPower.md
Mathias Bynens 8ee50178f3 Avoid confusing prototype methods for static methods
Correct: `Array.from()` (it’s a static method)
Incorrect: `Array.join()` (doesn’t exist; it’s a prototype method)

This patch uses the common `#` syntax to denote `.prototype.`.
2018-09-28 15:44:12 -04:00

22 lines
721 B
Markdown

### sumPower
Returns the sum of the powers of all the numbers from `start` to `end` (both inclusive).
Use `Array.prototype.fill()` to create an array of all the numbers in the target range, `Array.prototype.map()` and the exponent operator (`**`) to raise them to `power` and `Array.prototype.reduce()` to add them together.
Omit the second argument, `power`, to use a default power of `2`.
Omit the third argument, `start`, to use a default starting value of `1`.
```js
const sumPower = (end, power = 2, start = 1) =>
Array(end + 1 - start)
.fill(0)
.map((x, i) => (i + start) ** power)
.reduce((a, b) => a + b, 0);
```
```js
sumPower(10); // 385
sumPower(10, 3); //3025
sumPower(10, 3, 5); //2925
```