Last active
February 2, 2017 11:04
-
-
Save anler/24810b05cd5eb7514b8e7c0cce08a83e to your computer and use it in GitHub Desktop.
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
function getFourInARow(numbers) { | |
var xs = partitionEvery(4, numbers); | |
var transducer = compose( | |
mapping(calcProduct), | |
updateIn("maxProduct", max2), | |
updateIn("avg", avg2(xs.length)) | |
); | |
var result = xs.reduce(transducer(id), { maxProduct: 0, avg: 0 }); | |
return result.maxProduct - result.avg | |
} | |
// the magic... | |
function compose(...fs) { | |
return fs.reduce(function(f, g) { | |
return function(input) { | |
return f(g(input)); | |
}; | |
}); | |
} | |
function mapping(f) { | |
return function(task) { | |
return function(acc, x) { | |
return task(acc, f(x)); | |
}; | |
}; | |
} | |
function updateIn(field, f) { | |
return function(task) { | |
return function(acc, x) { | |
acc[field] = f(acc[field], x); | |
return task(acc, x); | |
}; | |
}; | |
} | |
function id(x) { return x; } | |
function max2(x, y) { return x >= y ? x : y; } | |
function avg2(total) { | |
return function(x, y) { | |
if (x === 0) | |
return y / total; | |
else | |
return x + y / total; | |
} | |
} | |
function multiply2(a, b) { return a * parseInt(b); } | |
function calcProduct(xs) { return xs.split("").reduce(multiply2); } | |
function partitionEvery(n, numbers) { | |
var adjacents = []; | |
while (true) { | |
if (numbers.length <= 4) { | |
adjacents.push(numbers); | |
break; | |
} else { | |
adjacents.push(numbers.slice(0, n)); | |
numbers = numbers.slice(1); | |
} | |
} | |
return adjacents; | |
} | |
// console.log(getFourInARow("12345678987654321")); // =>2592 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment