-
Notifications
You must be signed in to change notification settings - Fork 0
/
last-callback.js
51 lines (48 loc) · 1.31 KB
/
last-callback.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* Last callback selects last passed argument.
* If this last argument is a function, it will be invoke with
* given context, and arguments.
*
* Last callback returns safe function ready to call.
* Basically last-callback it's a wrapper around your callback function.
*
* @module last-callback
* @author Paweł Zadrożny <[email protected]> (https://pawelzny.com/)
* @copyright Paweł Zadrożny 2016
* @license MIT
* @version 2.0.1
*
* @example
* const callback = lastCallback(...arguments); // set callback
* callback(...arguments); // invoke callback with arguments
*
* @returns {Function} callback wrapper
*/
'use strict';
module.exports = lastCallback;
/**
* Extract last argument and check if is callable.
* If so, create inner callback function which apply all arguments for callback.
*
* If last argument is not callable, inner callback will provide empty callable vessel.
* @param {*} args
*
* @returns {function} callback
*/
function lastCallback (...args) {
let last = args.pop();
/**
* Callable vessel.
*
* @this allow to pass context from caller to callback.
* @param {*} args
*
* @returns {*}
*/
function callback (...args) {
if (typeof last === 'function') {
return last.apply(this, args);
}
}
return callback;
}