I wanted to practice functional programming (fp) without using any library but using vanilla JS only. So I took a problem from project euler:
The sum of the squares of the first ten natural numbers is,
12 + 22 + … + 102 = 385 The square of the sum of the first ten natural numbers is,
(1 + 2 + … + 10)2 = 552 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
My solution in FP:
/*jshint esversion: 6*/ (function () { 'use strict'; const range = f => num => Array.from(new Array(num), f); const quadRange = range((_, i) => (i + 1) * (i + 1)); const simpRange = range((_, i) => i + 1); const sum = (acc, val) => acc + val; const sumOfQuads = quadRange(100) .reduce(sum); const quadsOfSum = simpRange(100) .reduce(sum) * simpRange(100) .reduce(sum); console.log("solution ", quadsOfSum - sumOfQuads); })();
Is there a better way to write it in FP (without any libraries and with vanilla JS only)?