Created
August 23, 2018 06:47
-
-
Save jptcnde/7fa50b7c85889b8ca9b2505138407801 to your computer and use it in GitHub Desktop.
crockford-exercises - functional programming
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
/* | |
* This is a JavaScript Scratchpad. | |
* | |
* Enter some JavaScript, then Right Click or choose from the Execute Menu: | |
* 1. Run to evaluate the selected text (Ctrl+R), | |
* 2. Inspect to bring up an Object Inspector on the result (Ctrl+I), or, | |
* 3. Display to insert the result in a comment after the selection. (Ctrl+L) | |
*/ | |
function identityf(x) { | |
return function() { | |
return x; | |
} | |
} | |
function add(x, y) { | |
return x + y; | |
} | |
function mul(x, y) { | |
return x * y; | |
} | |
function addf(x) { | |
return function(y) { | |
return x + y; | |
} | |
} | |
// addf(3)(4) | |
function applyf(f) { | |
return function (x) { | |
return function (y) { | |
return f(x, y) | |
} | |
} | |
} | |
// applyf(add)(3)(5) | |
// var mulf = applyf(mul) | |
// mulf(2)(8) | |
function curry(f, x) { | |
return function (y) { | |
return f(x, y) | |
} | |
} | |
// curry(mul, 5)(6) | |
function methodize(f) { | |
return function (x) { | |
return f(this, x) | |
} | |
} | |
// Number.prototype.add = methodize(add); | |
// (3).add(4) | |
function demethodize(f) { | |
return function (x, y) { | |
return f.call(x, y) | |
} | |
} | |
// Number.prototype.add = methodize(add); | |
// demethodize(Number.prototype.add)(5, 6) | |
function twice(f) { | |
return function(x) { | |
return f(x, x) | |
} | |
} | |
var double = twice(add); | |
var square = twice(mul); | |
// double(11) | |
// 22 | |
function composeu(f, g) { | |
return function(a) { | |
return g(f(x)) | |
} | |
} | |
// composeu(double, square)(3) | |
/* | |
36 | |
*/ | |
function composeb(f, g) { | |
return function(x, y, z) { | |
return g(f(x, y), z) | |
} | |
} | |
// composeb(add, mul)(2,3,5) | |
/* | |
25 | |
*/ | |
// function once(f) { | |
// var called = false; | |
// return function (x, y) { | |
// if (called) { | |
// throw Error('throw!') | |
// } | |
// called = true; | |
// return f(x,y); | |
// } | |
// } | |
// better approach | |
function once(func) { | |
return function() { | |
var f = func; | |
func = null; | |
return f.apply(this, arguments) | |
} | |
} | |
// add_once = once(add); | |
// add_once(3,4) | |
// add_once(3,4) | |
function counterf(x) { | |
return { | |
inc: function() { | |
return x++; | |
}, | |
dec: function() { | |
return x--; | |
} | |
} | |
} | |
// var counter = counterf(10); | |
// counter.inc(); | |
// counter.dec(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment