Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80742 views
1
var bindCallback = require('../internal/bindCallback');
2
3
/** Native method references. */
4
var floor = Math.floor;
5
6
/* Native method references for those with the same name as other `lodash` methods. */
7
var nativeIsFinite = global.isFinite,
8
nativeMin = Math.min;
9
10
/** Used as references for the maximum length and index of an array. */
11
var MAX_ARRAY_LENGTH = 4294967295;
12
13
/**
14
* Invokes the iteratee function `n` times, returning an array of the results
15
* of each invocation. The `iteratee` is bound to `thisArg` and invoked with
16
* one argument; (index).
17
*
18
* @static
19
* @memberOf _
20
* @category Utility
21
* @param {number} n The number of times to invoke `iteratee`.
22
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
23
* @param {*} [thisArg] The `this` binding of `iteratee`.
24
* @returns {Array} Returns the array of results.
25
* @example
26
*
27
* var diceRolls = _.times(3, _.partial(_.random, 1, 6, false));
28
* // => [3, 6, 4]
29
*
30
* _.times(3, function(n) {
31
* mage.castSpell(n);
32
* });
33
* // => invokes `mage.castSpell(n)` three times with `n` of `0`, `1`, and `2`
34
*
35
* _.times(3, function(n) {
36
* this.cast(n);
37
* }, mage);
38
* // => also invokes `mage.castSpell(n)` three times
39
*/
40
function times(n, iteratee, thisArg) {
41
n = floor(n);
42
43
// Exit early to avoid a JSC JIT bug in Safari 8
44
// where `Array(0)` is treated as `Array(1)`.
45
if (n < 1 || !nativeIsFinite(n)) {
46
return [];
47
}
48
var index = -1,
49
result = Array(nativeMin(n, MAX_ARRAY_LENGTH));
50
51
iteratee = bindCallback(iteratee, thisArg, 1);
52
while (++index < n) {
53
if (index < MAX_ARRAY_LENGTH) {
54
result[index] = iteratee(index);
55
} else {
56
iteratee(index);
57
}
58
}
59
return result;
60
}
61
62
module.exports = times;
63
64