-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
82 lines (74 loc) · 2.27 KB
/
index.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*!
* handle-arguments <https://github.com/hybridables/handle-arguments>
*
* Copyright (c) 2015-2016 Charlike Mike Reagent <@tunnckoCore> (http://www.tunnckocore.tk)
* Released under the MIT license.
*/
'use strict'
var utils = require('./utils')
/**
* > Get separately non-callback arguments in `.arguments`, and
* the last function if it [is-callback-function][] in `.callback`.
* Signature is like [sliced][], it works almost the same way, but returns object
* with `.arguments` and `.callback` properties.
*
* **Example**
*
* ```js
* var handle = require('handle-arguments')
*
* function fixture () {
* return handle(arguments)
* }
*
* function cb () {}
* function noop () {}
*
* console.log(fixture(1, 2, 3, 4).arguments) // => [1, 2, 3, 4]
* console.log(fixture(1, 2, 3, 4).callback) // => false
*
* console.log(fixture(1, 2, cb).arguments) // => [1, 2]
* console.log(fixture(1, 2, cb).callback) // => [Function: cb]
*
* console.log(fixture(1, 2, noop).arguments) // => [1, 2, noop]
* console.log(fixture(1, 2, noop).callback) // => false
*
* // treat functions named `noop` or `foo` as callback
* function fn () {
* return handle(arguments, ['foo', 'noop'])
* }
*
* console.log(fn(1, 2, 3, noop).arguments) // => [1, 2, 3]
* console.log(fn(1, 2, 3, noop).callback) // => [Function: noop]
* ```
*
* @param {Array|Arguments} `argz` Arguments object or array to eat.
* @param {Array|Number} `names` If array directly passed to [is-callback-function][], otherwise to [sliced][].
* @param {Number} `index` Passed directly to [sliced][] if `number`.
* @return {Object}
* @api public
*/
module.exports = function handleArguments (argz, names, index) {
argz = utils.arrayify(argz)
var args = null
var nameNum = utils.isNumber(names)
var idxNum = utils.isNumber(index)
if (nameNum && !idxNum) {
args = utils.slice(argz, names)
names = false
} else if (nameNum && idxNum) {
args = utils.slice(argz, names, index)
} else {
args = utils.slice(argz)
}
var last = args[args.length - 1]
last = typeof last === 'function' ? last : function noop () {}
last = utils.isCallback(last, names) ? last : false
args = last ? utils.slice(args, 0, -1) : args
return {
callback: last,
cb: last,
arguments: args,
args: args
}
}