Last active
June 28, 2016 01:48
-
-
Save proudlygeek/2264386c44cade0e2ab7 to your computer and use it in GitHub Desktop.
Curry Callbacks
This file contains hidden or 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 callbackCurry(callbacks) { | |
var memoize = function memoize(xs) { | |
if (!xs.length) return null; | |
var tail = xs.slice(1), | |
head = xs[0]; | |
return head.bind(undefined, memoize(tail)); | |
}; | |
var curried = memoize(callbacks); | |
return curried(); | |
} | |
var Users = { | |
findByScreenName: function(name, cb) { | |
return cb({ | |
id: 12, | |
name: name | |
}); | |
}, | |
getProfile: function(id, cb) { | |
return cb({ | |
id: id, | |
name: 'Gianluca', | |
last: 'Bargelli', | |
age: 29 | |
}); | |
} | |
}; | |
var expected = { | |
id: 12, | |
name: 'Gianluca', | |
last: 'Bargelli', | |
age: 29 | |
}; | |
Test.describe('Callback hell'); | |
var profile = Users.findByScreenName('Gianluca', function(user) { | |
return Users.getProfile(user.id, function(profile) { | |
return profile; | |
}); | |
}); | |
Test.deepEquals(profile, expected); | |
Test.describe('Curry functions'); | |
var profileCurry = callbackCurry([ | |
function(next) { | |
return Users.findByScreenName('Gianluca', next); | |
}, | |
function(next, user) { | |
return Users.getProfile(user.id, next); | |
}, | |
function(next, profile) { | |
return profile; | |
} | |
]); | |
Test.deepEquals(profileCurry, expected); |
This file contains hidden or 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
// | |
// Simple assertion object (useful for testing functions). | |
// | |
var Test = { | |
describe: function(label) { | |
console.log('\n%s', label); | |
}, | |
equals: function(sut, expect) { | |
(sut === expect) | |
? console.log('\t%c ✓ ' + expect, 'color: green') | |
: console.log('\t%c ✗ ' + sut + ' !== ' + expect, 'color: red'); | |
}, | |
deepEquals: function(sut, expect) { | |
for (var key in expect) { | |
if (typeof sut === 'undefined' || !sut[key] || sut[key] !== expect[key]) { | |
console.log('\t%c ✗ ' + JSON.stringify(sut) + ' !== ' + JSON.stringify(expect), 'color: red'); | |
return; | |
} | |
} | |
console.log('\t%c ✓ ' + JSON.stringify(expect), 'color: green'); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment