I wanted to practice functional programming (fp) without using any library. So I took the 1st problem from project euler:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
My solution in fp looks like this:
const isDivisibleBy = i => number => i % number === 0;
const selected = criteria => (...numbers) => i => numbers.filter(criteria(i))
.length > 0;
const getSumOf = conditionFor => (sum, _, i) => conditionFor(i) ? sum + i :
sum;
const solution = Array(1000)
.fill()
.reduce(getSumOf(selected(isDivisibleBy)(3, 5)), 0);
I have questions regarding efficiency and parametization:
Is there a more efficient way to write the function
selected
that is still functional? Because right now the filter functions runs through all elements ofnumbers
- even if it finds an element that is not divisible for the given condition. Also.length > 0
makes it look like a hack. Is there a more declarative way?I assume
getSumOf
can't be refactored any more?