Last active
August 29, 2015 14:25
-
-
Save sryze/3426a0faadff8bcb38a8 to your computer and use it in GitHub Desktop.
Project Euler in JavaScript
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
var END_OF_WORLD = 'undefined'; | |
function nextNumber(n) { | |
return n + 1; | |
} | |
function numbers(base) { | |
var n = base; | |
return function() { | |
return (n = nextNumber(n)); | |
}; | |
} | |
function forEach(seq, fn) { | |
var n = 0; | |
while ((n = seq()) !== END_OF_WORLD) { | |
if (fn(n) === false) { | |
break; | |
} | |
} | |
} | |
function takeWhile(seq, pred) { | |
return function() { | |
var n = seq(); | |
return pred(n) ? n : END_OF_WORLD; | |
}; | |
} | |
function filter(seq, pred) { | |
return function() { | |
var n; | |
while ((n = seq()) != END_OF_WORLD) { | |
if (pred(n)) { | |
return n; | |
} | |
} | |
return END_OF_WORLD; | |
}; | |
} | |
function sum(seq) { | |
var result = 0; | |
forEach(seq, function(n) { | |
result += n; | |
}); | |
return result; | |
} | |
console.log( | |
sum( | |
filter( | |
takeWhile(numbers(1), function(n) { | |
return n < 1000; | |
}), | |
function(n) { | |
return n % 3 == 0 || n % 5 == 0; | |
} | |
) | |
) | |
); |
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
var END_OF_WORLD = 'undefined'; | |
function sequence(base, next) { | |
var n = base; | |
return function() { | |
var result = n; | |
n = next(n); | |
return result; | |
}; | |
} | |
function fibonacci(p) { | |
return [p[1], p[0] + p[1]]; | |
} | |
function forEach(seq, fn) { | |
var n = 0; | |
while ((n = seq()) !== END_OF_WORLD) { | |
if (fn(n) === false) { | |
break; | |
} | |
} | |
} | |
function takeWhile(seq, pred) { | |
return function() { | |
var n = seq(); | |
return pred(n) ? n : END_OF_WORLD; | |
}; | |
} | |
function filter(seq, pred) { | |
return function() { | |
var n; | |
while ((n = seq()) != END_OF_WORLD) { | |
if (pred(n)) { | |
return n; | |
} | |
} | |
return END_OF_WORLD; | |
}; | |
} | |
function map(seq, fn) { | |
return function() { | |
return fn(seq()); | |
}; | |
} | |
function sum(seq) { | |
var result = 0; | |
forEach(seq, function(n) { | |
result += n; | |
}); | |
return result; | |
} | |
console.log( | |
sum( | |
filter( | |
takeWhile( | |
map( | |
sequence([1, 2], fibonacci), | |
function(p) { | |
return p[0]; | |
} | |
), | |
function(n) { | |
return n < 4000000; | |
} | |
), | |
function(n) { | |
return n % 2 === 0; | |
} | |
) | |
) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment