ambi
Version:
Ambi lets you execute any function ambidextrously; providing you the ability to execute any function (be it synchronous, asynchronous, returns, callbacks, promises) as if it returned a promise.
97 lines (96 loc) • 3.51 kB
JavaScript
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
// Import
var typechecker_1 = require("typechecker");
// Handle success case
function onSuccess(value) {
// Reject if an error was returned
if ((0, typechecker_1.isError)(value))
return Promise.reject(value);
// Success case, so return the value
return value;
}
/**
* Ambidextrously execute the method with the passed arguments.
* If method.length > args.length, then ambi provides the method with a completion callback as the last expected argument.
* @param method A method, that can either resolve synchronously, via a promise, or via a callback.
* @param args The arguments to provide the function.
* @returns The determined result.
*/
function ambi(method) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
/*
Different ways functions can be called:
ambi(function(a,next){next(null, a)}, a)
> method.length > args.length
> next will be provided automatically
ambi(function(a){return a}, a)
> method.length = args.length
> no argument changes by ambi
ambi(function(a){return a}, a, b)
> method.length < args.length
> no argument changes by ambi
*/
try {
// Inject a completion callback
if (method.length > args.length) {
return new Promise(function (resolve, reject) {
var xargs = args
.slice()
// add the difference as undefined values
.concat(new Array(method.length - args.length - 1))
// add the completion callback
.concat([
function ambiCallback(err) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
if (err)
return reject(err);
if (args.length === 1)
return resolve(args[0]);
return resolve(args);
},
]);
method.apply(void 0, __spreadArray([], __read(xargs), false));
}).then(onSuccess);
}
// Execute without a completion callback
else {
return Promise.resolve(method.apply(void 0, __spreadArray([], __read(args), false))).then(onSuccess);
}
}
catch (err) {
return Promise.reject(err);
}
}
exports.default = ambi;
;