Extract function's last argument and wrap with ready to invoke function. If last argument is callable, hence callback - wrapper will invoke it. Otherwise invoked wrapper do nothing.
Last callback provides callable wrapper for last argument. There is no need for further checking if last argument is callable.
Wrapping works for infinite number of arguments even undeclared one.
NodeJS >= 8.9.0
Version for browsers is compatible with ES5.
with NPM:
npm install -S last-callback
For older NodeJS
npm install -S last-callback@1.0.3
Scenario: There is "execute" function which expect last argument to be optional callback.
const lastCallback = require('last-callback');
function execute(x, y, cb=null) {
// 'arguments' is magic variable always visible inside function.
let callback = lastCallback(...arguments);
let sum = x + y;
callback(sum);
return sum;
}
execute(10, 34, (result) => console.log(result));
Scenario: There is "make" function which allow callback as last argument.
TIP Undeclared arguments will NOT be visible for debugger and IDE inspection.
const lastCallback = require('last-callback');
function make(x, y, z) {
// 'arguments' is magic variable always visible inside function.
let callback = lastCallback(...arguments);
let result = (x + y) * z;
callback(result);
return result;
}
// make declared 3 arguments: 'x', 'y' and 'z'
// but passing fourth argument is completely legal
// and JS will not complain.
execute(10, 34, 5, (result) => console.log(result));
Scenario: There is 'execute' function which expect callback. There is also 'spy' object, which alter callback context.
const lastCallback = require('last-callback');
function returnSecret(secret) {
if (this.secret === undefined) {
this.secret = secret;
}
return this.secret;
}
// returns 'secret' without change
function execute(secret, cb) {
return lastCallback(...arguments)(secret);
}
// returns 'secret' from different context
function executeContext(secret, context, cb) {
return lastCallback(...arguments).call(context);
}
secretPassword = 'I am real secret';
// will return 'I am real secret'
execute(secretPassword, returnSecret);
// will return 'Luke I am your father'
executeContext(secretPassword, {secret: 'Luke I am your father'}, returnSecret);
Scenario: There is a 'execute' function which expected callback. The callback will be recursive.
const lastCallback = require('last-callback');
function recursiveCb (n, t) {
if (n < t) {
console.log(n)
recursiveCb(n + 1, t);
}
}
function execute(start, stop, cb) {
lastCallback(...arguments)(start, stop);
}
execute(0, 5, recursiveCb);
// console log result:
// 0
// 1
// 2
// 3
// 4
Did you find any bugs?
Maybe this documentation has language mistakes?
You have idea for great new feature?
Create new issue and describe your point of view. I will do my best to meet all requests.
This repository is open for changes and suggestions. I encourage you to write your own solution and make pull request.
The MIT License (MIT) Copyright (c) 2016 Paweł Zadrożny