Last active
May 9, 2016 20:30
-
-
Save JimOKelly/e82959b0c2039d54cc412ca75e44b68b to your computer and use it in GitHub Desktop.
This is how I would solve euler 1 without resulting to passing functions to functions (beginner code)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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. | |
if (typeof(Array.prototype.flatMap) != "function") { | |
// warning, we are mutating the actual base prototype for Array here | |
Array.prototype.flatMap = function(fn) { | |
return Array.prototype.concat.apply([], this.map(fn)); | |
}; | |
} | |
var sumMultiplesOf3and5 = (function() { | |
var naturalNumbers = function(from, to) { | |
var nums = []; | |
for(var i=from; i < to; i++) { | |
nums.push(i); | |
}; | |
return nums; | |
}; | |
var multiplesOf = function(multiples, nums) { | |
return multiples.flatMap(function(multiple) { | |
return nums.filter(function(num) { | |
return num % multiple == 0; | |
}); | |
}); | |
}; | |
var sum = function(nums) { | |
return nums.reduce(function(acc, num) { return num + acc }); | |
}; | |
var sumMultiplesOf3and5 = function(from, to) { | |
return sum(multiplesOf([3,5], naturalNumbers(from, to))); | |
} | |
return { | |
call: sumMultiplesOf3and5, | |
}; | |
}()); | |
console.log(sumMultiplesOf3and5.call(1, 10)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment