Created
August 26, 2013 16:09
-
-
Save squaremo/6343228 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
// Convert a promise-oriented API into a callback-oriented API | |
function identity(x) { return x; } | |
function slice(arrayish, arg1, arg2) { | |
return Array.prototype.slice.call(arrayish, arg1, arg2); | |
} | |
// Makes a transformer from promise-returning functions to | |
// callback-accepting functions. | |
function to_cb_accepting_fn(transform) { | |
transform = transform || identity; | |
return function(proc) { | |
function f(self) { | |
return function(/* args..., callback*/) { | |
var callback = arguments[arguments.length - 1]; | |
proc.apply(self, slice(arguments, 0, -1)) | |
.then(function(value) { | |
callback(null, transform(value)); | |
}, callback); | |
}; | |
} | |
var func = f(proc); | |
func.as_property_of = f; | |
return func; | |
}; | |
} | |
// Makes a transformer that takes functions returning values to | |
// functions returning transformed values. Used when you want to | |
// transform return values into something unpromisified. | |
function to_plain_func(transform) { | |
// NB in principle, if there's no transform, our function ought to | |
// just return the procedure itself; however, because of the way | |
// I've done methods (`as_property_of`), I need to cons a fresh | |
// closure to return. | |
transform = transform || identity; | |
return function(proc) { | |
function f(self) { | |
return function(/* , args... */) { | |
return transform(proc.apply(self, arguments)); | |
}; | |
} | |
var func = f(proc); | |
func.as_property_of = f; | |
return func; | |
}; | |
} | |
// Makes a transformer from objects to objects; the transformed | |
// objects are built according to the spec given, which puts | |
// transformers againsts property names. | |
function object(spec) { | |
var keys = Object.keys(spec); | |
var len = keys.length; | |
return function(obj) { | |
var res = {_original: obj}; // original included for debugging | |
for (var i=0; i < len; i++) { | |
var k = keys[i]; | |
res[k] = spec[k](obj[k]).as_property_of(obj); | |
} | |
return res; | |
}; | |
} | |
module.exports.func = to_cb_accepting_fn; | |
module.exports.plain_func = to_plain_func; | |
module.exports.object = object; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment