-
Notifications
You must be signed in to change notification settings - Fork 0
/
underbar.js
568 lines (439 loc) · 13.7 KB
/
underbar.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
'use strict';
// _.identity(value)
//
// Returns the same value that is used as the argument. In math: `f(x) = x`
//
// This function looks useless, but is used throughout Underscore as a default iteratee.
//
// var stooge = {name: 'moe'};
// stooge === _.identity(stooge);
// => true
exports.identity = function (value) {
if (arguments.length === 0) {
throw new Error('Invalid Argument');
}
return value;
};
// _.first(array, [n])
//
// Returns the first element of an array. Passing n will return the first n elements of the array.
//
// _.first([5, 4, 3, 2, 1]);
// => 5
exports.first = function (array, length) {
if (!Array.isArray(array)) {
throw new Error('Invalid Parameter');
}
array = array.slice();
if (length > 1) {
var elements = [];
length = length > array.length ? array.length : length;
for (var i = 0; i < length; i++) {
elements.push(array.shift());
}
return elements;
}
return array.shift();
};
// _.last(array, [n])
//
// Returns the last element of an array. Passing n will return the last n elements of the array.
//
// _.last([5, 4, 3, 2, 1]);
// => 1
exports.last = function (array, length) {
if (!Array.isArray(array)) {
throw new Error('Invalid Parameter');
}
array = array.slice();
if (length > 1) {
var elements = [];
length = length > array.length ? array.length : length;
for (var i = 0; i < length; i++) {
elements.push(array.pop());
}
return elements;
}
return array.pop();
};
// _.each(list, iteratee, [context])
//
// Iterates over a list of elements, yielding each in turn to an iteratee function.
// The iteratee is bound to the context object, if one is passed. Each invocation
// of iteratee is called with three arguments: (element, index, list). If list is a
// JavaScript object, iteratee's arguments will be (value, key, list).
// Returns the list for chaining.
//
// _.each([1, 2, 3], alert);
// => alerts each number in turn...
// _.each({one: 1, two: 2, three: 3}, alert);
// => alerts each number value in turn...
exports.each = function (list, cb) {
if (Array.isArray(list)) {
for (var i = 0; i < list.length; i++) {
cb(list[i], i, list);
}
} else if (typeof list === 'object') {
for (var key in list) {
cb(list[key], key, list);
}
}
};
// _.indexOf(array, value)
//
// Returns the index at which value can be found in the array, or -1 if value
// is not present in the array.
//
// _.indexOf([1, 2, 3], 2);
// => 1
exports.indexOf = function (array, value) {
if (!Array.isArray(array)) {
throw new Error('Collection must be an array.');
}
var position = -1;
for (var i = 0; i < array.length; i++) {
if (array[i] === value) {
position = i;
break;
}
}
return position;
};
// _.filter(collection, predicate)
//
// Looks through each value in the list, returning an array of all the values
// that pass a truth test (predicate).
//
// var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
// => [2, 4, 6]
exports.filter = function (collection, predicate) {
return this._filter(collection, predicate, 'filter');
};
// _.reject(list, predicate)
//
// Returns the values in list without the elements that the truth test (predicate)
// passes. The opposite of filter.
//
// var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
// => [1, 3, 5]
exports.reject = function (collection, predicate) {
return this._filter(collection, predicate, 'reject');
};
exports._filter = function (collection, predicate, operation) {
var filteredCollection = [];
var test;
this.each(collection, function (item) {
test = predicate(item);
test = (operation === 'filter') ? test : !test;
if (test) {
filteredCollection.push(item);
}
});
return filteredCollection;
};
// _.uniq(array)
//
// Produces a duplicate-free version of the array, using === to test object equality.
// In particular only the first occurence of each value is kept.
//
// _.uniq([1, 2, 1, 4, 1, 3]);
// => [1, 2, 4, 3]
exports.uniq = function (collection) {
if (!Array.isArray(collection)) {
throw new Error('Collection must be an array.');
}
var uniq = [];
this.each(collection, function (item, index, collection) {
if (uniq.indexOf(item) === -1) {
uniq.push(item);
}
});
return uniq;
};
// _.map(list, iteratee)
//
// Produces a new array of values by mapping each value in list through
// a transformation function (iteratee). The iteratee is passed three arguments:
// the value, then the index (or key) of the iteration, and finally a reference
// to the entire list.
//
// _.map([1, 2, 3], function(num){ return num * 3; });
// => [3, 6, 9]
//
// _.map({one: 1, two: 2, three: 3}, function(num, key){ return num * 3; });
// => [3, 6, 9]
//
// _.map([[1, 2], [3, 4]], _.first);
// => [1, 3]
exports.map = function (collection, iteratee) {
var mappedArray = [];
this.each(collection, function (item, index, list) {
mappedArray.push(iteratee(item, index, list));
});
return mappedArray;
};
// _.pluck(list, propertyName)
//
// A convenient version of what is perhaps the most common use-case for map:
// extracting a list of property values.
//
// var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
// _.pluck(stooges, 'name');
// => ["moe", "larry", "curly"]
exports.pluck = function (collection, propertyName) {
var pluckedArray = [];
this.each(collection, function (item, index, list) {
pluckedArray.push(item[propertyName]);
});
return pluckedArray;
};
// _.reduce(list, iteratee, [memo], [context])
//
// Also known as inject and foldl, reduce boils down a list of values into a single value.
// Memo is the initial state of the reduction, and each successive step of it should be
// returned by iteratee. The iteratee is passed four arguments: the memo, then the value
// and index (or key) of the iteration, and finally a reference to the entire list.
//
// If no memo is passed to the initial invocation of reduce, the iteratee is not invoked
// on the first element of the list. The first element is instead passed as the memo in
// the invocation of the iteratee on the next element in the list.
//
// var sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0);
// => 6
exports.reduce = function (list, iteratee, memo) {
var copiedList = list.slice();
if (typeof memo === 'undefined') {
memo = copiedList.shift();
}
this.each(copiedList, function (item, index) {
memo = iteratee(memo, item, index, list);
});
return memo;
};
// _.contains(list, value)
//
// Returns true if the value is present in the list.
//
// _.contains([1, 2, 3], 3);
// => true
exports.contains = function (list, value) {
if (typeof list !== 'object' || list === null) {
throw new Error('Invalid argument');
}
var found = false;
this.each(list, function (item, index) {
if (item === value) {
found = true;
}
});
return found;
};
// _.every(list, [predicate], [context])
//
// Returns true if all of the values in the list pass the predicate truth test.
// _.every([2, 4, 5], function(num) { return num % 2 == 0; });
// => false
exports.every = function (collection, predicate) {
if (typeof collection !== 'object' || collection === null) {
throw new Error('Invalid argument');
}
var test;
this.each(collection, function (item, index, list) {
if (typeof test !== undefined && test === false) {
return;
}
test = predicate(item, index, list) ? true : false;
});
return test;
};
// _.some(list, [predicate])
//
// Returns true if any of the values in the list pass the predicate truth test.
// _.some([null, 0, 'yes', false]);
// => true
exports.some = function (collection, predicate) {
if (typeof collection !== 'object' || collection === null) {
throw new Error('Invalid Argument');
}
var test;
this.each(collection, function (item, index, list) {
if (test) {
return;
}
test = predicate(item, index, list) ? true : false;
});
return test;
};
// _.extend(destination, *sources)
//
// Copy all of the properties in the source objects over to the destination object,
// and return the destination object. It's in-order, so the last source will
// override properties of the same name in previous arguments.
// _.extend({name: 'moe'}, {age: 50});
// => {name: 'moe', age: 50}
exports.extend = function () {
var args = Array.prototype.slice.call(arguments);
var destination = args[0];
var sources = args.slice(1);
validateArgument(destination);
this.each(sources, function (item) {
if (item !== undefined) {
validateArgument(item);
}
});
var self = this;
this.each(sources, function (item) {
self.each(item, addProperty);
});
function addProperty (value, index) {
destination[index] = value;
}
function validateArgument (item) {
if (typeof item !== 'object' || Array.isArray(item) || item === null) {
throw new Error('Invalid argument');
}
}
return destination;
};
// _.defaults(object, defaults)
//
// Fill in undefined properties in object with the first value present in
// the following list of defaults objects.
// var iceCream = {flavor: "chocolate"};
// _.defaults(iceCream, {flavor: "vanilla", sprinkles: "lots"});
// => {flavor: "chocolate", sprinkles: "lots"}
exports.defaults = function (sourceObj, defaultsObj) {
validateArgument(sourceObj);
validateArgument(defaultsObj);
this.each(defaultsObj, function (item, key, collection) {
if (!sourceObj[key]) {
sourceObj[key] = defaultsObj[key];
}
});
return sourceObj;
function validateArgument (param) {
if (typeof param !== 'object' || Array.isArray(param) || param === null) {
throw new Error('Invalid argument');
}
}
};
// _.once(function)
//
// Creates a version of the function that can only be called one time.
// Repeated calls to the modified function will have no effect, returning
// the value from the original call. Useful for initialization functions,
// instead of having to set a boolean flag and then check it later.
// var initialize = _.once(createApplication);
// initialize();
// initialize();
// Application is only created once.
exports.once = function (fn) {
if (typeof fn !== 'function') {
throw new Error('Invalid Argument. It must be a function!');
}
var called = false;
return function () {
var args = Array.prototype.slice.call(arguments);
if (!called) {
fn.apply(this, args);
called = true;
}
};
};
// _.memoize(function)
//
// Memoizes a given function by caching the computed result. Useful for
// speeding up slow-running computations. The cache of memoized values
// is available as the cache property on the returned function.
// var fibonacci = _.memoize(function(n) {
// return n < 2 ? n: fibonacci(n - 1) + fibonacci(n - 2);
// });
exports.memoize = function (fn) {
if (typeof fn !== 'function') {
throw new Error('Invalid Argument. It must be a function!');
}
var self = this;
memoizedFunction.cache = {};
return memoizedFunction;
function memoizedFunction () {
var args = Array.prototype.slice.call(arguments);
var hash = getHash(args);
var cache = memoizedFunction.cache;
return (cache[hash] = cache[hash] ? cache[hash] : fn.apply(self, args));
}
function getHash (args) {
var argsArray = args.slice();
var hash = '';
var stringifiedArgument;
self.each(argsArray, function (argument, index, collection) {
stringifiedArgument = stringifyArgument(argument);
hash += isLast(index, collection) ? stringifiedArgument : stringifiedArgument + ', ';
});
return hash;
}
function stringifyArgument (argument) {
var stringifiedArgument;
if (typeof argument === 'object' && !Array.isArray(argument) && argument !== null) {
var stringifiedObject = {};
for (var key in argument) {
stringifiedObject[key] = stringifyArgument(argument[key]);
}
stringifiedArgument = JSON.stringify(stringifiedObject);
}
else if (Array.isArray(argument)) {
stringifiedArgument = JSON.stringify(argument);
}
else {
stringifiedArgument = argument += '';
}
return stringifiedArgument;
}
function isLast (index, collection) {
return index === collection.length - 1;
}
};
// _.delay(function, wait, *arguments)
//
// Much like setTimeout, invokes function after wait milliseconds.
// If you pass the optional arguments, they will be forwarded on to
// the function when it is invoked.
// var log = _.bind(console.log, console);
// _.delay(log, 1000, 'logged later');
// => 'logged later' // Appears after one second.
exports.delay = function () {
var args = Array.prototype.slice.call(arguments);
var callback = args.shift();
var delay = args.shift();
var self = this;
if (typeof callback !== 'function' || typeof delay !== 'number') {
throw new Error('Invalid argument');
}
setTimeout(function () {
callback.apply(this, args);
}, delay);
};
// _.shuffle(list)
//
// Returns a shuffled copy of the list, using a version of the Fisher-Yates shuffle.
// _.shuffle([1, 2, 3, 4, 5, 6]);
// => [4, 1, 6, 3, 5, 2]
exports.shuffle = function (list) {
if (!Array.isArray(list)) {
throw new TypeError('Invalid argument');
}
return fisherYatesShuffle(list.slice());
function fisherYatesShuffle (list) {
var currentIndex = list.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = list[currentIndex];
list[currentIndex] = list[randomIndex];
list[randomIndex] = temporaryValue;
}
return list;
}
};