UNPKG

740 kBJavaScriptView Raw
1(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
2this.j$ = this.jStat = (function(Math, undefined) {
3
4// For quick reference.
5var concat = Array.prototype.concat;
6var slice = Array.prototype.slice;
7var toString = Object.prototype.toString;
8
9// Calculate correction for IEEE error
10// TODO: This calculation can be improved.
11function calcRdx(n, m) {
12 var val = n > m ? n : m;
13 return Math.pow(10,
14 17 - ~~(Math.log(((val > 0) ? val : -val)) * Math.LOG10E));
15}
16
17
18var isArray = Array.isArray || function isArray(arg) {
19 return toString.call(arg) === '[object Array]';
20};
21
22
23function isFunction(arg) {
24 return toString.call(arg) === '[object Function]';
25}
26
27
28function isNumber(arg) {
29 return typeof arg === 'number' && arg === arg;
30}
31
32
33// Converts the jStat matrix to vector.
34function toVector(arr) {
35 return concat.apply([], arr);
36}
37
38
39// The one and only jStat constructor.
40function jStat() {
41 return new jStat._init(arguments);
42}
43
44
45// TODO: Remove after all references in src files have been removed.
46jStat.fn = jStat.prototype;
47
48
49// By separating the initializer from the constructor it's easier to handle
50// always returning a new instance whether "new" was used or not.
51jStat._init = function _init(args) {
52 var i;
53
54 // If first argument is an array, must be vector or matrix.
55 if (isArray(args[0])) {
56 // Check if matrix.
57 if (isArray(args[0][0])) {
58 // See if a mapping function was also passed.
59 if (isFunction(args[1]))
60 args[0] = jStat.map(args[0], args[1]);
61 // Iterate over each is faster than this.push.apply(this, args[0].
62 for (i = 0; i < args[0].length; i++)
63 this[i] = args[0][i];
64 this.length = args[0].length;
65
66 // Otherwise must be a vector.
67 } else {
68 this[0] = isFunction(args[1]) ? jStat.map(args[0], args[1]) : args[0];
69 this.length = 1;
70 }
71
72 // If first argument is number, assume creation of sequence.
73 } else if (isNumber(args[0])) {
74 this[0] = jStat.seq.apply(null, args);
75 this.length = 1;
76
77 // Handle case when jStat object is passed to jStat.
78 } else if (args[0] instanceof jStat) {
79 // Duplicate the object and pass it back.
80 return jStat(args[0].toArray());
81
82 // Unexpected argument value, return empty jStat object.
83 // TODO: This is strange behavior. Shouldn't this throw or some such to let
84 // the user know they had bad arguments?
85 } else {
86 this[0] = [];
87 this.length = 1;
88 }
89
90 return this;
91};
92jStat._init.prototype = jStat.prototype;
93jStat._init.constructor = jStat;
94
95
96// Utility functions.
97// TODO: for internal use only?
98jStat.utils = {
99 calcRdx: calcRdx,
100 isArray: isArray,
101 isFunction: isFunction,
102 isNumber: isNumber,
103 toVector: toVector
104};
105
106
107// Easily extend the jStat object.
108// TODO: is this seriously necessary?
109jStat.extend = function extend(obj) {
110 var i, j;
111
112 if (arguments.length === 1) {
113 for (j in obj)
114 jStat[j] = obj[j];
115 return this;
116 }
117
118 for (i = 1; i < arguments.length; i++) {
119 for (j in arguments[i])
120 obj[j] = arguments[i][j];
121 }
122
123 return obj;
124};
125
126
127// Returns the number of rows in the matrix.
128jStat.rows = function rows(arr) {
129 return arr.length || 1;
130};
131
132
133// Returns the number of columns in the matrix.
134jStat.cols = function cols(arr) {
135 return arr[0].length || 1;
136};
137
138
139// Returns the dimensions of the object { rows: i, cols: j }
140jStat.dimensions = function dimensions(arr) {
141 return {
142 rows: jStat.rows(arr),
143 cols: jStat.cols(arr)
144 };
145};
146
147
148// Returns a specified row as a vector
149jStat.row = function row(arr, index) {
150 return arr[index];
151};
152
153
154// Returns the specified column as a vector
155jStat.col = function cols(arr, index) {
156 var column = new Array(arr.length);
157 for (var i = 0; i < arr.length; i++)
158 column[i] = [arr[i][index]];
159 return column;
160};
161
162
163// Returns the diagonal of the matrix
164jStat.diag = function diag(arr) {
165 var nrow = jStat.rows(arr);
166 var res = new Array(nrow);
167 for (var row = 0; row < nrow; row++)
168 res[row] = [arr[row][row]];
169 return res;
170};
171
172
173// Returns the anti-diagonal of the matrix
174jStat.antidiag = function antidiag(arr) {
175 var nrow = jStat.rows(arr) - 1;
176 var res = new Array(nrow);
177 for (var i = 0; nrow >= 0; nrow--, i++)
178 res[i] = [arr[i][nrow]];
179 return res;
180};
181
182// Transpose a matrix or array.
183jStat.transpose = function transpose(arr) {
184 var obj = [];
185 var objArr, rows, cols, j, i;
186
187 // Make sure arr is in matrix format.
188 if (!isArray(arr[0]))
189 arr = [arr];
190
191 rows = arr.length;
192 cols = arr[0].length;
193
194 for (i = 0; i < cols; i++) {
195 objArr = new Array(rows);
196 for (j = 0; j < rows; j++)
197 objArr[j] = arr[j][i];
198 obj.push(objArr);
199 }
200
201 // If obj is vector, return only single array.
202 return obj.length === 1 ? obj[0] : obj;
203};
204
205
206// Map a function to an array or array of arrays.
207// "toAlter" is an internal variable.
208jStat.map = function map(arr, func, toAlter) {
209 var row, nrow, ncol, res, col;
210
211 if (!isArray(arr[0]))
212 arr = [arr];
213
214 nrow = arr.length;
215 ncol = arr[0].length;
216 res = toAlter ? arr : new Array(nrow);
217
218 for (row = 0; row < nrow; row++) {
219 // if the row doesn't exist, create it
220 if (!res[row])
221 res[row] = new Array(ncol);
222 for (col = 0; col < ncol; col++)
223 res[row][col] = func(arr[row][col], row, col);
224 }
225
226 return res.length === 1 ? res[0] : res;
227};
228
229
230// Cumulatively combine the elements of an array or array of arrays using a function.
231jStat.cumreduce = function cumreduce(arr, func, toAlter) {
232 var row, nrow, ncol, res, col;
233
234 if (!isArray(arr[0]))
235 arr = [arr];
236
237 nrow = arr.length;
238 ncol = arr[0].length;
239 res = toAlter ? arr : new Array(nrow);
240
241 for (row = 0; row < nrow; row++) {
242 // if the row doesn't exist, create it
243 if (!res[row])
244 res[row] = new Array(ncol);
245 if (ncol > 0)
246 res[row][0] = arr[row][0];
247 for (col = 1; col < ncol; col++)
248 res[row][col] = func(res[row][col-1], arr[row][col]);
249 }
250 return res.length === 1 ? res[0] : res;
251};
252
253
254// Destructively alter an array.
255jStat.alter = function alter(arr, func) {
256 return jStat.map(arr, func, true);
257};
258
259
260// Generate a rows x cols matrix according to the supplied function.
261jStat.create = function create(rows, cols, func) {
262 var res = new Array(rows);
263 var i, j;
264
265 if (isFunction(cols)) {
266 func = cols;
267 cols = rows;
268 }
269
270 for (i = 0; i < rows; i++) {
271 res[i] = new Array(cols);
272 for (j = 0; j < cols; j++)
273 res[i][j] = func(i, j);
274 }
275
276 return res;
277};
278
279
280function retZero() { return 0; }
281
282
283// Generate a rows x cols matrix of zeros.
284jStat.zeros = function zeros(rows, cols) {
285 if (!isNumber(cols))
286 cols = rows;
287 return jStat.create(rows, cols, retZero);
288};
289
290
291function retOne() { return 1; }
292
293
294// Generate a rows x cols matrix of ones.
295jStat.ones = function ones(rows, cols) {
296 if (!isNumber(cols))
297 cols = rows;
298 return jStat.create(rows, cols, retOne);
299};
300
301
302// Generate a rows x cols matrix of uniformly random numbers.
303jStat.rand = function rand(rows, cols) {
304 if (!isNumber(cols))
305 cols = rows;
306 return jStat.create(rows, cols, Math.random);
307};
308
309
310function retIdent(i, j) { return i === j ? 1 : 0; }
311
312
313// Generate an identity matrix of size row x cols.
314jStat.identity = function identity(rows, cols) {
315 if (!isNumber(cols))
316 cols = rows;
317 return jStat.create(rows, cols, retIdent);
318};
319
320
321// Tests whether a matrix is symmetric
322jStat.symmetric = function symmetric(arr) {
323 var issymmetric = true;
324 var size = arr.length;
325 var row, col;
326
327 if (arr.length !== arr[0].length)
328 return false;
329
330 for (row = 0; row < size; row++) {
331 for (col = 0; col < size; col++)
332 if (arr[col][row] !== arr[row][col])
333 return false;
334 }
335
336 return true;
337};
338
339
340// Set all values to zero.
341jStat.clear = function clear(arr) {
342 return jStat.alter(arr, retZero);
343};
344
345
346// Generate sequence.
347jStat.seq = function seq(min, max, length, func) {
348 if (!isFunction(func))
349 func = false;
350
351 var arr = [];
352 var hival = calcRdx(min, max);
353 var step = (max * hival - min * hival) / ((length - 1) * hival);
354 var current = min;
355 var cnt;
356
357 // Current is assigned using a technique to compensate for IEEE error.
358 // TODO: Needs better implementation.
359 for (cnt = 0;
360 current <= max;
361 cnt++, current = (min * hival + step * hival * cnt) / hival) {
362 arr.push((func ? func(current, cnt) : current));
363 }
364
365 return arr;
366};
367
368
369// TODO: Go over this entire implementation. Seems a tragic waste of resources
370// doing all this work. Instead, and while ugly, use new Function() to generate
371// a custom function for each static method.
372
373// Quick reference.
374var jProto = jStat.prototype;
375
376// Default length.
377jProto.length = 0;
378
379// For internal use only.
380// TODO: Check if they're actually used, and if they are then rename them
381// to _*
382jProto.push = Array.prototype.push;
383jProto.sort = Array.prototype.sort;
384jProto.splice = Array.prototype.splice;
385jProto.slice = Array.prototype.slice;
386
387
388// Return a clean array.
389jProto.toArray = function toArray() {
390 return this.length > 1 ? slice.call(this) : slice.call(this)[0];
391};
392
393
394// Map a function to a matrix or vector.
395jProto.map = function map(func, toAlter) {
396 return jStat(jStat.map(this, func, toAlter));
397};
398
399
400// Cumulatively combine the elements of a matrix or vector using a function.
401jProto.cumreduce = function cumreduce(func, toAlter) {
402 return jStat(jStat.cumreduce(this, func, toAlter));
403};
404
405
406// Destructively alter an array.
407jProto.alter = function alter(func) {
408 jStat.alter(this, func);
409 return this;
410};
411
412
413// Extend prototype with methods that have no argument.
414(function(funcs) {
415 for (var i = 0; i < funcs.length; i++) (function(passfunc) {
416 jProto[passfunc] = function(func) {
417 var self = this,
418 results;
419 // Check for callback.
420 if (func) {
421 setTimeout(function() {
422 func.call(self, jProto[passfunc].call(self));
423 });
424 return this;
425 }
426 results = jStat[passfunc](this);
427 return isArray(results) ? jStat(results) : results;
428 };
429 })(funcs[i]);
430})('transpose clear symmetric rows cols dimensions diag antidiag'.split(' '));
431
432
433// Extend prototype with methods that have one argument.
434(function(funcs) {
435 for (var i = 0; i < funcs.length; i++) (function(passfunc) {
436 jProto[passfunc] = function(index, func) {
437 var self = this;
438 // check for callback
439 if (func) {
440 setTimeout(function() {
441 func.call(self, jProto[passfunc].call(self, index));
442 });
443 return this;
444 }
445 return jStat(jStat[passfunc](this, index));
446 };
447 })(funcs[i]);
448})('row col'.split(' '));
449
450
451// Extend prototype with simple shortcut methods.
452(function(funcs) {
453 for (var i = 0; i < funcs.length; i++) (function(passfunc) {
454 jProto[passfunc] = new Function(
455 'return jStat(jStat.' + passfunc + '.apply(null, arguments));');
456 })(funcs[i]);
457})('create zeros ones rand identity'.split(' '));
458
459
460// Exposing jStat.
461return jStat;
462
463}(Math));
464(function(jStat, Math) {
465
466var isFunction = jStat.utils.isFunction;
467
468// Ascending functions for sort
469function ascNum(a, b) { return a - b; }
470
471function clip(arg, min, max) {
472 return Math.max(min, Math.min(arg, max));
473}
474
475
476// sum of an array
477jStat.sum = function sum(arr) {
478 var sum = 0;
479 var i = arr.length;
480 while (--i >= 0)
481 sum += arr[i];
482 return sum;
483};
484
485
486// sum squared
487jStat.sumsqrd = function sumsqrd(arr) {
488 var sum = 0;
489 var i = arr.length;
490 while (--i >= 0)
491 sum += arr[i] * arr[i];
492 return sum;
493};
494
495
496// sum of squared errors of prediction (SSE)
497jStat.sumsqerr = function sumsqerr(arr) {
498 var mean = jStat.mean(arr);
499 var sum = 0;
500 var i = arr.length;
501 var tmp;
502 while (--i >= 0) {
503 tmp = arr[i] - mean;
504 sum += tmp * tmp;
505 }
506 return sum;
507};
508
509// sum of an array in each row
510jStat.sumrow = function sumrow(arr) {
511 var sum = 0;
512 var i = arr.length;
513 while (--i >= 0)
514 sum += arr[i];
515 return sum;
516};
517
518// product of an array
519jStat.product = function product(arr) {
520 var prod = 1;
521 var i = arr.length;
522 while (--i >= 0)
523 prod *= arr[i];
524 return prod;
525};
526
527
528// minimum value of an array
529jStat.min = function min(arr) {
530 var low = arr[0];
531 var i = 0;
532 while (++i < arr.length)
533 if (arr[i] < low)
534 low = arr[i];
535 return low;
536};
537
538
539// maximum value of an array
540jStat.max = function max(arr) {
541 var high = arr[0];
542 var i = 0;
543 while (++i < arr.length)
544 if (arr[i] > high)
545 high = arr[i];
546 return high;
547};
548
549
550// unique values of an array
551jStat.unique = function unique(arr) {
552 var hash = {}, _arr = [];
553 for(var i = 0; i < arr.length; i++) {
554 if (!hash[arr[i]]) {
555 hash[arr[i]] = true;
556 _arr.push(arr[i]);
557 }
558 }
559 return _arr;
560};
561
562
563// mean value of an array
564jStat.mean = function mean(arr) {
565 return jStat.sum(arr) / arr.length;
566};
567
568
569// mean squared error (MSE)
570jStat.meansqerr = function meansqerr(arr) {
571 return jStat.sumsqerr(arr) / arr.length;
572};
573
574
575// geometric mean of an array
576jStat.geomean = function geomean(arr) {
577 return Math.pow(jStat.product(arr), 1 / arr.length);
578};
579
580
581// median of an array
582jStat.median = function median(arr) {
583 var arrlen = arr.length;
584 var _arr = arr.slice().sort(ascNum);
585 // check if array is even or odd, then return the appropriate
586 return !(arrlen & 1)
587 ? (_arr[(arrlen / 2) - 1 ] + _arr[(arrlen / 2)]) / 2
588 : _arr[(arrlen / 2) | 0 ];
589};
590
591
592// cumulative sum of an array
593jStat.cumsum = function cumsum(arr) {
594 return jStat.cumreduce(arr, function (a, b) { return a + b; });
595};
596
597
598// cumulative product of an array
599jStat.cumprod = function cumprod(arr) {
600 return jStat.cumreduce(arr, function (a, b) { return a * b; });
601};
602
603
604// successive differences of a sequence
605jStat.diff = function diff(arr) {
606 var diffs = [];
607 var arrLen = arr.length;
608 var i;
609 for (i = 1; i < arrLen; i++)
610 diffs.push(arr[i] - arr[i - 1]);
611 return diffs;
612};
613
614
615// ranks of an array
616jStat.rank = function (arr) {
617 var arrlen = arr.length;
618 var sorted = arr.slice().sort(ascNum);
619 var ranks = new Array(arrlen);
620 for (var i = 0; i < arrlen; i++) {
621 var first = sorted.indexOf(arr[i]);
622 var last = sorted.lastIndexOf(arr[i]);
623 if (first === last) {
624 var val = first;
625 } else {
626 var val = (first + last) / 2;
627 }
628 ranks[i] = val + 1;
629 }
630 return ranks;
631};
632
633
634// mode of an array
635// if there are multiple modes of an array, return all of them
636// is this the appropriate way of handling it?
637jStat.mode = function mode(arr) {
638 var arrLen = arr.length;
639 var _arr = arr.slice().sort(ascNum);
640 var count = 1;
641 var maxCount = 0;
642 var numMaxCount = 0;
643 var mode_arr = [];
644 var i;
645
646 for (i = 0; i < arrLen; i++) {
647 if (_arr[i] === _arr[i + 1]) {
648 count++;
649 } else {
650 if (count > maxCount) {
651 mode_arr = [_arr[i]];
652 maxCount = count;
653 numMaxCount = 0;
654 }
655 // are there multiple max counts
656 else if (count === maxCount) {
657 mode_arr.push(_arr[i]);
658 numMaxCount++;
659 }
660 // resetting count for new value in array
661 count = 1;
662 }
663 }
664
665 return numMaxCount === 0 ? mode_arr[0] : mode_arr;
666};
667
668
669// range of an array
670jStat.range = function range(arr) {
671 return jStat.max(arr) - jStat.min(arr);
672};
673
674// variance of an array
675// flag = true indicates sample instead of population
676jStat.variance = function variance(arr, flag) {
677 return jStat.sumsqerr(arr) / (arr.length - (flag ? 1 : 0));
678};
679
680// deviation of an array
681jStat.deviation = function (arr) {
682 var mean = jStat.mean(arr);
683 var arrlen = arr.length;
684 var dev = new Array(arrlen);
685 for (var i = 0; i < arrlen; i++) {
686 dev[i] = arr[i] - mean;
687 }
688 return dev;
689};
690
691// standard deviation of an array
692// flag = true indicates sample instead of population
693jStat.stdev = function stdev(arr, flag) {
694 return Math.sqrt(jStat.variance(arr, flag));
695};
696
697
698// mean deviation (mean absolute deviation) of an array
699jStat.meandev = function meandev(arr) {
700 var devSum = 0;
701 var mean = jStat.mean(arr);
702 var i;
703 for (i = arr.length - 1; i >= 0; i--)
704 devSum += Math.abs(arr[i] - mean);
705 return devSum / arr.length;
706};
707
708
709// median deviation (median absolute deviation) of an array
710jStat.meddev = function meddev(arr) {
711 var devSum = 0;
712 var median = jStat.median(arr);
713 var i;
714 for (i = arr.length - 1; i >= 0; i--)
715 devSum += Math.abs(arr[i] - median);
716 return devSum / arr.length;
717};
718
719
720// coefficient of variation
721jStat.coeffvar = function coeffvar(arr) {
722 return jStat.stdev(arr) / jStat.mean(arr);
723};
724
725
726// quartiles of an array
727jStat.quartiles = function quartiles(arr) {
728 var arrlen = arr.length;
729 var _arr = arr.slice().sort(ascNum);
730 return [
731 _arr[ Math.round((arrlen) / 4) - 1 ],
732 _arr[ Math.round((arrlen) / 2) - 1 ],
733 _arr[ Math.round((arrlen) * 3 / 4) - 1 ]
734 ];
735};
736
737
738// Arbitary quantiles of an array. Direct port of the scipy.stats
739// implementation by Pierre GF Gerard-Marchant.
740jStat.quantiles = function quantiles(arr, quantilesArray, alphap, betap) {
741 var sortedArray = arr.slice().sort(ascNum);
742 var quantileVals = [quantilesArray.length];
743 var n = arr.length;
744 var i, p, m, aleph, k, gamma;
745
746 if (typeof alphap === 'undefined')
747 alphap = 3 / 8;
748 if (typeof betap === 'undefined')
749 betap = 3 / 8;
750
751 for (i = 0; i < quantilesArray.length; i++) {
752 p = quantilesArray[i];
753 m = alphap + p * (1 - alphap - betap);
754 aleph = n * p + m;
755 k = Math.floor(clip(aleph, 1, n - 1));
756 gamma = clip(aleph - k, 0, 1);
757 quantileVals[i] = (1 - gamma) * sortedArray[k - 1] + gamma * sortedArray[k];
758 }
759
760 return quantileVals;
761};
762
763// Returns the k-th percentile of values in a range, where k is in the
764// range 0..1, exclusive.
765jStat.percentile = function percentile(arr, k) {
766 var _arr = arr.slice().sort(ascNum);
767 var realIndex = k * (_arr.length - 1);
768 var index = parseInt(realIndex);
769 var frac = realIndex - index;
770
771 if (index + 1 < _arr.length) {
772 return _arr[index] * (1 - frac) + _arr[index + 1] * frac;
773 } else {
774 return _arr[index];
775 }
776}
777
778
779// The percentile rank of score in a given array. Returns the percentage
780// of all values in the input array that are less than (kind='strict') or
781// less or equal than (kind='weak') score. Default is weak.
782jStat.percentileOfScore = function percentileOfScore(arr, score, kind) {
783 var counter = 0;
784 var len = arr.length;
785 var strict = false;
786 var value, i;
787
788 if (kind === 'strict')
789 strict = true;
790
791 for (i = 0; i < len; i++) {
792 value = arr[i];
793 if ((strict && value < score) ||
794 (!strict && value <= score)) {
795 counter++;
796 }
797 }
798
799 return counter / len;
800};
801
802
803// Histogram (bin count) data
804jStat.histogram = function histogram(arr, bins) {
805 var first = jStat.min(arr);
806 var binCnt = bins || 4;
807 var binWidth = (jStat.max(arr) - first) / binCnt;
808 var len = arr.length;
809 var bins = [];
810 var i;
811
812 for (i = 0; i < binCnt; i++)
813 bins[i] = 0;
814 for (i = 0; i < len; i++)
815 bins[Math.min(Math.floor(((arr[i] - first) / binWidth)), binCnt - 1)] += 1;
816
817 return bins;
818};
819
820
821// covariance of two arrays
822jStat.covariance = function covariance(arr1, arr2) {
823 var u = jStat.mean(arr1);
824 var v = jStat.mean(arr2);
825 var arr1Len = arr1.length;
826 var sq_dev = new Array(arr1Len);
827 var i;
828
829 for (i = 0; i < arr1Len; i++)
830 sq_dev[i] = (arr1[i] - u) * (arr2[i] - v);
831
832 return jStat.sum(sq_dev) / (arr1Len - 1);
833};
834
835
836// (pearson's) population correlation coefficient, rho
837jStat.corrcoeff = function corrcoeff(arr1, arr2) {
838 return jStat.covariance(arr1, arr2) /
839 jStat.stdev(arr1, 1) /
840 jStat.stdev(arr2, 1);
841};
842
843 // (spearman's) rank correlation coefficient, sp
844jStat.spearmancoeff = function (arr1, arr2) {
845 arr1 = jStat.rank(arr1);
846 arr2 = jStat.rank(arr2);
847 var arr1dev = jStat.deviation(arr1);
848 var arr2dev = jStat.deviation(arr2);
849 return jStat.sum(arr1dev.map(function (x, i) {
850 return x * arr2dev[i];
851 })) /
852 Math.sqrt(jStat.sum(arr1dev.map(function (x) {
853 return Math.pow(x, 2);
854 })) * jStat.sum(arr2dev.map(function (x) {
855 return Math.pow(x, 2);
856 }))
857 );
858}
859
860
861// statistical standardized moments (general form of skew/kurt)
862jStat.stanMoment = function stanMoment(arr, n) {
863 var mu = jStat.mean(arr);
864 var sigma = jStat.stdev(arr);
865 var len = arr.length;
866 var skewSum = 0;
867
868 for (i = 0; i < len; i++)
869 skewSum += Math.pow((arr[i] - mu) / sigma, n);
870
871 return skewSum / arr.length;
872};
873
874// (pearson's) moment coefficient of skewness
875jStat.skewness = function skewness(arr) {
876 return jStat.stanMoment(arr, 3);
877};
878
879// (pearson's) (excess) kurtosis
880jStat.kurtosis = function kurtosis(arr) {
881 return jStat.stanMoment(arr, 4) - 3;
882};
883
884
885var jProto = jStat.prototype;
886
887
888// Extend jProto with method for calculating cumulative sums and products.
889// This differs from the similar extension below as cumsum and cumprod should
890// not be run again in the case fullbool === true.
891// If a matrix is passed, automatically assume operation should be done on the
892// columns.
893(function(funcs) {
894 for (var i = 0; i < funcs.length; i++) (function(passfunc) {
895 // If a matrix is passed, automatically assume operation should be done on
896 // the columns.
897 jProto[passfunc] = function(fullbool, func) {
898 var arr = [];
899 var i = 0;
900 var tmpthis = this;
901 // Assignment reassignation depending on how parameters were passed in.
902 if (isFunction(fullbool)) {
903 func = fullbool;
904 fullbool = false;
905 }
906 // Check if a callback was passed with the function.
907 if (func) {
908 setTimeout(function() {
909 func.call(tmpthis, jProto[passfunc].call(tmpthis, fullbool));
910 });
911 return this;
912 }
913 // Check if matrix and run calculations.
914 if (this.length > 1) {
915 tmpthis = fullbool === true ? this : this.transpose();
916 for (; i < tmpthis.length; i++)
917 arr[i] = jStat[passfunc](tmpthis[i]);
918 return arr;
919 }
920 // Pass fullbool if only vector, not a matrix. for variance and stdev.
921 return jStat[passfunc](this[0], fullbool);
922 };
923 })(funcs[i]);
924})(('cumsum cumprod').split(' '));
925
926
927// Extend jProto with methods which don't require arguments and work on columns.
928(function(funcs) {
929 for (var i = 0; i < funcs.length; i++) (function(passfunc) {
930 // If a matrix is passed, automatically assume operation should be done on
931 // the columns.
932 jProto[passfunc] = function(fullbool, func) {
933 var arr = [];
934 var i = 0;
935 var tmpthis = this;
936 // Assignment reassignation depending on how parameters were passed in.
937 if (isFunction(fullbool)) {
938 func = fullbool;
939 fullbool = false;
940 }
941 // Check if a callback was passed with the function.
942 if (func) {
943 setTimeout(function() {
944 func.call(tmpthis, jProto[passfunc].call(tmpthis, fullbool));
945 });
946 return this;
947 }
948 // Check if matrix and run calculations.
949 if (this.length > 1) {
950 if (passfunc !== 'sumrow')
951 tmpthis = fullbool === true ? this : this.transpose();
952 for (; i < tmpthis.length; i++)
953 arr[i] = jStat[passfunc](tmpthis[i]);
954 return fullbool === true
955 ? jStat[passfunc](jStat.utils.toVector(arr))
956 : arr;
957 }
958 // Pass fullbool if only vector, not a matrix. for variance and stdev.
959 return jStat[passfunc](this[0], fullbool);
960 };
961 })(funcs[i]);
962})(('sum sumsqrd sumsqerr sumrow product min max unique mean meansqerr ' +
963 'geomean median diff rank mode range variance deviation stdev meandev ' +
964 'meddev coeffvar quartiles histogram skewness kurtosis').split(' '));
965
966
967// Extend jProto with functions that take arguments. Operations on matrices are
968// done on columns.
969(function(funcs) {
970 for (var i = 0; i < funcs.length; i++) (function(passfunc) {
971 jProto[passfunc] = function() {
972 var arr = [];
973 var i = 0;
974 var tmpthis = this;
975 var args = Array.prototype.slice.call(arguments);
976
977 // If the last argument is a function, we assume it's a callback; we
978 // strip the callback out and call the function again.
979 if (isFunction(args[args.length - 1])) {
980 var callbackFunction = args[args.length - 1];
981 var argsToPass = args.slice(0, args.length - 1);
982
983 setTimeout(function() {
984 callbackFunction.call(tmpthis,
985 jProto[passfunc].apply(tmpthis, argsToPass));
986 });
987 return this;
988
989 // Otherwise we curry the function args and call normally.
990 } else {
991 var callbackFunction = undefined;
992 var curriedFunction = function curriedFunction(vector) {
993 return jStat[passfunc].apply(tmpthis, [vector].concat(args));
994 }
995 }
996
997 // If this is a matrix, run column-by-column.
998 if (this.length > 1) {
999 tmpthis = tmpthis.transpose();
1000 for (; i < tmpthis.length; i++)
1001 arr[i] = curriedFunction(tmpthis[i]);
1002 return arr;
1003 }
1004
1005 // Otherwise run on the vector.
1006 return curriedFunction(this[0]);
1007 };
1008 })(funcs[i]);
1009})('quantiles percentileOfScore'.split(' '));
1010
1011}(this.jStat, Math));
1012// Special functions //
1013(function(jStat, Math) {
1014
1015// Log-gamma function
1016jStat.gammaln = function gammaln(x) {
1017 var j = 0;
1018 var cof = [
1019 76.18009172947146, -86.50532032941677, 24.01409824083091,
1020 -1.231739572450155, 0.1208650973866179e-2, -0.5395239384953e-5
1021 ];
1022 var ser = 1.000000000190015;
1023 var xx, y, tmp;
1024 tmp = (y = xx = x) + 5.5;
1025 tmp -= (xx + 0.5) * Math.log(tmp);
1026 for (; j < 6; j++)
1027 ser += cof[j] / ++y;
1028 return Math.log(2.5066282746310005 * ser / xx) - tmp;
1029};
1030
1031
1032// gamma of x
1033jStat.gammafn = function gammafn(x) {
1034 var p = [-1.716185138865495, 24.76565080557592, -379.80425647094563,
1035 629.3311553128184, 866.9662027904133, -31451.272968848367,
1036 -36144.413418691176, 66456.14382024054
1037 ];
1038 var q = [-30.8402300119739, 315.35062697960416, -1015.1563674902192,
1039 -3107.771671572311, 22538.118420980151, 4755.8462775278811,
1040 -134659.9598649693, -115132.2596755535];
1041 var fact = false;
1042 var n = 0;
1043 var xden = 0;
1044 var xnum = 0;
1045 var y = x;
1046 var i, z, yi, res, sum, ysq;
1047 if (y <= 0) {
1048 res = y % 1 + 3.6e-16;
1049 if (res) {
1050 fact = (!(y & 1) ? 1 : -1) * Math.PI / Math.sin(Math.PI * res);
1051 y = 1 - y;
1052 } else {
1053 return Infinity;
1054 }
1055 }
1056 yi = y;
1057 if (y < 1) {
1058 z = y++;
1059 } else {
1060 z = (y -= n = (y | 0) - 1) - 1;
1061 }
1062 for (i = 0; i < 8; ++i) {
1063 xnum = (xnum + p[i]) * z;
1064 xden = xden * z + q[i];
1065 }
1066 res = xnum / xden + 1;
1067 if (yi < y) {
1068 res /= yi;
1069 } else if (yi > y) {
1070 for (i = 0; i < n; ++i) {
1071 res *= y;
1072 y++;
1073 }
1074 }
1075 if (fact) {
1076 res = fact / res;
1077 }
1078 return res;
1079};
1080
1081
1082// lower incomplete gamma function, which is usually typeset with a
1083// lower-case greek gamma as the function symbol
1084jStat.gammap = function gammap(a, x) {
1085 return jStat.lowRegGamma(a, x) * jStat.gammafn(a);
1086};
1087
1088
1089// The lower regularized incomplete gamma function, usually written P(a,x)
1090jStat.lowRegGamma = function lowRegGamma(a, x) {
1091 var aln = jStat.gammaln(a);
1092 var ap = a;
1093 var sum = 1 / a;
1094 var del = sum;
1095 var b = x + 1 - a;
1096 var c = 1 / 1.0e-30;
1097 var d = 1 / b;
1098 var h = d;
1099 var i = 1;
1100 // calculate maximum number of itterations required for a
1101 var ITMAX = -~(Math.log((a >= 1) ? a : 1 / a) * 8.5 + a * 0.4 + 17);
1102 var an, endval;
1103
1104 if (x < 0 || a <= 0) {
1105 return NaN;
1106 } else if (x < a + 1) {
1107 for (; i <= ITMAX; i++) {
1108 sum += del *= x / ++ap;
1109 }
1110 return (sum * Math.exp(-x + a * Math.log(x) - (aln)));
1111 }
1112
1113 for (; i <= ITMAX; i++) {
1114 an = -i * (i - a);
1115 b += 2;
1116 d = an * d + b;
1117 c = b + an / c;
1118 d = 1 / d;
1119 h *= d * c;
1120 }
1121
1122 return (1 - h * Math.exp(-x + a * Math.log(x) - (aln)));
1123};
1124
1125// natural log factorial of n
1126jStat.factorialln = function factorialln(n) {
1127 return n < 0 ? NaN : jStat.gammaln(n + 1);
1128};
1129
1130// factorial of n
1131jStat.factorial = function factorial(n) {
1132 return n < 0 ? NaN : jStat.gammafn(n + 1);
1133};
1134
1135// combinations of n, m
1136jStat.combination = function combination(n, m) {
1137 // make sure n or m don't exceed the upper limit of usable values
1138 return (n > 170 || m > 170)
1139 ? Math.exp(jStat.combinationln(n, m))
1140 : (jStat.factorial(n) / jStat.factorial(m)) / jStat.factorial(n - m);
1141};
1142
1143
1144jStat.combinationln = function combinationln(n, m){
1145 return jStat.factorialln(n) - jStat.factorialln(m) - jStat.factorialln(n - m);
1146};
1147
1148
1149// permutations of n, m
1150jStat.permutation = function permutation(n, m) {
1151 return jStat.factorial(n) / jStat.factorial(n - m);
1152};
1153
1154
1155// beta function
1156jStat.betafn = function betafn(x, y) {
1157 // ensure arguments are positive
1158 if (x <= 0 || y <= 0)
1159 return undefined;
1160 // make sure x + y doesn't exceed the upper limit of usable values
1161 return (x + y > 170)
1162 ? Math.exp(jStat.betaln(x, y))
1163 : jStat.gammafn(x) * jStat.gammafn(y) / jStat.gammafn(x + y);
1164};
1165
1166
1167// natural logarithm of beta function
1168jStat.betaln = function betaln(x, y) {
1169 return jStat.gammaln(x) + jStat.gammaln(y) - jStat.gammaln(x + y);
1170};
1171
1172
1173// Evaluates the continued fraction for incomplete beta function by modified
1174// Lentz's method.
1175jStat.betacf = function betacf(x, a, b) {
1176 var fpmin = 1e-30;
1177 var m = 1;
1178 var qab = a + b;
1179 var qap = a + 1;
1180 var qam = a - 1;
1181 var c = 1;
1182 var d = 1 - qab * x / qap;
1183 var m2, aa, del, h;
1184
1185 // These q's will be used in factors that occur in the coefficients
1186 if (Math.abs(d) < fpmin)
1187 d = fpmin;
1188 d = 1 / d;
1189 h = d;
1190
1191 for (; m <= 100; m++) {
1192 m2 = 2 * m;
1193 aa = m * (b - m) * x / ((qam + m2) * (a + m2));
1194 // One step (the even one) of the recurrence
1195 d = 1 + aa * d;
1196 if (Math.abs(d) < fpmin)
1197 d = fpmin;
1198 c = 1 + aa / c;
1199 if (Math.abs(c) < fpmin)
1200 c = fpmin;
1201 d = 1 / d;
1202 h *= d * c;
1203 aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2));
1204 // Next step of the recurrence (the odd one)
1205 d = 1 + aa * d;
1206 if (Math.abs(d) < fpmin)
1207 d = fpmin;
1208 c = 1 + aa / c;
1209 if (Math.abs(c) < fpmin)
1210 c = fpmin;
1211 d = 1 / d;
1212 del = d * c;
1213 h *= del;
1214 if (Math.abs(del - 1.0) < 3e-7)
1215 break;
1216 }
1217
1218 return h;
1219};
1220
1221
1222// Returns the inverse of the lower regularized inomplete gamma function
1223jStat.gammapinv = function gammapinv(p, a) {
1224 var j = 0;
1225 var a1 = a - 1;
1226 var EPS = 1e-8;
1227 var gln = jStat.gammaln(a);
1228 var x, err, t, u, pp, lna1, afac;
1229
1230 if (p >= 1)
1231 return Math.max(100, a + 100 * Math.sqrt(a));
1232 if (p <= 0)
1233 return 0;
1234 if (a > 1) {
1235 lna1 = Math.log(a1);
1236 afac = Math.exp(a1 * (lna1 - 1) - gln);
1237 pp = (p < 0.5) ? p : 1 - p;
1238 t = Math.sqrt(-2 * Math.log(pp));
1239 x = (2.30753 + t * 0.27061) / (1 + t * (0.99229 + t * 0.04481)) - t;
1240 if (p < 0.5)
1241 x = -x;
1242 x = Math.max(1e-3,
1243 a * Math.pow(1 - 1 / (9 * a) - x / (3 * Math.sqrt(a)), 3));
1244 } else {
1245 t = 1 - a * (0.253 + a * 0.12);
1246 if (p < t)
1247 x = Math.pow(p / t, 1 / a);
1248 else
1249 x = 1 - Math.log(1 - (p - t) / (1 - t));
1250 }
1251
1252 for(; j < 12; j++) {
1253 if (x <= 0)
1254 return 0;
1255 err = jStat.lowRegGamma(a, x) - p;
1256 if (a > 1)
1257 t = afac * Math.exp(-(x - a1) + a1 * (Math.log(x) - lna1));
1258 else
1259 t = Math.exp(-x + a1 * Math.log(x) - gln);
1260 u = err / t;
1261 x -= (t = u / (1 - 0.5 * Math.min(1, u * ((a - 1) / x - 1))));
1262 if (x <= 0)
1263 x = 0.5 * (x + t);
1264 if (Math.abs(t) < EPS * x)
1265 break;
1266 }
1267
1268 return x;
1269};
1270
1271
1272// Returns the error function erf(x)
1273jStat.erf = function erf(x) {
1274 var cof = [-1.3026537197817094, 6.4196979235649026e-1, 1.9476473204185836e-2,
1275 -9.561514786808631e-3, -9.46595344482036e-4, 3.66839497852761e-4,
1276 4.2523324806907e-5, -2.0278578112534e-5, -1.624290004647e-6,
1277 1.303655835580e-6, 1.5626441722e-8, -8.5238095915e-8,
1278 6.529054439e-9, 5.059343495e-9, -9.91364156e-10,
1279 -2.27365122e-10, 9.6467911e-11, 2.394038e-12,
1280 -6.886027e-12, 8.94487e-13, 3.13092e-13,
1281 -1.12708e-13, 3.81e-16, 7.106e-15,
1282 -1.523e-15, -9.4e-17, 1.21e-16,
1283 -2.8e-17];
1284 var j = cof.length - 1;
1285 var isneg = false;
1286 var d = 0;
1287 var dd = 0;
1288 var t, ty, tmp, res;
1289
1290 if (x < 0) {
1291 x = -x;
1292 isneg = true;
1293 }
1294
1295 t = 2 / (2 + x);
1296 ty = 4 * t - 2;
1297
1298 for(; j > 0; j--) {
1299 tmp = d;
1300 d = ty * d - dd + cof[j];
1301 dd = tmp;
1302 }
1303
1304 res = t * Math.exp(-x * x + 0.5 * (cof[0] + ty * d) - dd);
1305 return isneg ? res - 1 : 1 - res;
1306};
1307
1308
1309// Returns the complmentary error function erfc(x)
1310jStat.erfc = function erfc(x) {
1311 return 1 - jStat.erf(x);
1312};
1313
1314
1315// Returns the inverse of the complementary error function
1316jStat.erfcinv = function erfcinv(p) {
1317 var j = 0;
1318 var x, err, t, pp;
1319 if (p >= 2)
1320 return -100;
1321 if (p <= 0)
1322 return 100;
1323 pp = (p < 1) ? p : 2 - p;
1324 t = Math.sqrt(-2 * Math.log(pp / 2));
1325 x = -0.70711 * ((2.30753 + t * 0.27061) /
1326 (1 + t * (0.99229 + t * 0.04481)) - t);
1327 for (; j < 2; j++) {
1328 err = jStat.erfc(x) - pp;
1329 x += err / (1.12837916709551257 * Math.exp(-x * x) - x * err);
1330 }
1331 return (p < 1) ? x : -x;
1332};
1333
1334
1335// Returns the inverse of the incomplete beta function
1336jStat.ibetainv = function ibetainv(p, a, b) {
1337 var EPS = 1e-8;
1338 var a1 = a - 1;
1339 var b1 = b - 1;
1340 var j = 0;
1341 var lna, lnb, pp, t, u, err, x, al, h, w, afac;
1342 if (p <= 0)
1343 return 0;
1344 if (p >= 1)
1345 return 1;
1346 if (a >= 1 && b >= 1) {
1347 pp = (p < 0.5) ? p : 1 - p;
1348 t = Math.sqrt(-2 * Math.log(pp));
1349 x = (2.30753 + t * 0.27061) / (1 + t* (0.99229 + t * 0.04481)) - t;
1350 if (p < 0.5)
1351 x = -x;
1352 al = (x * x - 3) / 6;
1353 h = 2 / (1 / (2 * a - 1) + 1 / (2 * b - 1));
1354 w = (x * Math.sqrt(al + h) / h) - (1 / (2 * b - 1) - 1 / (2 * a - 1)) *
1355 (al + 5 / 6 - 2 / (3 * h));
1356 x = a / (a + b * Math.exp(2 * w));
1357 } else {
1358 lna = Math.log(a / (a + b));
1359 lnb = Math.log(b / (a + b));
1360 t = Math.exp(a * lna) / a;
1361 u = Math.exp(b * lnb) / b;
1362 w = t + u;
1363 if (p < t / w)
1364 x = Math.pow(a * w * p, 1 / a);
1365 else
1366 x = 1 - Math.pow(b * w * (1 - p), 1 / b);
1367 }
1368 afac = -jStat.gammaln(a) - jStat.gammaln(b) + jStat.gammaln(a + b);
1369 for(; j < 10; j++) {
1370 if (x === 0 || x === 1)
1371 return x;
1372 err = jStat.ibeta(x, a, b) - p;
1373 t = Math.exp(a1 * Math.log(x) + b1 * Math.log(1 - x) + afac);
1374 u = err / t;
1375 x -= (t = u / (1 - 0.5 * Math.min(1, u * (a1 / x - b1 / (1 - x)))));
1376 if (x <= 0)
1377 x = 0.5 * (x + t);
1378 if (x >= 1)
1379 x = 0.5 * (x + t + 1);
1380 if (Math.abs(t) < EPS * x && j > 0)
1381 break;
1382 }
1383 return x;
1384};
1385
1386
1387// Returns the incomplete beta function I_x(a,b)
1388jStat.ibeta = function ibeta(x, a, b) {
1389 // Factors in front of the continued fraction.
1390 var bt = (x === 0 || x === 1) ? 0 :
1391 Math.exp(jStat.gammaln(a + b) - jStat.gammaln(a) -
1392 jStat.gammaln(b) + a * Math.log(x) + b *
1393 Math.log(1 - x));
1394 if (x < 0 || x > 1)
1395 return false;
1396 if (x < (a + 1) / (a + b + 2))
1397 // Use continued fraction directly.
1398 return bt * jStat.betacf(x, a, b) / a;
1399 // else use continued fraction after making the symmetry transformation.
1400 return 1 - bt * jStat.betacf(1 - x, b, a) / b;
1401};
1402
1403
1404// Returns a normal deviate (mu=0, sigma=1).
1405// If n and m are specified it returns a object of normal deviates.
1406jStat.randn = function randn(n, m) {
1407 var u, v, x, y, q, mat;
1408 if (!m)
1409 m = n;
1410 if (n)
1411 return jStat.create(n, m, function() { return jStat.randn(); });
1412 do {
1413 u = Math.random();
1414 v = 1.7156 * (Math.random() - 0.5);
1415 x = u - 0.449871;
1416 y = Math.abs(v) + 0.386595;
1417 q = x * x + y * (0.19600 * y - 0.25472 * x);
1418 } while (q > 0.27597 && (q > 0.27846 || v * v > -4 * Math.log(u) * u * u));
1419 return v / u;
1420};
1421
1422
1423// Returns a gamma deviate by the method of Marsaglia and Tsang.
1424jStat.randg = function randg(shape, n, m) {
1425 var oalph = shape;
1426 var a1, a2, u, v, x, mat;
1427 if (!m)
1428 m = n;
1429 if (!shape)
1430 shape = 1;
1431 if (n) {
1432 mat = jStat.zeros(n,m);
1433 mat.alter(function() { return jStat.randg(shape); });
1434 return mat;
1435 }
1436 if (shape < 1)
1437 shape += 1;
1438 a1 = shape - 1 / 3;
1439 a2 = 1 / Math.sqrt(9 * a1);
1440 do {
1441 do {
1442 x = jStat.randn();
1443 v = 1 + a2 * x;
1444 } while(v <= 0);
1445 v = v * v * v;
1446 u = Math.random();
1447 } while(u > 1 - 0.331 * Math.pow(x, 4) &&
1448 Math.log(u) > 0.5 * x*x + a1 * (1 - v + Math.log(v)));
1449 // alpha > 1
1450 if (shape == oalph)
1451 return a1 * v;
1452 // alpha < 1
1453 do {
1454 u = Math.random();
1455 } while(u === 0);
1456 return Math.pow(u, 1 / oalph) * a1 * v;
1457};
1458
1459
1460// making use of static methods on the instance
1461(function(funcs) {
1462 for (var i = 0; i < funcs.length; i++) (function(passfunc) {
1463 jStat.fn[passfunc] = function() {
1464 return jStat(
1465 jStat.map(this, function(value) { return jStat[passfunc](value); }));
1466 }
1467 })(funcs[i]);
1468})('gammaln gammafn factorial factorialln'.split(' '));
1469
1470
1471(function(funcs) {
1472 for (var i = 0; i < funcs.length; i++) (function(passfunc) {
1473 jStat.fn[passfunc] = function() {
1474 return jStat(jStat[passfunc].apply(null, arguments));
1475 };
1476 })(funcs[i]);
1477})('randn'.split(' '));
1478
1479}(this.jStat, Math));
1480(function(jStat, Math) {
1481
1482// generate all distribution instance methods
1483(function(list) {
1484 for (var i = 0; i < list.length; i++) (function(func) {
1485 // distribution instance method
1486 jStat[func] = function(a, b, c) {
1487 if (!(this instanceof arguments.callee))
1488 return new arguments.callee(a, b, c);
1489 this._a = a;
1490 this._b = b;
1491 this._c = c;
1492 return this;
1493 };
1494 // distribution method to be used on a jStat instance
1495 jStat.fn[func] = function(a, b, c) {
1496 var newthis = jStat[func](a, b, c);
1497 newthis.data = this;
1498 return newthis;
1499 };
1500 // sample instance method
1501 jStat[func].prototype.sample = function(arr) {
1502 var a = this._a;
1503 var b = this._b;
1504 var c = this._c;
1505 if (arr)
1506 return jStat.alter(arr, function() {
1507 return jStat[func].sample(a, b, c);
1508 });
1509 else
1510 return jStat[func].sample(a, b, c);
1511 };
1512 // generate the pdf, cdf and inv instance methods
1513 (function(vals) {
1514 for (var i = 0; i < vals.length; i++) (function(fnfunc) {
1515 jStat[func].prototype[fnfunc] = function(x) {
1516 var a = this._a;
1517 var b = this._b;
1518 var c = this._c;
1519 if (!x && x !== 0)
1520 x = this.data;
1521 if (typeof x !== 'number') {
1522 return jStat.fn.map.call(x, function(x) {
1523 return jStat[func][fnfunc](x, a, b, c);
1524 });
1525 }
1526 return jStat[func][fnfunc](x, a, b, c);
1527 };
1528 })(vals[i]);
1529 })('pdf cdf inv'.split(' '));
1530 // generate the mean, median, mode and variance instance methods
1531 (function(vals) {
1532 for (var i = 0; i < vals.length; i++) (function(fnfunc) {
1533 jStat[func].prototype[fnfunc] = function() {
1534 return jStat[func][fnfunc](this._a, this._b, this._c);
1535 };
1536 })(vals[i]);
1537 })('mean median mode variance'.split(' '));
1538 })(list[i]);
1539})((
1540 'beta centralF cauchy chisquare exponential gamma invgamma kumaraswamy ' +
1541 'laplace lognormal noncentralt normal pareto studentt weibull uniform ' +
1542 'binomial negbin hypgeom poisson triangular'
1543).split(' '));
1544
1545
1546
1547// extend beta function with static methods
1548jStat.extend(jStat.beta, {
1549 pdf: function pdf(x, alpha, beta) {
1550 // PDF is zero outside the support
1551 if (x > 1 || x < 0)
1552 return 0;
1553 // PDF is one for the uniform case
1554 if (alpha == 1 && beta == 1)
1555 return 1;
1556
1557 if (alpha < 512 && beta < 512) {
1558 return (Math.pow(x, alpha - 1) * Math.pow(1 - x, beta - 1)) /
1559 jStat.betafn(alpha, beta);
1560 } else {
1561 return Math.exp((alpha - 1) * Math.log(x) +
1562 (beta - 1) * Math.log(1 - x) -
1563 jStat.betaln(alpha, beta));
1564 }
1565 },
1566
1567 cdf: function cdf(x, alpha, beta) {
1568 return (x > 1 || x < 0) ? (x > 1) * 1 : jStat.ibeta(x, alpha, beta);
1569 },
1570
1571 inv: function inv(x, alpha, beta) {
1572 return jStat.ibetainv(x, alpha, beta);
1573 },
1574
1575 mean: function mean(alpha, beta) {
1576 return alpha / (alpha + beta);
1577 },
1578
1579 median: function median(alpha, beta) {
1580 return jStat.ibetainv(0.5, alpha, beta);
1581 },
1582
1583 mode: function mode(alpha, beta) {
1584 return (alpha - 1 ) / ( alpha + beta - 2);
1585 },
1586
1587 // return a random sample
1588 sample: function sample(alpha, beta) {
1589 var u = jStat.randg(alpha);
1590 return u / (u + jStat.randg(beta));
1591 },
1592
1593 variance: function variance(alpha, beta) {
1594 return (alpha * beta) / (Math.pow(alpha + beta, 2) * (alpha + beta + 1));
1595 }
1596});
1597
1598// extend F function with static methods
1599jStat.extend(jStat.centralF, {
1600 // This implementation of the pdf function avoids float overflow
1601 // See the way that R calculates this value:
1602 // https://svn.r-project.org/R/trunk/src/nmath/df.c
1603 pdf: function pdf(x, df1, df2) {
1604 var p, q, f;
1605
1606 if (x < 0)
1607 return 0;
1608
1609 if (df1 <= 2) {
1610 if (x === 0 && df1 < 2) {
1611 return Infinity;
1612 }
1613 if (x === 0 && df1 === 2) {
1614 return 1;
1615 }
1616 return Math.sqrt((Math.pow(df1 * x, df1) * Math.pow(df2, df2)) /
1617 (Math.pow(df1 * x + df2, df1 + df2))) /
1618 (x * jStat.betafn(df1/2, df2/2));
1619 }
1620
1621 p = (df1 * x) / (df2 + x * df1);
1622 q = df2 / (df2 + x * df1);
1623 f = df1 * q / 2.0;
1624 return f * jStat.binomial.pdf((df1 - 2) / 2, (df1 + df2 - 2) / 2, p);
1625 },
1626
1627 cdf: function cdf(x, df1, df2) {
1628 if (x < 0)
1629 return 0;
1630 return jStat.ibeta((df1 * x) / (df1 * x + df2), df1 / 2, df2 / 2);
1631 },
1632
1633 inv: function inv(x, df1, df2) {
1634 return df2 / (df1 * (1 / jStat.ibetainv(x, df1 / 2, df2 / 2) - 1));
1635 },
1636
1637 mean: function mean(df1, df2) {
1638 return (df2 > 2) ? df2 / (df2 - 2) : undefined;
1639 },
1640
1641 mode: function mode(df1, df2) {
1642 return (df1 > 2) ? (df2 * (df1 - 2)) / (df1 * (df2 + 2)) : undefined;
1643 },
1644
1645 // return a random sample
1646 sample: function sample(df1, df2) {
1647 var x1 = jStat.randg(df1 / 2) * 2;
1648 var x2 = jStat.randg(df2 / 2) * 2;
1649 return (x1 / df1) / (x2 / df2);
1650 },
1651
1652 variance: function variance(df1, df2) {
1653 if (df2 <= 4)
1654 return undefined;
1655 return 2 * df2 * df2 * (df1 + df2 - 2) /
1656 (df1 * (df2 - 2) * (df2 - 2) * (df2 - 4));
1657 }
1658});
1659
1660
1661// extend cauchy function with static methods
1662jStat.extend(jStat.cauchy, {
1663 pdf: function pdf(x, local, scale) {
1664 if (scale < 0) { return 0; }
1665
1666 return (scale / (Math.pow(x - local, 2) + Math.pow(scale, 2))) / Math.PI;
1667 },
1668
1669 cdf: function cdf(x, local, scale) {
1670 return Math.atan((x - local) / scale) / Math.PI + 0.5;
1671 },
1672
1673 inv: function(p, local, scale) {
1674 return local + scale * Math.tan(Math.PI * (p - 0.5));
1675 },
1676
1677 median: function median(local, scale) {
1678 return local;
1679 },
1680
1681 mode: function mode(local, scale) {
1682 return local;
1683 },
1684
1685 sample: function sample(local, scale) {
1686 return jStat.randn() *
1687 Math.sqrt(1 / (2 * jStat.randg(0.5))) * scale + local;
1688 }
1689});
1690
1691
1692
1693// extend chisquare function with static methods
1694jStat.extend(jStat.chisquare, {
1695 pdf: function pdf(x, dof) {
1696 if (x < 0)
1697 return 0;
1698 return (x === 0 && dof === 2) ? 0.5 :
1699 Math.exp((dof / 2 - 1) * Math.log(x) - x / 2 - (dof / 2) *
1700 Math.log(2) - jStat.gammaln(dof / 2));
1701 },
1702
1703 cdf: function cdf(x, dof) {
1704 if (x < 0)
1705 return 0;
1706 return jStat.lowRegGamma(dof / 2, x / 2);
1707 },
1708
1709 inv: function(p, dof) {
1710 return 2 * jStat.gammapinv(p, 0.5 * dof);
1711 },
1712
1713 mean : function(dof) {
1714 return dof;
1715 },
1716
1717 // TODO: this is an approximation (is there a better way?)
1718 median: function median(dof) {
1719 return dof * Math.pow(1 - (2 / (9 * dof)), 3);
1720 },
1721
1722 mode: function mode(dof) {
1723 return (dof - 2 > 0) ? dof - 2 : 0;
1724 },
1725
1726 sample: function sample(dof) {
1727 return jStat.randg(dof / 2) * 2;
1728 },
1729
1730 variance: function variance(dof) {
1731 return 2 * dof;
1732 }
1733});
1734
1735
1736
1737// extend exponential function with static methods
1738jStat.extend(jStat.exponential, {
1739 pdf: function pdf(x, rate) {
1740 return x < 0 ? 0 : rate * Math.exp(-rate * x);
1741 },
1742
1743 cdf: function cdf(x, rate) {
1744 return x < 0 ? 0 : 1 - Math.exp(-rate * x);
1745 },
1746
1747 inv: function(p, rate) {
1748 return -Math.log(1 - p) / rate;
1749 },
1750
1751 mean : function(rate) {
1752 return 1 / rate;
1753 },
1754
1755 median: function (rate) {
1756 return (1 / rate) * Math.log(2);
1757 },
1758
1759 mode: function mode(rate) {
1760 return 0;
1761 },
1762
1763 sample: function sample(rate) {
1764 return -1 / rate * Math.log(Math.random());
1765 },
1766
1767 variance : function(rate) {
1768 return Math.pow(rate, -2);
1769 }
1770});
1771
1772
1773
1774// extend gamma function with static methods
1775jStat.extend(jStat.gamma, {
1776 pdf: function pdf(x, shape, scale) {
1777 if (x < 0)
1778 return 0;
1779 return (x === 0 && shape === 1) ? 1 / scale :
1780 Math.exp((shape - 1) * Math.log(x) - x / scale -
1781 jStat.gammaln(shape) - shape * Math.log(scale));
1782 },
1783
1784 cdf: function cdf(x, shape, scale) {
1785 if (x < 0)
1786 return 0;
1787 return jStat.lowRegGamma(shape, x / scale);
1788 },
1789
1790 inv: function(p, shape, scale) {
1791 return jStat.gammapinv(p, shape) * scale;
1792 },
1793
1794 mean : function(shape, scale) {
1795 return shape * scale;
1796 },
1797
1798 mode: function mode(shape, scale) {
1799 if(shape > 1) return (shape - 1) * scale;
1800 return undefined;
1801 },
1802
1803 sample: function sample(shape, scale) {
1804 return jStat.randg(shape) * scale;
1805 },
1806
1807 variance: function variance(shape, scale) {
1808 return shape * scale * scale;
1809 }
1810});
1811
1812// extend inverse gamma function with static methods
1813jStat.extend(jStat.invgamma, {
1814 pdf: function pdf(x, shape, scale) {
1815 if (x <= 0)
1816 return 0;
1817 return Math.exp(-(shape + 1) * Math.log(x) - scale / x -
1818 jStat.gammaln(shape) + shape * Math.log(scale));
1819 },
1820
1821 cdf: function cdf(x, shape, scale) {
1822 if (x <= 0)
1823 return 0;
1824 return 1 - jStat.lowRegGamma(shape, scale / x);
1825 },
1826
1827 inv: function(p, shape, scale) {
1828 return scale / jStat.gammapinv(1 - p, shape);
1829 },
1830
1831 mean : function(shape, scale) {
1832 return (shape > 1) ? scale / (shape - 1) : undefined;
1833 },
1834
1835 mode: function mode(shape, scale) {
1836 return scale / (shape + 1);
1837 },
1838
1839 sample: function sample(shape, scale) {
1840 return scale / jStat.randg(shape);
1841 },
1842
1843 variance: function variance(shape, scale) {
1844 if (shape <= 2)
1845 return undefined;
1846 return scale * scale / ((shape - 1) * (shape - 1) * (shape - 2));
1847 }
1848});
1849
1850
1851// extend kumaraswamy function with static methods
1852jStat.extend(jStat.kumaraswamy, {
1853 pdf: function pdf(x, alpha, beta) {
1854 if (x === 0 && alpha === 1)
1855 return beta;
1856 else if (x === 1 && beta === 1)
1857 return alpha;
1858 return Math.exp(Math.log(alpha) + Math.log(beta) + (alpha - 1) *
1859 Math.log(x) + (beta - 1) *
1860 Math.log(1 - Math.pow(x, alpha)));
1861 },
1862
1863 cdf: function cdf(x, alpha, beta) {
1864 if (x < 0)
1865 return 0;
1866 else if (x > 1)
1867 return 1;
1868 return (1 - Math.pow(1 - Math.pow(x, alpha), beta));
1869 },
1870
1871 inv: function inv(p, alpha, beta) {
1872 return Math.pow(1 - Math.pow(1 - p, 1 / beta), 1 / alpha);
1873 },
1874
1875 mean : function(alpha, beta) {
1876 return (beta * jStat.gammafn(1 + 1 / alpha) *
1877 jStat.gammafn(beta)) / (jStat.gammafn(1 + 1 / alpha + beta));
1878 },
1879
1880 median: function median(alpha, beta) {
1881 return Math.pow(1 - Math.pow(2, -1 / beta), 1 / alpha);
1882 },
1883
1884 mode: function mode(alpha, beta) {
1885 if (!(alpha >= 1 && beta >= 1 && (alpha !== 1 && beta !== 1)))
1886 return undefined;
1887 return Math.pow((alpha - 1) / (alpha * beta - 1), 1 / alpha);
1888 },
1889
1890 variance: function variance(alpha, beta) {
1891 throw new Error('variance not yet implemented');
1892 // TODO: complete this
1893 }
1894});
1895
1896
1897
1898// extend lognormal function with static methods
1899jStat.extend(jStat.lognormal, {
1900 pdf: function pdf(x, mu, sigma) {
1901 if (x <= 0)
1902 return 0;
1903 return Math.exp(-Math.log(x) - 0.5 * Math.log(2 * Math.PI) -
1904 Math.log(sigma) - Math.pow(Math.log(x) - mu, 2) /
1905 (2 * sigma * sigma));
1906 },
1907
1908 cdf: function cdf(x, mu, sigma) {
1909 if (x < 0)
1910 return 0;
1911 return 0.5 +
1912 (0.5 * jStat.erf((Math.log(x) - mu) / Math.sqrt(2 * sigma * sigma)));
1913 },
1914
1915 inv: function(p, mu, sigma) {
1916 return Math.exp(-1.41421356237309505 * sigma * jStat.erfcinv(2 * p) + mu);
1917 },
1918
1919 mean: function mean(mu, sigma) {
1920 return Math.exp(mu + sigma * sigma / 2);
1921 },
1922
1923 median: function median(mu, sigma) {
1924 return Math.exp(mu);
1925 },
1926
1927 mode: function mode(mu, sigma) {
1928 return Math.exp(mu - sigma * sigma);
1929 },
1930
1931 sample: function sample(mu, sigma) {
1932 return Math.exp(jStat.randn() * sigma + mu);
1933 },
1934
1935 variance: function variance(mu, sigma) {
1936 return (Math.exp(sigma * sigma) - 1) * Math.exp(2 * mu + sigma * sigma);
1937 }
1938});
1939
1940
1941
1942// extend noncentralt function with static methods
1943jStat.extend(jStat.noncentralt, {
1944 pdf: function pdf(x, dof, ncp) {
1945 var tol = 1e-14;
1946 if (Math.abs(ncp) < tol) // ncp approx 0; use student-t
1947 return jStat.studentt.pdf(x, dof)
1948
1949 if (Math.abs(x) < tol) { // different formula for x == 0
1950 return Math.exp(jStat.gammaln((dof + 1) / 2) - ncp * ncp / 2 -
1951 0.5 * Math.log(Math.PI * dof) - jStat.gammaln(dof / 2));
1952 }
1953
1954 // formula for x != 0
1955 return dof / x *
1956 (jStat.noncentralt.cdf(x * Math.sqrt(1 + 2 / dof), dof+2, ncp) -
1957 jStat.noncentralt.cdf(x, dof, ncp));
1958 },
1959
1960 cdf: function cdf(x, dof, ncp) {
1961 var tol = 1e-14;
1962 var min_iterations = 200;
1963
1964 if (Math.abs(ncp) < tol) // ncp approx 0; use student-t
1965 return jStat.studentt.cdf(x, dof);
1966
1967 // turn negative x into positive and flip result afterwards
1968 var flip = false;
1969 if (x < 0) {
1970 flip = true;
1971 ncp = -ncp;
1972 }
1973
1974 var prob = jStat.normal.cdf(-ncp, 0, 1);
1975 var value = tol + 1;
1976 // use value at last two steps to determine convergence
1977 var lastvalue = value;
1978 var y = x * x / (x * x + dof);
1979 var j = 0;
1980 var p = Math.exp(-ncp * ncp / 2);
1981 var q = Math.exp(-ncp * ncp / 2 - 0.5 * Math.log(2) -
1982 jStat.gammaln(3 / 2)) * ncp;
1983 while (j < min_iterations || lastvalue > tol || value > tol) {
1984 lastvalue = value;
1985 if (j > 0) {
1986 p *= (ncp * ncp) / (2 * j);
1987 q *= (ncp * ncp) / (2 * (j + 1 / 2));
1988 }
1989 value = p * jStat.beta.cdf(y, j + 0.5, dof / 2) +
1990 q * jStat.beta.cdf(y, j+1, dof/2);
1991 prob += 0.5 * value;
1992 j++;
1993 }
1994
1995 return flip ? (1 - prob) : prob;
1996 }
1997});
1998
1999
2000// extend normal function with static methods
2001jStat.extend(jStat.normal, {
2002 pdf: function pdf(x, mean, std) {
2003 return Math.exp(-0.5 * Math.log(2 * Math.PI) -
2004 Math.log(std) - Math.pow(x - mean, 2) / (2 * std * std));
2005 },
2006
2007 cdf: function cdf(x, mean, std) {
2008 return 0.5 * (1 + jStat.erf((x - mean) / Math.sqrt(2 * std * std)));
2009 },
2010
2011 inv: function(p, mean, std) {
2012 return -1.41421356237309505 * std * jStat.erfcinv(2 * p) + mean;
2013 },
2014
2015 mean : function(mean, std) {
2016 return mean;
2017 },
2018
2019 median: function median(mean, std) {
2020 return mean;
2021 },
2022
2023 mode: function (mean, std) {
2024 return mean;
2025 },
2026
2027 sample: function sample(mean, std) {
2028 return jStat.randn() * std + mean;
2029 },
2030
2031 variance : function(mean, std) {
2032 return std * std;
2033 }
2034});
2035
2036
2037
2038// extend pareto function with static methods
2039jStat.extend(jStat.pareto, {
2040 pdf: function pdf(x, scale, shape) {
2041 if (x < scale)
2042 return 0;
2043 return (shape * Math.pow(scale, shape)) / Math.pow(x, shape + 1);
2044 },
2045
2046 cdf: function cdf(x, scale, shape) {
2047 if (x < scale)
2048 return 0;
2049 return 1 - Math.pow(scale / x, shape);
2050 },
2051
2052 inv: function inv(p, scale, shape) {
2053 return scale / Math.pow(1 - p, 1 / shape);
2054 },
2055
2056 mean: function mean(scale, shape) {
2057 if (shape <= 1)
2058 return undefined;
2059 return (shape * Math.pow(scale, shape)) / (shape - 1);
2060 },
2061
2062 median: function median(scale, shape) {
2063 return scale * (shape * Math.SQRT2);
2064 },
2065
2066 mode: function mode(scale, shape) {
2067 return scale;
2068 },
2069
2070 variance : function(scale, shape) {
2071 if (shape <= 2)
2072 return undefined;
2073 return (scale*scale * shape) / (Math.pow(shape - 1, 2) * (shape - 2));
2074 }
2075});
2076
2077
2078
2079// extend studentt function with static methods
2080jStat.extend(jStat.studentt, {
2081 pdf: function pdf(x, dof) {
2082 dof = dof > 1e100 ? 1e100 : dof;
2083 return (1/(Math.sqrt(dof) * jStat.betafn(0.5, dof/2))) *
2084 Math.pow(1 + ((x * x) / dof), -((dof + 1) / 2));
2085 },
2086
2087 cdf: function cdf(x, dof) {
2088 var dof2 = dof / 2;
2089 return jStat.ibeta((x + Math.sqrt(x * x + dof)) /
2090 (2 * Math.sqrt(x * x + dof)), dof2, dof2);
2091 },
2092
2093 inv: function(p, dof) {
2094 var x = jStat.ibetainv(2 * Math.min(p, 1 - p), 0.5 * dof, 0.5);
2095 x = Math.sqrt(dof * (1 - x) / x);
2096 return (p > 0.5) ? x : -x;
2097 },
2098
2099 mean: function mean(dof) {
2100 return (dof > 1) ? 0 : undefined;
2101 },
2102
2103 median: function median(dof) {
2104 return 0;
2105 },
2106
2107 mode: function mode(dof) {
2108 return 0;
2109 },
2110
2111 sample: function sample(dof) {
2112 return jStat.randn() * Math.sqrt(dof / (2 * jStat.randg(dof / 2)));
2113 },
2114
2115 variance: function variance(dof) {
2116 return (dof > 2) ? dof / (dof - 2) : (dof > 1) ? Infinity : undefined;
2117 }
2118});
2119
2120
2121
2122// extend weibull function with static methods
2123jStat.extend(jStat.weibull, {
2124 pdf: function pdf(x, scale, shape) {
2125 if (x < 0 || scale < 0 || shape < 0)
2126 return 0;
2127 return (shape / scale) * Math.pow((x / scale), (shape - 1)) *
2128 Math.exp(-(Math.pow((x / scale), shape)));
2129 },
2130
2131 cdf: function cdf(x, scale, shape) {
2132 return x < 0 ? 0 : 1 - Math.exp(-Math.pow((x / scale), shape));
2133 },
2134
2135 inv: function(p, scale, shape) {
2136 return scale * Math.pow(-Math.log(1 - p), 1 / shape);
2137 },
2138
2139 mean : function(scale, shape) {
2140 return scale * jStat.gammafn(1 + 1 / shape);
2141 },
2142
2143 median: function median(scale, shape) {
2144 return scale * Math.pow(Math.log(2), 1 / shape);
2145 },
2146
2147 mode: function mode(scale, shape) {
2148 if (shape <= 1)
2149 return 0;
2150 return scale * Math.pow((shape - 1) / shape, 1 / shape);
2151 },
2152
2153 sample: function sample(scale, shape) {
2154 return scale * Math.pow(-Math.log(Math.random()), 1 / shape);
2155 },
2156
2157 variance: function variance(scale, shape) {
2158 return scale * scale * jStat.gammafn(1 + 2 / shape) -
2159 Math.pow(jStat.weibull.mean(scale, shape), 2);
2160 }
2161});
2162
2163
2164
2165// extend uniform function with static methods
2166jStat.extend(jStat.uniform, {
2167 pdf: function pdf(x, a, b) {
2168 return (x < a || x > b) ? 0 : 1 / (b - a);
2169 },
2170
2171 cdf: function cdf(x, a, b) {
2172 if (x < a)
2173 return 0;
2174 else if (x < b)
2175 return (x - a) / (b - a);
2176 return 1;
2177 },
2178
2179 inv: function(p, a, b) {
2180 return a + (p * (b - a));
2181 },
2182
2183 mean: function mean(a, b) {
2184 return 0.5 * (a + b);
2185 },
2186
2187 median: function median(a, b) {
2188 return jStat.mean(a, b);
2189 },
2190
2191 mode: function mode(a, b) {
2192 throw new Error('mode is not yet implemented');
2193 },
2194
2195 sample: function sample(a, b) {
2196 return (a / 2 + b / 2) + (b / 2 - a / 2) * (2 * Math.random() - 1);
2197 },
2198
2199 variance: function variance(a, b) {
2200 return Math.pow(b - a, 2) / 12;
2201 }
2202});
2203
2204
2205
2206// extend uniform function with static methods
2207jStat.extend(jStat.binomial, {
2208 pdf: function pdf(k, n, p) {
2209 return (p === 0 || p === 1) ?
2210 ((n * p) === k ? 1 : 0) :
2211 jStat.combination(n, k) * Math.pow(p, k) * Math.pow(1 - p, n - k);
2212 },
2213
2214 cdf: function cdf(x, n, p) {
2215 var binomarr = [],
2216 k = 0;
2217 if (x < 0) {
2218 return 0;
2219 }
2220 if (x < n) {
2221 for (; k <= x; k++) {
2222 binomarr[ k ] = jStat.binomial.pdf(k, n, p);
2223 }
2224 return jStat.sum(binomarr);
2225 }
2226 return 1;
2227 }
2228});
2229
2230
2231
2232// extend uniform function with static methods
2233jStat.extend(jStat.negbin, {
2234 pdf: function pdf(k, r, p) {
2235 if (k !== k >>> 0)
2236 return false;
2237 if (k < 0)
2238 return 0;
2239 return jStat.combination(k + r - 1, r - 1) *
2240 Math.pow(1 - p, k) * Math.pow(p, r);
2241 },
2242
2243 cdf: function cdf(x, r, p) {
2244 var sum = 0,
2245 k = 0;
2246 if (x < 0) return 0;
2247 for (; k <= x; k++) {
2248 sum += jStat.negbin.pdf(k, r, p);
2249 }
2250 return sum;
2251 }
2252});
2253
2254
2255
2256// extend uniform function with static methods
2257jStat.extend(jStat.hypgeom, {
2258 pdf: function pdf(k, N, m, n) {
2259 // Hypergeometric PDF.
2260
2261 // A simplification of the CDF algorithm below.
2262
2263 // k = number of successes drawn
2264 // N = population size
2265 // m = number of successes in population
2266 // n = number of items drawn from population
2267
2268 if(k !== k | 0) {
2269 return false;
2270 } else if(k < 0 || k < m - (N - n)) {
2271 // It's impossible to have this few successes drawn.
2272 return 0;
2273 } else if(k > n || k > m) {
2274 // It's impossible to have this many successes drawn.
2275 return 0;
2276 } else if (m * 2 > N) {
2277 // More than half the population is successes.
2278
2279 if(n * 2 > N) {
2280 // More than half the population is sampled.
2281
2282 return jStat.hypgeom.pdf(N - m - n + k, N, N - m, N - n)
2283 } else {
2284 // Half or less of the population is sampled.
2285
2286 return jStat.hypgeom.pdf(n - k, N, N - m, n);
2287 }
2288
2289 } else if(n * 2 > N) {
2290 // Half or less is successes.
2291
2292 return jStat.hypgeom.pdf(m - k, N, m, N - n);
2293
2294 } else if(m < n) {
2295 // We want to have the number of things sampled to be less than the
2296 // successes available. So swap the definitions of successful and sampled.
2297 return jStat.hypgeom.pdf(k, N, n, m);
2298 } else {
2299 // If we get here, half or less of the population was sampled, half or
2300 // less of it was successes, and we had fewer sampled things than
2301 // successes. Now we can do this complicated iterative algorithm in an
2302 // efficient way.
2303
2304 // The basic premise of the algorithm is that we partially normalize our
2305 // intermediate product to keep it in a numerically good region, and then
2306 // finish the normalization at the end.
2307
2308 // This variable holds the scaled probability of the current number of
2309 // successes.
2310 var scaledPDF = 1;
2311
2312 // This keeps track of how much we have normalized.
2313 var samplesDone = 0;
2314
2315 for(var i = 0; i < k; i++) {
2316 // For every possible number of successes up to that observed...
2317
2318 while(scaledPDF > 1 && samplesDone < n) {
2319 // Intermediate result is growing too big. Apply some of the
2320 // normalization to shrink everything.
2321
2322 scaledPDF *= 1 - (m / (N - samplesDone));
2323
2324 // Say we've normalized by this sample already.
2325 samplesDone++;
2326 }
2327
2328 // Work out the partially-normalized hypergeometric PDF for the next
2329 // number of successes
2330 scaledPDF *= (n - i) * (m - i) / ((i + 1) * (N - m - n + i + 1));
2331 }
2332
2333 for(; samplesDone < n; samplesDone++) {
2334 // Apply all the rest of the normalization
2335 scaledPDF *= 1 - (m / (N - samplesDone));
2336 }
2337
2338 // Bound answer sanely before returning.
2339 return Math.min(1, Math.max(0, scaledPDF));
2340 }
2341 },
2342
2343 cdf: function cdf(x, N, m, n) {
2344 // Hypergeometric CDF.
2345
2346 // This algorithm is due to Prof. Thomas S. Ferguson, <tom@math.ucla.edu>,
2347 // and comes from his hypergeometric test calculator at
2348 // <http://www.math.ucla.edu/~tom/distributions/Hypergeometric.html>.
2349
2350 // x = number of successes drawn
2351 // N = population size
2352 // m = number of successes in population
2353 // n = number of items drawn from population
2354
2355 if(x < 0 || x < m - (N - n)) {
2356 // It's impossible to have this few successes drawn or fewer.
2357 return 0;
2358 } else if(x >= n || x >= m) {
2359 // We will always have this many successes or fewer.
2360 return 1;
2361 } else if (m * 2 > N) {
2362 // More than half the population is successes.
2363
2364 if(n * 2 > N) {
2365 // More than half the population is sampled.
2366
2367 return jStat.hypgeom.cdf(N - m - n + x, N, N - m, N - n)
2368 } else {
2369 // Half or less of the population is sampled.
2370
2371 return 1 - jStat.hypgeom.cdf(n - x - 1, N, N - m, n);
2372 }
2373
2374 } else if(n * 2 > N) {
2375 // Half or less is successes.
2376
2377 return 1 - jStat.hypgeom.cdf(m - x - 1, N, m, N - n);
2378
2379 } else if(m < n) {
2380 // We want to have the number of things sampled to be less than the
2381 // successes available. So swap the definitions of successful and sampled.
2382 return jStat.hypgeom.cdf(x, N, n, m);
2383 } else {
2384 // If we get here, half or less of the population was sampled, half or
2385 // less of it was successes, and we had fewer sampled things than
2386 // successes. Now we can do this complicated iterative algorithm in an
2387 // efficient way.
2388
2389 // The basic premise of the algorithm is that we partially normalize our
2390 // intermediate sum to keep it in a numerically good region, and then
2391 // finish the normalization at the end.
2392
2393 // Holds the intermediate, scaled total CDF.
2394 var scaledCDF = 1;
2395
2396 // This variable holds the scaled probability of the current number of
2397 // successes.
2398 var scaledPDF = 1;
2399
2400 // This keeps track of how much we have normalized.
2401 var samplesDone = 0;
2402
2403 for(var i = 0; i < x; i++) {
2404 // For every possible number of successes up to that observed...
2405
2406 while(scaledCDF > 1 && samplesDone < n) {
2407 // Intermediate result is growing too big. Apply some of the
2408 // normalization to shrink everything.
2409
2410 var factor = 1 - (m / (N - samplesDone));
2411
2412 scaledPDF *= factor;
2413 scaledCDF *= factor;
2414
2415 // Say we've normalized by this sample already.
2416 samplesDone++;
2417 }
2418
2419 // Work out the partially-normalized hypergeometric PDF for the next
2420 // number of successes
2421 scaledPDF *= (n - i) * (m - i) / ((i + 1) * (N - m - n + i + 1));
2422
2423 // Add to the CDF answer.
2424 scaledCDF += scaledPDF;
2425 }
2426
2427 for(; samplesDone < n; samplesDone++) {
2428 // Apply all the rest of the normalization
2429 scaledCDF *= 1 - (m / (N - samplesDone));
2430 }
2431
2432 // Bound answer sanely before returning.
2433 return Math.min(1, Math.max(0, scaledCDF));
2434 }
2435 }
2436});
2437
2438
2439
2440// extend uniform function with static methods
2441jStat.extend(jStat.poisson, {
2442 pdf: function pdf(k, l) {
2443 if (l < 0 || (k % 1) !== 0 || k < 0) {
2444 return 0;
2445 }
2446
2447 return Math.pow(l, k) * Math.exp(-l) / jStat.factorial(k);
2448 },
2449
2450 cdf: function cdf(x, l) {
2451 var sumarr = [],
2452 k = 0;
2453 if (x < 0) return 0;
2454 for (; k <= x; k++) {
2455 sumarr.push(jStat.poisson.pdf(k, l));
2456 }
2457 return jStat.sum(sumarr);
2458 },
2459
2460 mean : function(l) {
2461 return l;
2462 },
2463
2464 variance : function(l) {
2465 return l;
2466 },
2467
2468 sample: function sample(l) {
2469 var p = 1, k = 0, L = Math.exp(-l);
2470 do {
2471 k++;
2472 p *= Math.random();
2473 } while (p > L);
2474 return k - 1;
2475 }
2476});
2477
2478// extend triangular function with static methods
2479jStat.extend(jStat.triangular, {
2480 pdf: function pdf(x, a, b, c) {
2481 if (b <= a || c < a || c > b) {
2482 return NaN;
2483 } else {
2484 if (x < a || x > b) {
2485 return 0;
2486 } else if (x < c) {
2487 return (2 * (x - a)) / ((b - a) * (c - a));
2488 } else if (x === c) {
2489 return (2 / (b - a));
2490 } else { // x > c
2491 return (2 * (b - x)) / ((b - a) * (b - c));
2492 }
2493 }
2494 },
2495
2496 cdf: function cdf(x, a, b, c) {
2497 if (b <= a || c < a || c > b)
2498 return NaN;
2499 if (x <= a)
2500 return 0;
2501 else if (x >= b)
2502 return 1;
2503 if (x <= c)
2504 return Math.pow(x - a, 2) / ((b - a) * (c - a));
2505 else // x > c
2506 return 1 - Math.pow(b - x, 2) / ((b - a) * (b - c));
2507 },
2508
2509 inv: function inv(p, a, b, c) {
2510 if (b <= a || c < a || c > b) {
2511 return NaN;
2512 } else {
2513 if (p <= ((c - a) / (b - a))) {
2514 return a + (b - a) * Math.sqrt(p * ((c - a) / (b - a)));
2515 } else { // p > ((c - a) / (b - a))
2516 return a + (b - a) * (1 - Math.sqrt((1 - p) * (1 - ((c - a) / (b - a)))));
2517 }
2518 }
2519 },
2520
2521 mean: function mean(a, b, c) {
2522 return (a + b + c) / 3;
2523 },
2524
2525 median: function median(a, b, c) {
2526 if (c <= (a + b) / 2) {
2527 return b - Math.sqrt((b - a) * (b - c)) / Math.sqrt(2);
2528 } else if (c > (a + b) / 2) {
2529 return a + Math.sqrt((b - a) * (c - a)) / Math.sqrt(2);
2530 }
2531 },
2532
2533 mode: function mode(a, b, c) {
2534 return c;
2535 },
2536
2537 sample: function sample(a, b, c) {
2538 var u = Math.random();
2539 if (u < ((c - a) / (b - a)))
2540 return a + Math.sqrt(u * (b - a) * (c - a))
2541 return b - Math.sqrt((1 - u) * (b - a) * (b - c));
2542 },
2543
2544 variance: function variance(a, b, c) {
2545 return (a * a + b * b + c * c - a * b - a * c - b * c) / 18;
2546 }
2547});
2548
2549function laplaceSign(x) { return x / Math.abs(x); }
2550
2551jStat.extend(jStat.laplace, {
2552 pdf: function pdf(x, mu, b) {
2553 return (b <= 0) ? 0 : (Math.exp(-Math.abs(x - mu) / b)) / (2 * b);
2554 },
2555
2556 cdf: function cdf(x, mu, b) {
2557 if (b <= 0) { return 0; }
2558
2559 if(x < mu) {
2560 return 0.5 * Math.exp((x - mu) / b);
2561 } else {
2562 return 1 - 0.5 * Math.exp(- (x - mu) / b);
2563 }
2564 },
2565
2566 mean: function(mu, b) {
2567 return mu;
2568 },
2569
2570 median: function(mu, b) {
2571 return mu;
2572 },
2573
2574 mode: function(mu, b) {
2575 return mu;
2576 },
2577
2578 variance: function(mu, b) {
2579 return 2 * b * b;
2580 },
2581
2582 sample: function sample(mu, b) {
2583 var u = Math.random() - 0.5;
2584
2585 return mu - (b * laplaceSign(u) * Math.log(1 - (2 * Math.abs(u))));
2586 }
2587});
2588
2589}(this.jStat, Math));
2590/* Provides functions for the solution of linear system of equations, integration, extrapolation,
2591 * interpolation, eigenvalue problems, differential equations and PCA analysis. */
2592
2593(function(jStat, Math) {
2594
2595var push = Array.prototype.push;
2596var isArray = jStat.utils.isArray;
2597
2598function isUsable(arg) {
2599 return isArray(arg) || arg instanceof jStat;
2600}
2601
2602jStat.extend({
2603
2604 // add a vector/matrix to a vector/matrix or scalar
2605 add: function add(arr, arg) {
2606 // check if arg is a vector or scalar
2607 if (isUsable(arg)) {
2608 if (!isUsable(arg[0])) arg = [ arg ];
2609 return jStat.map(arr, function(value, row, col) {
2610 return value + arg[row][col];
2611 });
2612 }
2613 return jStat.map(arr, function(value) { return value + arg; });
2614 },
2615
2616 // subtract a vector or scalar from the vector
2617 subtract: function subtract(arr, arg) {
2618 // check if arg is a vector or scalar
2619 if (isUsable(arg)) {
2620 if (!isUsable(arg[0])) arg = [ arg ];
2621 return jStat.map(arr, function(value, row, col) {
2622 return value - arg[row][col] || 0;
2623 });
2624 }
2625 return jStat.map(arr, function(value) { return value - arg; });
2626 },
2627
2628 // matrix division
2629 divide: function divide(arr, arg) {
2630 if (isUsable(arg)) {
2631 if (!isUsable(arg[0])) arg = [ arg ];
2632 return jStat.multiply(arr, jStat.inv(arg));
2633 }
2634 return jStat.map(arr, function(value) { return value / arg; });
2635 },
2636
2637 // matrix multiplication
2638 multiply: function multiply(arr, arg) {
2639 var row, col, nrescols, sum,
2640 nrow = arr.length,
2641 ncol = arr[0].length,
2642 res = jStat.zeros(nrow, nrescols = (isUsable(arg)) ? arg[0].length : ncol),
2643 rescols = 0;
2644 if (isUsable(arg)) {
2645 for (; rescols < nrescols; rescols++) {
2646 for (row = 0; row < nrow; row++) {
2647 sum = 0;
2648 for (col = 0; col < ncol; col++)
2649 sum += arr[row][col] * arg[col][rescols];
2650 res[row][rescols] = sum;
2651 }
2652 }
2653 return (nrow === 1 && rescols === 1) ? res[0][0] : res;
2654 }
2655 return jStat.map(arr, function(value) { return value * arg; });
2656 },
2657
2658 // Returns the dot product of two matricies
2659 dot: function dot(arr, arg) {
2660 if (!isUsable(arr[0])) arr = [ arr ];
2661 if (!isUsable(arg[0])) arg = [ arg ];
2662 // convert column to row vector
2663 var left = (arr[0].length === 1 && arr.length !== 1) ? jStat.transpose(arr) : arr,
2664 right = (arg[0].length === 1 && arg.length !== 1) ? jStat.transpose(arg) : arg,
2665 res = [],
2666 row = 0,
2667 nrow = left.length,
2668 ncol = left[0].length,
2669 sum, col;
2670 for (; row < nrow; row++) {
2671 res[row] = [];
2672 sum = 0;
2673 for (col = 0; col < ncol; col++)
2674 sum += left[row][col] * right[row][col];
2675 res[row] = sum;
2676 }
2677 return (res.length === 1) ? res[0] : res;
2678 },
2679
2680 // raise every element by a scalar
2681 pow: function pow(arr, arg) {
2682 return jStat.map(arr, function(value) { return Math.pow(value, arg); });
2683 },
2684
2685 // exponentiate every element
2686 exp: function exp(arr) {
2687 return jStat.map(arr, function(value) { return Math.exp(value); });
2688 },
2689
2690 // generate the natural log of every element
2691 log: function exp(arr) {
2692 return jStat.map(arr, function(value) { return Math.log(value); });
2693 },
2694
2695 // generate the absolute values of the vector
2696 abs: function abs(arr) {
2697 return jStat.map(arr, function(value) { return Math.abs(value); });
2698 },
2699
2700 // computes the p-norm of the vector
2701 // In the case that a matrix is passed, uses the first row as the vector
2702 norm: function norm(arr, p) {
2703 var nnorm = 0,
2704 i = 0;
2705 // check the p-value of the norm, and set for most common case
2706 if (isNaN(p)) p = 2;
2707 // check if multi-dimensional array, and make vector correction
2708 if (isUsable(arr[0])) arr = arr[0];
2709 // vector norm
2710 for (; i < arr.length; i++) {
2711 nnorm += Math.pow(Math.abs(arr[i]), p);
2712 }
2713 return Math.pow(nnorm, 1 / p);
2714 },
2715
2716 // computes the angle between two vectors in rads
2717 // In case a matrix is passed, this uses the first row as the vector
2718 angle: function angle(arr, arg) {
2719 return Math.acos(jStat.dot(arr, arg) / (jStat.norm(arr) * jStat.norm(arg)));
2720 },
2721
2722 // augment one matrix by another
2723 // Note: this function returns a matrix, not a jStat object
2724 aug: function aug(a, b) {
2725 var newarr = [];
2726 for (var i = 0; i < a.length; i++) {
2727 newarr.push(a[i].slice());
2728 }
2729 for (var i = 0; i < newarr.length; i++) {
2730 push.apply(newarr[i], b[i]);
2731 }
2732 return newarr;
2733 },
2734
2735 // The inv() function calculates the inverse of a matrix
2736 // Create the inverse by augmenting the matrix by the identity matrix of the
2737 // appropriate size, and then use G-J elimination on the augmented matrix.
2738 inv: function inv(a) {
2739 var rows = a.length;
2740 var cols = a[0].length;
2741 var b = jStat.identity(rows, cols);
2742 var c = jStat.gauss_jordan(a, b);
2743 var result = [];
2744 var i = 0;
2745 var j;
2746
2747 //We need to copy the inverse portion to a new matrix to rid G-J artifacts
2748 for (; i < rows; i++) {
2749 result[i] = [];
2750 for (j = cols; j < c[0].length; j++)
2751 result[i][j - cols] = c[i][j];
2752 }
2753 return result;
2754 },
2755
2756 // calculate the determinant of a matrix
2757 det: function det(a) {
2758 var alen = a.length,
2759 alend = alen * 2,
2760 vals = new Array(alend),
2761 rowshift = alen - 1,
2762 colshift = alend - 1,
2763 mrow = rowshift - alen + 1,
2764 mcol = colshift,
2765 i = 0,
2766 result = 0,
2767 j;
2768 // check for special 2x2 case
2769 if (alen === 2) {
2770 return a[0][0] * a[1][1] - a[0][1] * a[1][0];
2771 }
2772 for (; i < alend; i++) {
2773 vals[i] = 1;
2774 }
2775 for (i = 0; i < alen; i++) {
2776 for (j = 0; j < alen; j++) {
2777 vals[(mrow < 0) ? mrow + alen : mrow ] *= a[i][j];
2778 vals[(mcol < alen) ? mcol + alen : mcol ] *= a[i][j];
2779 mrow++;
2780 mcol--;
2781 }
2782 mrow = --rowshift - alen + 1;
2783 mcol = --colshift;
2784 }
2785 for (i = 0; i < alen; i++) {
2786 result += vals[i];
2787 }
2788 for (; i < alend; i++) {
2789 result -= vals[i];
2790 }
2791 return result;
2792 },
2793
2794 gauss_elimination: function gauss_elimination(a, b) {
2795 var i = 0,
2796 j = 0,
2797 n = a.length,
2798 m = a[0].length,
2799 factor = 1,
2800 sum = 0,
2801 x = [],
2802 maug, pivot, temp, k;
2803 a = jStat.aug(a, b);
2804 maug = a[0].length;
2805 for(i = 0; i < n; i++) {
2806 pivot = a[i][i];
2807 j = i;
2808 for (k = i + 1; k < m; k++) {
2809 if (pivot < Math.abs(a[k][i])) {
2810 pivot = a[k][i];
2811 j = k;
2812 }
2813 }
2814 if (j != i) {
2815 for(k = 0; k < maug; k++) {
2816 temp = a[i][k];
2817 a[i][k] = a[j][k];
2818 a[j][k] = temp;
2819 }
2820 }
2821 for (j = i + 1; j < n; j++) {
2822 factor = a[j][i] / a[i][i];
2823 for(k = i; k < maug; k++) {
2824 a[j][k] = a[j][k] - factor * a[i][k];
2825 }
2826 }
2827 }
2828 for (i = n - 1; i >= 0; i--) {
2829 sum = 0;
2830 for (j = i + 1; j<= n - 1; j++) {
2831 sum = sum + x[j] * a[i][j];
2832 }
2833 x[i] =(a[i][maug - 1] - sum) / a[i][i];
2834 }
2835 return x;
2836 },
2837
2838 gauss_jordan: function gauss_jordan(a, b) {
2839 var m = jStat.aug(a, b),
2840 h = m.length,
2841 w = m[0].length;
2842 // find max pivot
2843 for (var y = 0; y < h; y++) {
2844 var maxrow = y;
2845 for (var y2 = y+1; y2 < h; y2++) {
2846 if (Math.abs(m[y2][y]) > Math.abs(m[maxrow][y]))
2847 maxrow = y2;
2848 }
2849 var tmp = m[y];
2850 m[y] = m[maxrow];
2851 m[maxrow] = tmp
2852 for (var y2 = y+1; y2 < h; y2++) {
2853 c = m[y2][y] / m[y][y];
2854 for (var x = y; x < w; x++) {
2855 m[y2][x] -= m[y][x] * c;
2856 }
2857 }
2858 }
2859 // backsubstitute
2860 for (var y = h-1; y >= 0; y--) {
2861 c = m[y][y];
2862 for (var y2 = 0; y2 < y; y2++) {
2863 for (var x = w-1; x > y-1; x--) {
2864 m[y2][x] -= m[y][x] * m[y2][y] / c;
2865 }
2866 }
2867 m[y][y] /= c;
2868 for (var x = h; x < w; x++) {
2869 m[y][x] /= c;
2870 }
2871 }
2872 return m;
2873 },
2874
2875 lu: function lu(a, b) {
2876 throw new Error('lu not yet implemented');
2877 },
2878
2879 cholesky: function cholesky(a, b) {
2880 throw new Error('cholesky not yet implemented');
2881 },
2882
2883 gauss_jacobi: function gauss_jacobi(a, b, x, r) {
2884 var i = 0;
2885 var j = 0;
2886 var n = a.length;
2887 var l = [];
2888 var u = [];
2889 var d = [];
2890 var xv, c, h, xk;
2891 for (; i < n; i++) {
2892 l[i] = [];
2893 u[i] = [];
2894 d[i] = [];
2895 for (j = 0; j < n; j++) {
2896 if (i > j) {
2897 l[i][j] = a[i][j];
2898 u[i][j] = d[i][j] = 0;
2899 } else if (i < j) {
2900 u[i][j] = a[i][j];
2901 l[i][j] = d[i][j] = 0;
2902 } else {
2903 d[i][j] = a[i][j];
2904 l[i][j] = u[i][j] = 0;
2905 }
2906 }
2907 }
2908 h = jStat.multiply(jStat.multiply(jStat.inv(d), jStat.add(l, u)), -1);
2909 c = jStat.multiply(jStat.inv(d), b);
2910 xv = x;
2911 xk = jStat.add(jStat.multiply(h, x), c);
2912 i = 2;
2913 while (Math.abs(jStat.norm(jStat.subtract(xk,xv))) > r) {
2914 xv = xk;
2915 xk = jStat.add(jStat.multiply(h, xv), c);
2916 i++;
2917 }
2918 return xk;
2919 },
2920
2921 gauss_seidel: function gauss_seidel(a, b, x, r) {
2922 var i = 0;
2923 var n = a.length;
2924 var l = [];
2925 var u = [];
2926 var d = [];
2927 var j, xv, c, h, xk;
2928 for (; i < n; i++) {
2929 l[i] = [];
2930 u[i] = [];
2931 d[i] = [];
2932 for (j = 0; j < n; j++) {
2933 if (i > j) {
2934 l[i][j] = a[i][j];
2935 u[i][j] = d[i][j] = 0;
2936 } else if (i < j) {
2937 u[i][j] = a[i][j];
2938 l[i][j] = d[i][j] = 0;
2939 } else {
2940 d[i][j] = a[i][j];
2941 l[i][j] = u[i][j] = 0;
2942 }
2943 }
2944 }
2945 h = jStat.multiply(jStat.multiply(jStat.inv(jStat.add(d, l)), u), -1);
2946 c = jStat.multiply(jStat.inv(jStat.add(d, l)), b);
2947 xv = x;
2948 xk = jStat.add(jStat.multiply(h, x), c);
2949 i = 2;
2950 while (Math.abs(jStat.norm(jStat.subtract(xk, xv))) > r) {
2951 xv = xk;
2952 xk = jStat.add(jStat.multiply(h, xv), c);
2953 i = i + 1;
2954 }
2955 return xk;
2956 },
2957
2958 SOR: function SOR(a, b, x, r, w) {
2959 var i = 0;
2960 var n = a.length;
2961 var l = [];
2962 var u = [];
2963 var d = [];
2964 var j, xv, c, h, xk;
2965 for (; i < n; i++) {
2966 l[i] = [];
2967 u[i] = [];
2968 d[i] = [];
2969 for (j = 0; j < n; j++) {
2970 if (i > j) {
2971 l[i][j] = a[i][j];
2972 u[i][j] = d[i][j] = 0;
2973 } else if (i < j) {
2974 u[i][j] = a[i][j];
2975 l[i][j] = d[i][j] = 0;
2976 } else {
2977 d[i][j] = a[i][j];
2978 l[i][j] = u[i][j] = 0;
2979 }
2980 }
2981 }
2982 h = jStat.multiply(jStat.inv(jStat.add(d, jStat.multiply(l, w))),
2983 jStat.subtract(jStat.multiply(d, 1 - w),
2984 jStat.multiply(u, w)));
2985 c = jStat.multiply(jStat.multiply(jStat.inv(jStat.add(d,
2986 jStat.multiply(l, w))), b), w);
2987 xv = x;
2988 xk = jStat.add(jStat.multiply(h, x), c);
2989 i = 2;
2990 while (Math.abs(jStat.norm(jStat.subtract(xk, xv))) > r) {
2991 xv = xk;
2992 xk = jStat.add(jStat.multiply(h, xv), c);
2993 i++;
2994 }
2995 return xk;
2996 },
2997
2998 householder: function householder(a) {
2999 var m = a.length;
3000 var n = a[0].length;
3001 var i = 0;
3002 var w = [];
3003 var p = [];
3004 var alpha, r, k, j, factor;
3005 for (; i < m - 1; i++) {
3006 alpha = 0;
3007 for (j = i + 1; j < n; j++)
3008 alpha += (a[j][i] * a[j][i]);
3009 factor = (a[i + 1][i] > 0) ? -1 : 1;
3010 alpha = factor * Math.sqrt(alpha);
3011 r = Math.sqrt((((alpha * alpha) - a[i + 1][i] * alpha) / 2));
3012 w = jStat.zeros(m, 1);
3013 w[i + 1][0] = (a[i + 1][i] - alpha) / (2 * r);
3014 for (k = i + 2; k < m; k++) w[k][0] = a[k][i] / (2 * r);
3015 p = jStat.subtract(jStat.identity(m, n),
3016 jStat.multiply(jStat.multiply(w, jStat.transpose(w)), 2));
3017 a = jStat.multiply(p, jStat.multiply(a, p));
3018 }
3019 return a;
3020 },
3021
3022 // TODO: not working properly.
3023 QR: function QR(a, b) {
3024 var m = a.length;
3025 var n = a[0].length;
3026 var i = 0;
3027 var w = [];
3028 var p = [];
3029 var x = [];
3030 var j, alpha, r, k, factor, sum;
3031 for (; i < m - 1; i++) {
3032 alpha = 0;
3033 for (j = i + 1; j < n; j++)
3034 alpha += (a[j][i] * a[j][i]);
3035 factor = (a[i + 1][i] > 0) ? -1 : 1;
3036 alpha = factor * Math.sqrt(alpha);
3037 r = Math.sqrt((((alpha * alpha) - a[i + 1][i] * alpha) / 2));
3038 w = jStat.zeros(m, 1);
3039 w[i + 1][0] = (a[i + 1][i] - alpha) / (2 * r);
3040 for (k = i + 2; k < m; k++)
3041 w[k][0] = a[k][i] / (2 * r);
3042 p = jStat.subtract(jStat.identity(m, n),
3043 jStat.multiply(jStat.multiply(w, jStat.transpose(w)), 2));
3044 a = jStat.multiply(p, a);
3045 b = jStat.multiply(p, b);
3046 }
3047 for (i = m - 1; i >= 0; i--) {
3048 sum = 0;
3049 for (j = i + 1; j <= n - 1; j++)
3050 sum = x[j] * a[i][j];
3051 x[i] = b[i][0] / a[i][i];
3052 }
3053 return x;
3054 },
3055
3056 jacobi: function jacobi(a) {
3057 var condition = 1;
3058 var count = 0;
3059 var n = a.length;
3060 var e = jStat.identity(n, n);
3061 var ev = [];
3062 var b, i, j, p, q, maxim, theta, s;
3063 // condition === 1 only if tolerance is not reached
3064 while (condition === 1) {
3065 count++;
3066 maxim = a[0][1];
3067 p = 0;
3068 q = 1;
3069 for (i = 0; i < n; i++) {
3070 for (j = 0; j < n; j++) {
3071 if (i != j) {
3072 if (maxim < Math.abs(a[i][j])) {
3073 maxim = Math.abs(a[i][j]);
3074 p = i;
3075 q = j;
3076 }
3077 }
3078 }
3079 }
3080 if (a[p][p] === a[q][q])
3081 theta = (a[p][q] > 0) ? Math.PI / 4 : -Math.PI / 4;
3082 else
3083 theta = Math.atan(2 * a[p][q] / (a[p][p] - a[q][q])) / 2;
3084 s = jStat.identity(n, n);
3085 s[p][p] = Math.cos(theta);
3086 s[p][q] = -Math.sin(theta);
3087 s[q][p] = Math.sin(theta);
3088 s[q][q] = Math.cos(theta);
3089 // eigen vector matrix
3090 e = jStat.multiply(e, s);
3091 b = jStat.multiply(jStat.multiply(jStat.inv(s), a), s);
3092 a = b;
3093 condition = 0;
3094 for (i = 1; i < n; i++) {
3095 for (j = 1; j < n; j++) {
3096 if (i != j && Math.abs(a[i][j]) > 0.001) {
3097 condition = 1;
3098 }
3099 }
3100 }
3101 }
3102 for (i = 0; i < n; i++) ev.push(a[i][i]);
3103 //returns both the eigenvalue and eigenmatrix
3104 return [e, ev];
3105 },
3106
3107 rungekutta: function rungekutta(f, h, p, t_j, u_j, order) {
3108 var k1, k2, u_j1, k3, k4;
3109 if (order === 2) {
3110 while (t_j <= p) {
3111 k1 = h * f(t_j, u_j);
3112 k2 = h * f(t_j + h, u_j + k1);
3113 u_j1 = u_j + (k1 + k2) / 2;
3114 u_j = u_j1;
3115 t_j = t_j + h;
3116 }
3117 }
3118 if (order === 4) {
3119 while (t_j <= p) {
3120 k1 = h * f(t_j, u_j);
3121 k2 = h * f(t_j + h / 2, u_j + k1 / 2);
3122 k3 = h * f(t_j + h / 2, u_j + k2 / 2);
3123 k4 = h * f(t_j +h, u_j + k3);
3124 u_j1 = u_j + (k1 + 2 * k2 + 2 * k3 + k4) / 6;
3125 u_j = u_j1;
3126 t_j = t_j + h;
3127 }
3128 }
3129 return u_j;
3130 },
3131
3132 romberg: function romberg(f, a, b, order) {
3133 var i = 0;
3134 var h = (b - a) / 2;
3135 var x = [];
3136 var h1 = [];
3137 var g = [];
3138 var m, a1, j, k, I, d;
3139 while (i < order / 2) {
3140 I = f(a);
3141 for (j = a, k = 0; j <= b; j = j + h, k++) x[k] = j;
3142 m = x.length;
3143 for (j = 1; j < m - 1; j++) {
3144 I += (((j % 2) !== 0) ? 4 : 2) * f(x[j]);
3145 }
3146 I = (h / 3) * (I + f(b));
3147 g[i] = I;
3148 h /= 2;
3149 i++;
3150 }
3151 a1 = g.length;
3152 m = 1;
3153 while (a1 !== 1) {
3154 for (j = 0; j < a1 - 1; j++)
3155 h1[j] = ((Math.pow(4, m)) * g[j + 1] - g[j]) / (Math.pow(4, m) - 1);
3156 a1 = h1.length;
3157 g = h1;
3158 h1 = [];
3159 m++;
3160 }
3161 return g;
3162 },
3163
3164 richardson: function richardson(X, f, x, h) {
3165 function pos(X, x) {
3166 var i = 0;
3167 var n = X.length;
3168 var p;
3169 for (; i < n; i++)
3170 if (X[i] === x) p = i;
3171 return p;
3172 }
3173 var n = X.length,
3174 h_min = Math.abs(x - X[pos(X, x) + 1]),
3175 i = 0,
3176 g = [],
3177 h1 = [],
3178 y1, y2, m, a, j;
3179 while (h >= h_min) {
3180 y1 = pos(X, x + h);
3181 y2 = pos(X, x);
3182 g[i] = (f[y1] - 2 * f[y2] + f[2 * y2 - y1]) / (h * h);
3183 h /= 2;
3184 i++;
3185 }
3186 a = g.length;
3187 m = 1;
3188 while (a != 1) {
3189 for (j = 0; j < a - 1; j++)
3190 h1[j] = ((Math.pow(4, m)) * g[j + 1] - g[j]) / (Math.pow(4, m) - 1);
3191 a = h1.length;
3192 g = h1;
3193 h1 = [];
3194 m++;
3195 }
3196 return g;
3197 },
3198
3199 simpson: function simpson(f, a, b, n) {
3200 var h = (b - a) / n;
3201 var I = f(a);
3202 var x = [];
3203 var j = a;
3204 var k = 0;
3205 var i = 1;
3206 var m;
3207 for (; j <= b; j = j + h, k++)
3208 x[k] = j;
3209 m = x.length;
3210 for (; i < m - 1; i++) {
3211 I += ((i % 2 !== 0) ? 4 : 2) * f(x[i]);
3212 }
3213 return (h / 3) * (I + f(b));
3214 },
3215
3216 hermite: function hermite(X, F, dF, value) {
3217 var n = X.length;
3218 var p = 0;
3219 var i = 0;
3220 var l = [];
3221 var dl = [];
3222 var A = [];
3223 var B = [];
3224 var j;
3225 for (; i < n; i++) {
3226 l[i] = 1;
3227 for (j = 0; j < n; j++) {
3228 if (i != j) l[i] *= (value - X[j]) / (X[i] - X[j]);
3229 }
3230 dl[i] = 0;
3231 for (j = 0; j < n; j++) {
3232 if (i != j) dl[i] += 1 / (X [i] - X[j]);
3233 }
3234 A[i] = (1 - 2 * (value - X[i]) * dl[i]) * (l[i] * l[i]);
3235 B[i] = (value - X[i]) * (l[i] * l[i]);
3236 p += (A[i] * F[i] + B[i] * dF[i]);
3237 }
3238 return p;
3239 },
3240
3241 lagrange: function lagrange(X, F, value) {
3242 var p = 0;
3243 var i = 0;
3244 var j, l;
3245 var n = X.length;
3246 for (; i < n; i++) {
3247 l = F[i];
3248 for (j = 0; j < n; j++) {
3249 // calculating the lagrange polynomial L_i
3250 if (i != j) l *= (value - X[j]) / (X[i] - X[j]);
3251 }
3252 // adding the lagrange polynomials found above
3253 p += l;
3254 }
3255 return p;
3256 },
3257
3258 cubic_spline: function cubic_spline(X, F, value) {
3259 var n = X.length;
3260 var i = 0, j;
3261 var A = [];
3262 var B = [];
3263 var alpha = [];
3264 var c = [];
3265 var h = [];
3266 var b = [];
3267 var d = [];
3268 for (; i < n - 1; i++)
3269 h[i] = X[i + 1] - X[i];
3270 alpha[0] = 0;
3271 for (i = 1; i < n - 1; i++) {
3272 alpha[i] = (3 / h[i]) * (F[i + 1] - F[i]) -
3273 (3 / h[i-1]) * (F[i] - F[i-1]);
3274 }
3275 for (i = 1; i < n - 1; i++) {
3276 A[i] = [];
3277 B[i] = [];
3278 A[i][i-1] = h[i-1];
3279 A[i][i] = 2 * (h[i - 1] + h[i]);
3280 A[i][i+1] = h[i];
3281 B[i][0] = alpha[i];
3282 }
3283 c = jStat.multiply(jStat.inv(A), B);
3284 for (j = 0; j < n - 1; j++) {
3285 b[j] = (F[j + 1] - F[j]) / h[j] - h[j] * (c[j + 1][0] + 2 * c[j][0]) / 3;
3286 d[j] = (c[j + 1][0] - c[j][0]) / (3 * h[j]);
3287 }
3288 for (j = 0; j < n; j++) {
3289 if (X[j] > value) break;
3290 }
3291 j -= 1;
3292 return F[j] + (value - X[j]) * b[j] + jStat.sq(value-X[j]) *
3293 c[j] + (value - X[j]) * jStat.sq(value - X[j]) * d[j];
3294 },
3295
3296 gauss_quadrature: function gauss_quadrature() {
3297 throw new Error('gauss_quadrature not yet implemented');
3298 },
3299
3300 PCA: function PCA(X) {
3301 var m = X.length;
3302 var n = X[0].length;
3303 var flag = false;
3304 var i = 0;
3305 var j, temp1;
3306 var u = [];
3307 var D = [];
3308 var result = [];
3309 var temp2 = [];
3310 var Y = [];
3311 var Bt = [];
3312 var B = [];
3313 var C = [];
3314 var V = [];
3315 var Vt = [];
3316 for (i = 0; i < m; i++) {
3317 u[i] = jStat.sum(X[i]) / n;
3318 }
3319 for (i = 0; i < n; i++) {
3320 B[i] = [];
3321 for(j = 0; j < m; j++) {
3322 B[i][j] = X[j][i] - u[j];
3323 }
3324 }
3325 B = jStat.transpose(B);
3326 for (i = 0; i < m; i++) {
3327 C[i] = [];
3328 for (j = 0; j < m; j++) {
3329 C[i][j] = (jStat.dot([B[i]], [B[j]])) / (n - 1);
3330 }
3331 }
3332 result = jStat.jacobi(C);
3333 V = result[0];
3334 D = result[1];
3335 Vt = jStat.transpose(V);
3336 for (i = 0; i < D.length; i++) {
3337 for (j = i; j < D.length; j++) {
3338 if(D[i] < D[j]) {
3339 temp1 = D[i];
3340 D[i] = D[j];
3341 D[j] = temp1;
3342 temp2 = Vt[i];
3343 Vt[i] = Vt[j];
3344 Vt[j] = temp2;
3345 }
3346 }
3347 }
3348 Bt = jStat.transpose(B);
3349 for (i = 0; i < m; i++) {
3350 Y[i] = [];
3351 for (j = 0; j < Bt.length; j++) {
3352 Y[i][j] = jStat.dot([Vt[i]], [Bt[j]]);
3353 }
3354 }
3355 return [X, D, Vt, Y];
3356 }
3357});
3358
3359// extend jStat.fn with methods that require one argument
3360(function(funcs) {
3361 for (var i = 0; i < funcs.length; i++) (function(passfunc) {
3362 jStat.fn[passfunc] = function(arg, func) {
3363 var tmpthis = this;
3364 // check for callback
3365 if (func) {
3366 setTimeout(function() {
3367 func.call(tmpthis, jStat.fn[passfunc].call(tmpthis, arg));
3368 }, 15);
3369 return this;
3370 }
3371 if (typeof jStat[passfunc](this, arg) === 'number')
3372 return jStat[passfunc](this, arg);
3373 else
3374 return jStat(jStat[passfunc](this, arg));
3375 };
3376 }(funcs[i]));
3377}('add divide multiply subtract dot pow exp log abs norm angle'.split(' ')));
3378
3379}(this.jStat, Math));
3380(function(jStat, Math) {
3381
3382var slice = [].slice;
3383var isNumber = jStat.utils.isNumber;
3384var isArray = jStat.utils.isArray;
3385
3386// flag==true denotes use of sample standard deviation
3387// Z Statistics
3388jStat.extend({
3389 // 2 different parameter lists:
3390 // (value, mean, sd)
3391 // (value, array, flag)
3392 zscore: function zscore() {
3393 var args = slice.call(arguments);
3394 if (isNumber(args[1])) {
3395 return (args[0] - args[1]) / args[2];
3396 }
3397 return (args[0] - jStat.mean(args[1])) / jStat.stdev(args[1], args[2]);
3398 },
3399
3400 // 3 different paramter lists:
3401 // (value, mean, sd, sides)
3402 // (zscore, sides)
3403 // (value, array, sides, flag)
3404 ztest: function ztest() {
3405 var args = slice.call(arguments);
3406 var z;
3407 if (isArray(args[1])) {
3408 // (value, array, sides, flag)
3409 z = jStat.zscore(args[0],args[1],args[3]);
3410 return (args[2] === 1) ?
3411 (jStat.normal.cdf(-Math.abs(z), 0, 1)) :
3412 (jStat.normal.cdf(-Math.abs(z), 0, 1)*2);
3413 } else {
3414 if (args.length > 2) {
3415 // (value, mean, sd, sides)
3416 z = jStat.zscore(args[0],args[1],args[2]);
3417 return (args[3] === 1) ?
3418 (jStat.normal.cdf(-Math.abs(z),0,1)) :
3419 (jStat.normal.cdf(-Math.abs(z),0,1)* 2);
3420 } else {
3421 // (zscore, sides)
3422 z = args[0];
3423 return (args[1] === 1) ?
3424 (jStat.normal.cdf(-Math.abs(z),0,1)) :
3425 (jStat.normal.cdf(-Math.abs(z),0,1)*2);
3426 }
3427 }
3428 }
3429});
3430
3431jStat.extend(jStat.fn, {
3432 zscore: function zscore(value, flag) {
3433 return (value - this.mean()) / this.stdev(flag);
3434 },
3435
3436 ztest: function ztest(value, sides, flag) {
3437 var zscore = Math.abs(this.zscore(value, flag));
3438 return (sides === 1) ?
3439 (jStat.normal.cdf(-zscore, 0, 1)) :
3440 (jStat.normal.cdf(-zscore, 0, 1) * 2);
3441 }
3442});
3443
3444// T Statistics
3445jStat.extend({
3446 // 2 parameter lists
3447 // (value, mean, sd, n)
3448 // (value, array)
3449 tscore: function tscore() {
3450 var args = slice.call(arguments);
3451 return (args.length === 4) ?
3452 ((args[0] - args[1]) / (args[2] / Math.sqrt(args[3]))) :
3453 ((args[0] - jStat.mean(args[1])) /
3454 (jStat.stdev(args[1], true) / Math.sqrt(args[1].length)));
3455 },
3456
3457 // 3 different paramter lists:
3458 // (value, mean, sd, n, sides)
3459 // (tscore, n, sides)
3460 // (value, array, sides)
3461 ttest: function ttest() {
3462 var args = slice.call(arguments);
3463 var tscore;
3464 if (args.length === 5) {
3465 tscore = Math.abs(jStat.tscore(args[0], args[1], args[2], args[3]));
3466 return (args[4] === 1) ?
3467 (jStat.studentt.cdf(-tscore, args[3]-1)) :
3468 (jStat.studentt.cdf(-tscore, args[3]-1)*2);
3469 }
3470 if (isNumber(args[1])) {
3471 tscore = Math.abs(args[0])
3472 return (args[2] == 1) ?
3473 (jStat.studentt.cdf(-tscore, args[1]-1)) :
3474 (jStat.studentt.cdf(-tscore, args[1]-1) * 2);
3475 }
3476 tscore = Math.abs(jStat.tscore(args[0], args[1]))
3477 return (args[2] == 1) ?
3478 (jStat.studentt.cdf(-tscore, args[1].length-1)) :
3479 (jStat.studentt.cdf(-tscore, args[1].length-1) * 2);
3480 }
3481});
3482
3483jStat.extend(jStat.fn, {
3484 tscore: function tscore(value) {
3485 return (value - this.mean()) / (this.stdev(true) / Math.sqrt(this.cols()));
3486 },
3487
3488 ttest: function ttest(value, sides) {
3489 return (sides === 1) ?
3490 (1 - jStat.studentt.cdf(Math.abs(this.tscore(value)), this.cols()-1)) :
3491 (jStat.studentt.cdf(-Math.abs(this.tscore(value)), this.cols()-1)*2);
3492 }
3493});
3494
3495// F Statistics
3496jStat.extend({
3497 // Paramter list is as follows:
3498 // (array1, array2, array3, ...)
3499 // or it is an array of arrays
3500 // array of arrays conversion
3501 anovafscore: function anovafscore() {
3502 var args = slice.call(arguments),
3503 expVar, sample, sampMean, sampSampMean, tmpargs, unexpVar, i, j;
3504 if (args.length === 1) {
3505 tmpargs = new Array(args[0].length);
3506 for (i = 0; i < args[0].length; i++) {
3507 tmpargs[i] = args[0][i];
3508 }
3509 args = tmpargs;
3510 }
3511 // 2 sample case
3512 if (args.length === 2) {
3513 return jStat.variance(args[0]) / jStat.variance(args[1]);
3514 }
3515 // Builds sample array
3516 sample = new Array();
3517 for (i = 0; i < args.length; i++) {
3518 sample = sample.concat(args[i]);
3519 }
3520 sampMean = jStat.mean(sample);
3521 // Computes the explained variance
3522 expVar = 0;
3523 for (i = 0; i < args.length; i++) {
3524 expVar = expVar + args[i].length * Math.pow(jStat.mean(args[i]) - sampMean, 2);
3525 }
3526 expVar /= (args.length - 1);
3527 // Computes unexplained variance
3528 unexpVar = 0;
3529 for (i = 0; i < args.length; i++) {
3530 sampSampMean = jStat.mean(args[i]);
3531 for (j = 0; j < args[i].length; j++) {
3532 unexpVar += Math.pow(args[i][j] - sampSampMean, 2);
3533 }
3534 }
3535 unexpVar /= (sample.length - args.length);
3536 return expVar / unexpVar;
3537 },
3538
3539 // 2 different paramter setups
3540 // (array1, array2, array3, ...)
3541 // (anovafscore, df1, df2)
3542 anovaftest: function anovaftest() {
3543 var args = slice.call(arguments),
3544 df1, df2, n, i;
3545 if (isNumber(args[0])) {
3546 return 1 - jStat.centralF.cdf(args[0], args[1], args[2]);
3547 }
3548 anovafscore = jStat.anovafscore(args);
3549 df1 = args.length - 1;
3550 n = 0;
3551 for (i = 0; i < args.length; i++) {
3552 n = n + args[i].length;
3553 }
3554 df2 = n - df1 - 1;
3555 return 1 - jStat.centralF.cdf(anovafscore, df1, df2);
3556 },
3557
3558 ftest: function ftest(fscore, df1, df2) {
3559 return 1 - jStat.centralF.cdf(fscore, df1, df2);
3560 }
3561});
3562
3563jStat.extend(jStat.fn, {
3564 anovafscore: function anovafscore() {
3565 return jStat.anovafscore(this.toArray());
3566 },
3567
3568 anovaftes: function anovaftes() {
3569 var n = 0;
3570 var i;
3571 for (i = 0; i < this.length; i++) {
3572 n = n + this[i].length;
3573 }
3574 return jStat.ftest(this.anovafscore(), this.length - 1, n - this.length);
3575 }
3576});
3577
3578// Error Bounds
3579jStat.extend({
3580 // 2 different parameter setups
3581 // (value, alpha, sd, n)
3582 // (value, alpha, array)
3583 normalci: function normalci() {
3584 var args = slice.call(arguments),
3585 ans = new Array(2),
3586 change;
3587 if (args.length === 4) {
3588 change = Math.abs(jStat.normal.inv(args[1] / 2, 0, 1) *
3589 args[2] / Math.sqrt(args[3]));
3590 } else {
3591 change = Math.abs(jStat.normal.inv(args[1] / 2, 0, 1) *
3592 jStat.stdev(args[2]) / Math.sqrt(args[2].length));
3593 }
3594 ans[0] = args[0] - change;
3595 ans[1] = args[0] + change;
3596 return ans;
3597 },
3598
3599 // 2 different parameter setups
3600 // (value, alpha, sd, n)
3601 // (value, alpha, array)
3602 tci: function tci() {
3603 var args = slice.call(arguments),
3604 ans = new Array(2),
3605 change;
3606 if (args.length === 4) {
3607 change = Math.abs(jStat.studentt.inv(args[1] / 2, args[3] - 1) *
3608 args[2] / Math.sqrt(args[3]));
3609 } else {
3610 change = Math.abs(jStat.studentt.inv(args[1] / 2, args[2].length - 1) *
3611 jStat.stdev(args[2], true) / Math.sqrt(args[2].length));
3612 }
3613 ans[0] = args[0] - change;
3614 ans[1] = args[0] + change;
3615 return ans;
3616 },
3617
3618 significant: function significant(pvalue, alpha) {
3619 return pvalue < alpha;
3620 }
3621});
3622
3623jStat.extend(jStat.fn, {
3624 normalci: function normalci(value, alpha) {
3625 return jStat.normalci(value, alpha, this.toArray());
3626 },
3627
3628 tci: function tci(value, alpha) {
3629 return jStat.tci(value, alpha, this.toArray());
3630 }
3631});
3632
3633// internal method for calculating the z-score for a difference of proportions test
3634function differenceOfProportions(p1, n1, p2, n2) {
3635 if (p1 > 1 || p2 > 1 || p1 <= 0 || p2 <= 0) {
3636 throw new Error("Proportions should be greater than 0 and less than 1")
3637 }
3638 var pooled = (p1 * n1 + p2 * n2) / (n1 + n2);
3639 var se = Math.sqrt(pooled * (1 - pooled) * ((1/n1) + (1/n2)));
3640 return (p1 - p2) / se;
3641}
3642
3643// Difference of Proportions
3644jStat.extend(jStat.fn, {
3645 oneSidedDifferenceOfProportions: function oneSidedDifferenceOfProportions(p1, n1, p2, n2) {
3646 var z = differenceOfProportions(p1, n1, p2, n2);
3647 return jStat.ztest(z, 1);
3648 },
3649
3650 twoSidedDifferenceOfProportions: function twoSidedDifferenceOfProportions(p1, n1, p2, n2) {
3651 var z = differenceOfProportions(p1, n1, p2, n2);
3652 return jStat.ztest(z, 2);
3653 }
3654});
3655
3656}(this.jStat, Math));
3657
3658},{}],2:[function(require,module,exports){
3659(function (global){
3660/**
3661 * @license
3662 * lodash 4.6.1 (Custom Build) <https://lodash.com/>
3663 * Build: `lodash -d -o ./foo/lodash.js`
3664 * Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/>
3665 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
3666 * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
3667 * Available under MIT license <https://lodash.com/license>
3668 */
3669;(function() {
3670
3671 /** Used as a safe reference for `undefined` in pre-ES5 environments. */
3672 var undefined;
3673
3674 /** Used as the semantic version number. */
3675 var VERSION = '4.6.1';
3676
3677 /** Used as the size to enable large array optimizations. */
3678 var LARGE_ARRAY_SIZE = 200;
3679
3680 /** Used as the `TypeError` message for "Functions" methods. */
3681 var FUNC_ERROR_TEXT = 'Expected a function';
3682
3683 /** Used to stand-in for `undefined` hash values. */
3684 var HASH_UNDEFINED = '__lodash_hash_undefined__';
3685
3686 /** Used as the internal argument placeholder. */
3687 var PLACEHOLDER = '__lodash_placeholder__';
3688
3689 /** Used to compose bitmasks for wrapper metadata. */
3690 var BIND_FLAG = 1,
3691 BIND_KEY_FLAG = 2,
3692 CURRY_BOUND_FLAG = 4,
3693 CURRY_FLAG = 8,
3694 CURRY_RIGHT_FLAG = 16,
3695 PARTIAL_FLAG = 32,
3696 PARTIAL_RIGHT_FLAG = 64,
3697 ARY_FLAG = 128,
3698 REARG_FLAG = 256,
3699 FLIP_FLAG = 512;
3700
3701 /** Used to compose bitmasks for comparison styles. */
3702 var UNORDERED_COMPARE_FLAG = 1,
3703 PARTIAL_COMPARE_FLAG = 2;
3704
3705 /** Used as default options for `_.truncate`. */
3706 var DEFAULT_TRUNC_LENGTH = 30,
3707 DEFAULT_TRUNC_OMISSION = '...';
3708
3709 /** Used to detect hot functions by number of calls within a span of milliseconds. */
3710 var HOT_COUNT = 150,
3711 HOT_SPAN = 16;
3712
3713 /** Used to indicate the type of lazy iteratees. */
3714 var LAZY_FILTER_FLAG = 1,
3715 LAZY_MAP_FLAG = 2,
3716 LAZY_WHILE_FLAG = 3;
3717
3718 /** Used as references for various `Number` constants. */
3719 var INFINITY = 1 / 0,
3720 MAX_SAFE_INTEGER = 9007199254740991,
3721 MAX_INTEGER = 1.7976931348623157e+308,
3722 NAN = 0 / 0;
3723
3724 /** Used as references for the maximum length and index of an array. */
3725 var MAX_ARRAY_LENGTH = 4294967295,
3726 MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,
3727 HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;
3728
3729 /** `Object#toString` result references. */
3730 var argsTag = '[object Arguments]',
3731 arrayTag = '[object Array]',
3732 boolTag = '[object Boolean]',
3733 dateTag = '[object Date]',
3734 errorTag = '[object Error]',
3735 funcTag = '[object Function]',
3736 genTag = '[object GeneratorFunction]',
3737 mapTag = '[object Map]',
3738 numberTag = '[object Number]',
3739 objectTag = '[object Object]',
3740 regexpTag = '[object RegExp]',
3741 setTag = '[object Set]',
3742 stringTag = '[object String]',
3743 symbolTag = '[object Symbol]',
3744 weakMapTag = '[object WeakMap]',
3745 weakSetTag = '[object WeakSet]';
3746
3747 var arrayBufferTag = '[object ArrayBuffer]',
3748 float32Tag = '[object Float32Array]',
3749 float64Tag = '[object Float64Array]',
3750 int8Tag = '[object Int8Array]',
3751 int16Tag = '[object Int16Array]',
3752 int32Tag = '[object Int32Array]',
3753 uint8Tag = '[object Uint8Array]',
3754 uint8ClampedTag = '[object Uint8ClampedArray]',
3755 uint16Tag = '[object Uint16Array]',
3756 uint32Tag = '[object Uint32Array]';
3757
3758 /** Used to match empty string literals in compiled template source. */
3759 var reEmptyStringLeading = /\b__p \+= '';/g,
3760 reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
3761 reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
3762
3763 /** Used to match HTML entities and HTML characters. */
3764 var reEscapedHtml = /&(?:amp|lt|gt|quot|#39|#96);/g,
3765 reUnescapedHtml = /[&<>"'`]/g,
3766 reHasEscapedHtml = RegExp(reEscapedHtml.source),
3767 reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
3768
3769 /** Used to match template delimiters. */
3770 var reEscape = /<%-([\s\S]+?)%>/g,
3771 reEvaluate = /<%([\s\S]+?)%>/g,
3772 reInterpolate = /<%=([\s\S]+?)%>/g;
3773
3774 /** Used to match property names within property paths. */
3775 var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
3776 reIsPlainProp = /^\w*$/,
3777 rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]/g;
3778
3779 /** Used to match `RegExp` [syntax characters](http://ecma-international.org/ecma-262/6.0/#sec-patterns). */
3780 var reRegExpChar = /[\\^$.*+?()[\]{}|]/g,
3781 reHasRegExpChar = RegExp(reRegExpChar.source);
3782
3783 /** Used to match leading and trailing whitespace. */
3784 var reTrim = /^\s+|\s+$/g,
3785 reTrimStart = /^\s+/,
3786 reTrimEnd = /\s+$/;
3787
3788 /** Used to match backslashes in property paths. */
3789 var reEscapeChar = /\\(\\)?/g;
3790
3791 /** Used to match [ES template delimiters](http://ecma-international.org/ecma-262/6.0/#sec-template-literal-lexical-components). */
3792 var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
3793
3794 /** Used to match `RegExp` flags from their coerced string values. */
3795 var reFlags = /\w*$/;
3796
3797 /** Used to detect hexadecimal string values. */
3798 var reHasHexPrefix = /^0x/i;
3799
3800 /** Used to detect bad signed hexadecimal string values. */
3801 var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
3802
3803 /** Used to detect binary string values. */
3804 var reIsBinary = /^0b[01]+$/i;
3805
3806 /** Used to detect host constructors (Safari > 5). */
3807 var reIsHostCtor = /^\[object .+?Constructor\]$/;
3808
3809 /** Used to detect octal string values. */
3810 var reIsOctal = /^0o[0-7]+$/i;
3811
3812 /** Used to detect unsigned integer values. */
3813 var reIsUint = /^(?:0|[1-9]\d*)$/;
3814
3815 /** Used to match latin-1 supplementary letters (excluding mathematical operators). */
3816 var reLatin1 = /[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g;
3817
3818 /** Used to ensure capturing order of template delimiters. */
3819 var reNoMatch = /($^)/;
3820
3821 /** Used to match unescaped characters in compiled string literals. */
3822 var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
3823
3824 /** Used to compose unicode character classes. */
3825 var rsAstralRange = '\\ud800-\\udfff',
3826 rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23',
3827 rsComboSymbolsRange = '\\u20d0-\\u20f0',
3828 rsDingbatRange = '\\u2700-\\u27bf',
3829 rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
3830 rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
3831 rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
3832 rsQuoteRange = '\\u2018\\u2019\\u201c\\u201d',
3833 rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000',
3834 rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
3835 rsVarRange = '\\ufe0e\\ufe0f',
3836 rsBreakRange = rsMathOpRange + rsNonCharRange + rsQuoteRange + rsSpaceRange;
3837
3838 /** Used to compose unicode capture groups. */
3839 var rsAstral = '[' + rsAstralRange + ']',
3840 rsBreak = '[' + rsBreakRange + ']',
3841 rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']',
3842 rsDigits = '\\d+',
3843 rsDingbat = '[' + rsDingbatRange + ']',
3844 rsLower = '[' + rsLowerRange + ']',
3845 rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
3846 rsFitz = '\\ud83c[\\udffb-\\udfff]',
3847 rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
3848 rsNonAstral = '[^' + rsAstralRange + ']',
3849 rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
3850 rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
3851 rsUpper = '[' + rsUpperRange + ']',
3852 rsZWJ = '\\u200d';
3853
3854 /** Used to compose unicode regexes. */
3855 var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')',
3856 rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')',
3857 reOptMod = rsModifier + '?',
3858 rsOptVar = '[' + rsVarRange + ']?',
3859 rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
3860 rsSeq = rsOptVar + reOptMod + rsOptJoin,
3861 rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,
3862 rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
3863
3864 /**
3865 * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
3866 * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
3867 */
3868 var reComboMark = RegExp(rsCombo, 'g');
3869
3870 /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
3871 var reComplexSymbol = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
3872
3873 /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
3874 var reHasComplexSymbol = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']');
3875
3876 /** Used to match non-compound words composed of alphanumeric characters. */
3877 var reBasicWord = /[a-zA-Z0-9]+/g;
3878
3879 /** Used to match complex or compound words. */
3880 var reComplexWord = RegExp([
3881 rsUpper + '?' + rsLower + '+(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
3882 rsUpperMisc + '+(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')',
3883 rsUpper + '?' + rsLowerMisc + '+',
3884 rsUpper + '+',
3885 rsDigits,
3886 rsEmoji
3887 ].join('|'), 'g');
3888
3889 /** Used to detect strings that need a more robust regexp to match words. */
3890 var reHasComplexWord = /[a-z][A-Z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;
3891
3892 /** Used to assign default `context` object properties. */
3893 var contextProps = [
3894 'Array', 'Buffer', 'Date', 'Error', 'Float32Array', 'Float64Array',
3895 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object',
3896 'Reflect', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array',
3897 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', '_',
3898 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout'
3899 ];
3900
3901 /** Used to make template sourceURLs easier to identify. */
3902 var templateCounter = -1;
3903
3904 /** Used to identify `toStringTag` values of typed arrays. */
3905 var typedArrayTags = {};
3906 typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
3907 typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
3908 typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
3909 typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
3910 typedArrayTags[uint32Tag] = true;
3911 typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
3912 typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
3913 typedArrayTags[dateTag] = typedArrayTags[errorTag] =
3914 typedArrayTags[funcTag] = typedArrayTags[mapTag] =
3915 typedArrayTags[numberTag] = typedArrayTags[objectTag] =
3916 typedArrayTags[regexpTag] = typedArrayTags[setTag] =
3917 typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
3918
3919 /** Used to identify `toStringTag` values supported by `_.clone`. */
3920 var cloneableTags = {};
3921 cloneableTags[argsTag] = cloneableTags[arrayTag] =
3922 cloneableTags[arrayBufferTag] = cloneableTags[boolTag] =
3923 cloneableTags[dateTag] = cloneableTags[float32Tag] =
3924 cloneableTags[float64Tag] = cloneableTags[int8Tag] =
3925 cloneableTags[int16Tag] = cloneableTags[int32Tag] =
3926 cloneableTags[mapTag] = cloneableTags[numberTag] =
3927 cloneableTags[objectTag] = cloneableTags[regexpTag] =
3928 cloneableTags[setTag] = cloneableTags[stringTag] =
3929 cloneableTags[symbolTag] = cloneableTags[uint8Tag] =
3930 cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] =
3931 cloneableTags[uint32Tag] = true;
3932 cloneableTags[errorTag] = cloneableTags[funcTag] =
3933 cloneableTags[weakMapTag] = false;
3934
3935 /** Used to map latin-1 supplementary letters to basic latin letters. */
3936 var deburredLetters = {
3937 '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
3938 '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
3939 '\xc7': 'C', '\xe7': 'c',
3940 '\xd0': 'D', '\xf0': 'd',
3941 '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
3942 '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
3943 '\xcC': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
3944 '\xeC': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
3945 '\xd1': 'N', '\xf1': 'n',
3946 '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
3947 '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
3948 '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
3949 '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
3950 '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
3951 '\xc6': 'Ae', '\xe6': 'ae',
3952 '\xde': 'Th', '\xfe': 'th',
3953 '\xdf': 'ss'
3954 };
3955
3956 /** Used to map characters to HTML entities. */
3957 var htmlEscapes = {
3958 '&': '&amp;',
3959 '<': '&lt;',
3960 '>': '&gt;',
3961 '"': '&quot;',
3962 "'": '&#39;',
3963 '`': '&#96;'
3964 };
3965
3966 /** Used to map HTML entities to characters. */
3967 var htmlUnescapes = {
3968 '&amp;': '&',
3969 '&lt;': '<',
3970 '&gt;': '>',
3971 '&quot;': '"',
3972 '&#39;': "'",
3973 '&#96;': '`'
3974 };
3975
3976 /** Used to determine if values are of the language type `Object`. */
3977 var objectTypes = {
3978 'function': true,
3979 'object': true
3980 };
3981
3982 /** Used to escape characters for inclusion in compiled string literals. */
3983 var stringEscapes = {
3984 '\\': '\\',
3985 "'": "'",
3986 '\n': 'n',
3987 '\r': 'r',
3988 '\u2028': 'u2028',
3989 '\u2029': 'u2029'
3990 };
3991
3992 /** Built-in method references without a dependency on `root`. */
3993 var freeParseFloat = parseFloat,
3994 freeParseInt = parseInt;
3995
3996 /** Detect free variable `exports`. */
3997 var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType)
3998 ? exports
3999 : undefined;
4000
4001 /** Detect free variable `module`. */
4002 var freeModule = (objectTypes[typeof module] && module && !module.nodeType)
4003 ? module
4004 : undefined;
4005
4006 /** Detect the popular CommonJS extension `module.exports`. */
4007 var moduleExports = (freeModule && freeModule.exports === freeExports)
4008 ? freeExports
4009 : undefined;
4010
4011 /** Detect free variable `global` from Node.js. */
4012 var freeGlobal = checkGlobal(freeExports && freeModule && typeof global == 'object' && global);
4013
4014 /** Detect free variable `self`. */
4015 var freeSelf = checkGlobal(objectTypes[typeof self] && self);
4016
4017 /** Detect free variable `window`. */
4018 var freeWindow = checkGlobal(objectTypes[typeof window] && window);
4019
4020 /** Detect `this` as the global object. */
4021 var thisGlobal = checkGlobal(objectTypes[typeof this] && this);
4022
4023 /**
4024 * Used as a reference to the global object.
4025 *
4026 * The `this` value is used if it's the global object to avoid Greasemonkey's
4027 * restricted `window` object, otherwise the `window` object is used.
4028 */
4029 var root = freeGlobal ||
4030 ((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) ||
4031 freeSelf || thisGlobal || Function('return this')();
4032
4033 /*--------------------------------------------------------------------------*/
4034
4035 /**
4036 * Adds the key-value `pair` to `map`.
4037 *
4038 * @private
4039 * @param {Object} map The map to modify.
4040 * @param {Array} pair The key-value pair to add.
4041 * @returns {Object} Returns `map`.
4042 */
4043 function addMapEntry(map, pair) {
4044 // Don't return `Map#set` because it doesn't return the map instance in IE 11.
4045 map.set(pair[0], pair[1]);
4046 return map;
4047 }
4048
4049 /**
4050 * Adds `value` to `set`.
4051 *
4052 * @private
4053 * @param {Object} set The set to modify.
4054 * @param {*} value The value to add.
4055 * @returns {Object} Returns `set`.
4056 */
4057 function addSetEntry(set, value) {
4058 set.add(value);
4059 return set;
4060 }
4061
4062 /**
4063 * A faster alternative to `Function#apply`, this function invokes `func`
4064 * with the `this` binding of `thisArg` and the arguments of `args`.
4065 *
4066 * @private
4067 * @param {Function} func The function to invoke.
4068 * @param {*} thisArg The `this` binding of `func`.
4069 * @param {...*} args The arguments to invoke `func` with.
4070 * @returns {*} Returns the result of `func`.
4071 */
4072 function apply(func, thisArg, args) {
4073 var length = args.length;
4074 switch (length) {
4075 case 0: return func.call(thisArg);
4076 case 1: return func.call(thisArg, args[0]);
4077 case 2: return func.call(thisArg, args[0], args[1]);
4078 case 3: return func.call(thisArg, args[0], args[1], args[2]);
4079 }
4080 return func.apply(thisArg, args);
4081 }
4082
4083 /**
4084 * A specialized version of `baseAggregator` for arrays.
4085 *
4086 * @private
4087 * @param {Array} array The array to iterate over.
4088 * @param {Function} setter The function to set `accumulator` values.
4089 * @param {Function} iteratee The iteratee to transform keys.
4090 * @param {Object} accumulator The initial aggregated object.
4091 * @returns {Function} Returns `accumulator`.
4092 */
4093 function arrayAggregator(array, setter, iteratee, accumulator) {
4094 var index = -1,
4095 length = array.length;
4096
4097 while (++index < length) {
4098 var value = array[index];
4099 setter(accumulator, value, iteratee(value), array);
4100 }
4101 return accumulator;
4102 }
4103
4104 /**
4105 * Creates a new array concatenating `array` with `other`.
4106 *
4107 * @private
4108 * @param {Array} array The first array to concatenate.
4109 * @param {Array} other The second array to concatenate.
4110 * @returns {Array} Returns the new concatenated array.
4111 */
4112 function arrayConcat(array, other) {
4113 var index = -1,
4114 length = array.length,
4115 othIndex = -1,
4116 othLength = other.length,
4117 result = Array(length + othLength);
4118
4119 while (++index < length) {
4120 result[index] = array[index];
4121 }
4122 while (++othIndex < othLength) {
4123 result[index++] = other[othIndex];
4124 }
4125 return result;
4126 }
4127
4128 /**
4129 * A specialized version of `_.forEach` for arrays without support for
4130 * iteratee shorthands.
4131 *
4132 * @private
4133 * @param {Array} array The array to iterate over.
4134 * @param {Function} iteratee The function invoked per iteration.
4135 * @returns {Array} Returns `array`.
4136 */
4137 function arrayEach(array, iteratee) {
4138 var index = -1,
4139 length = array.length;
4140
4141 while (++index < length) {
4142 if (iteratee(array[index], index, array) === false) {
4143 break;
4144 }
4145 }
4146 return array;
4147 }
4148
4149 /**
4150 * A specialized version of `_.forEachRight` for arrays without support for
4151 * iteratee shorthands.
4152 *
4153 * @private
4154 * @param {Array} array The array to iterate over.
4155 * @param {Function} iteratee The function invoked per iteration.
4156 * @returns {Array} Returns `array`.
4157 */
4158 function arrayEachRight(array, iteratee) {
4159 var length = array.length;
4160
4161 while (length--) {
4162 if (iteratee(array[length], length, array) === false) {
4163 break;
4164 }
4165 }
4166 return array;
4167 }
4168
4169 /**
4170 * A specialized version of `_.every` for arrays without support for
4171 * iteratee shorthands.
4172 *
4173 * @private
4174 * @param {Array} array The array to iterate over.
4175 * @param {Function} predicate The function invoked per iteration.
4176 * @returns {boolean} Returns `true` if all elements pass the predicate check, else `false`.
4177 */
4178 function arrayEvery(array, predicate) {
4179 var index = -1,
4180 length = array.length;
4181
4182 while (++index < length) {
4183 if (!predicate(array[index], index, array)) {
4184 return false;
4185 }
4186 }
4187 return true;
4188 }
4189
4190 /**
4191 * A specialized version of `_.filter` for arrays without support for
4192 * iteratee shorthands.
4193 *
4194 * @private
4195 * @param {Array} array The array to iterate over.
4196 * @param {Function} predicate The function invoked per iteration.
4197 * @returns {Array} Returns the new filtered array.
4198 */
4199 function arrayFilter(array, predicate) {
4200 var index = -1,
4201 length = array.length,
4202 resIndex = 0,
4203 result = [];
4204
4205 while (++index < length) {
4206 var value = array[index];
4207 if (predicate(value, index, array)) {
4208 result[resIndex++] = value;
4209 }
4210 }
4211 return result;
4212 }
4213
4214 /**
4215 * A specialized version of `_.includes` for arrays without support for
4216 * specifying an index to search from.
4217 *
4218 * @private
4219 * @param {Array} array The array to search.
4220 * @param {*} target The value to search for.
4221 * @returns {boolean} Returns `true` if `target` is found, else `false`.
4222 */
4223 function arrayIncludes(array, value) {
4224 return !!array.length && baseIndexOf(array, value, 0) > -1;
4225 }
4226
4227 /**
4228 * This function is like `arrayIncludes` except that it accepts a comparator.
4229 *
4230 * @private
4231 * @param {Array} array The array to search.
4232 * @param {*} target The value to search for.
4233 * @param {Function} comparator The comparator invoked per element.
4234 * @returns {boolean} Returns `true` if `target` is found, else `false`.
4235 */
4236 function arrayIncludesWith(array, value, comparator) {
4237 var index = -1,
4238 length = array.length;
4239
4240 while (++index < length) {
4241 if (comparator(value, array[index])) {
4242 return true;
4243 }
4244 }
4245 return false;
4246 }
4247
4248 /**
4249 * A specialized version of `_.map` for arrays without support for iteratee
4250 * shorthands.
4251 *
4252 * @private
4253 * @param {Array} array The array to iterate over.
4254 * @param {Function} iteratee The function invoked per iteration.
4255 * @returns {Array} Returns the new mapped array.
4256 */
4257 function arrayMap(array, iteratee) {
4258 var index = -1,
4259 length = array.length,
4260 result = Array(length);
4261
4262 while (++index < length) {
4263 result[index] = iteratee(array[index], index, array);
4264 }
4265 return result;
4266 }
4267
4268 /**
4269 * Appends the elements of `values` to `array`.
4270 *
4271 * @private
4272 * @param {Array} array The array to modify.
4273 * @param {Array} values The values to append.
4274 * @returns {Array} Returns `array`.
4275 */
4276 function arrayPush(array, values) {
4277 var index = -1,
4278 length = values.length,
4279 offset = array.length;
4280
4281 while (++index < length) {
4282 array[offset + index] = values[index];
4283 }
4284 return array;
4285 }
4286
4287 /**
4288 * A specialized version of `_.reduce` for arrays without support for
4289 * iteratee shorthands.
4290 *
4291 * @private
4292 * @param {Array} array The array to iterate over.
4293 * @param {Function} iteratee The function invoked per iteration.
4294 * @param {*} [accumulator] The initial value.
4295 * @param {boolean} [initAccum] Specify using the first element of `array` as the initial value.
4296 * @returns {*} Returns the accumulated value.
4297 */
4298 function arrayReduce(array, iteratee, accumulator, initAccum) {
4299 var index = -1,
4300 length = array.length;
4301
4302 if (initAccum && length) {
4303 accumulator = array[++index];
4304 }
4305 while (++index < length) {
4306 accumulator = iteratee(accumulator, array[index], index, array);
4307 }
4308 return accumulator;
4309 }
4310
4311 /**
4312 * A specialized version of `_.reduceRight` for arrays without support for
4313 * iteratee shorthands.
4314 *
4315 * @private
4316 * @param {Array} array The array to iterate over.
4317 * @param {Function} iteratee The function invoked per iteration.
4318 * @param {*} [accumulator] The initial value.
4319 * @param {boolean} [initAccum] Specify using the last element of `array` as the initial value.
4320 * @returns {*} Returns the accumulated value.
4321 */
4322 function arrayReduceRight(array, iteratee, accumulator, initAccum) {
4323 var length = array.length;
4324 if (initAccum && length) {
4325 accumulator = array[--length];
4326 }
4327 while (length--) {
4328 accumulator = iteratee(accumulator, array[length], length, array);
4329 }
4330 return accumulator;
4331 }
4332
4333 /**
4334 * A specialized version of `_.some` for arrays without support for iteratee
4335 * shorthands.
4336 *
4337 * @private
4338 * @param {Array} array The array to iterate over.
4339 * @param {Function} predicate The function invoked per iteration.
4340 * @returns {boolean} Returns `true` if any element passes the predicate check, else `false`.
4341 */
4342 function arraySome(array, predicate) {
4343 var index = -1,
4344 length = array.length;
4345
4346 while (++index < length) {
4347 if (predicate(array[index], index, array)) {
4348 return true;
4349 }
4350 }
4351 return false;
4352 }
4353
4354 /**
4355 * The base implementation of methods like `_.max` and `_.min` which accepts a
4356 * `comparator` to determine the extremum value.
4357 *
4358 * @private
4359 * @param {Array} array The array to iterate over.
4360 * @param {Function} iteratee The iteratee invoked per iteration.
4361 * @param {Function} comparator The comparator used to compare values.
4362 * @returns {*} Returns the extremum value.
4363 */
4364 function baseExtremum(array, iteratee, comparator) {
4365 var index = -1,
4366 length = array.length;
4367
4368 while (++index < length) {
4369 var value = array[index],
4370 current = iteratee(value);
4371
4372 if (current != null && (computed === undefined
4373 ? current === current
4374 : comparator(current, computed)
4375 )) {
4376 var computed = current,
4377 result = value;
4378 }
4379 }
4380 return result;
4381 }
4382
4383 /**
4384 * The base implementation of methods like `_.find` and `_.findKey`, without
4385 * support for iteratee shorthands, which iterates over `collection` using
4386 * `eachFunc`.
4387 *
4388 * @private
4389 * @param {Array|Object} collection The collection to search.
4390 * @param {Function} predicate The function invoked per iteration.
4391 * @param {Function} eachFunc The function to iterate over `collection`.
4392 * @param {boolean} [retKey] Specify returning the key of the found element instead of the element itself.
4393 * @returns {*} Returns the found element or its key, else `undefined`.
4394 */
4395 function baseFind(collection, predicate, eachFunc, retKey) {
4396 var result;
4397 eachFunc(collection, function(value, key, collection) {
4398 if (predicate(value, key, collection)) {
4399 result = retKey ? key : value;
4400 return false;
4401 }
4402 });
4403 return result;
4404 }
4405
4406 /**
4407 * The base implementation of `_.findIndex` and `_.findLastIndex` without
4408 * support for iteratee shorthands.
4409 *
4410 * @private
4411 * @param {Array} array The array to search.
4412 * @param {Function} predicate The function invoked per iteration.
4413 * @param {boolean} [fromRight] Specify iterating from right to left.
4414 * @returns {number} Returns the index of the matched value, else `-1`.
4415 */
4416 function baseFindIndex(array, predicate, fromRight) {
4417 var length = array.length,
4418 index = fromRight ? length : -1;
4419
4420 while ((fromRight ? index-- : ++index < length)) {
4421 if (predicate(array[index], index, array)) {
4422 return index;
4423 }
4424 }
4425 return -1;
4426 }
4427
4428 /**
4429 * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
4430 *
4431 * @private
4432 * @param {Array} array The array to search.
4433 * @param {*} value The value to search for.
4434 * @param {number} fromIndex The index to search from.
4435 * @returns {number} Returns the index of the matched value, else `-1`.
4436 */
4437 function baseIndexOf(array, value, fromIndex) {
4438 if (value !== value) {
4439 return indexOfNaN(array, fromIndex);
4440 }
4441 var index = fromIndex - 1,
4442 length = array.length;
4443
4444 while (++index < length) {
4445 if (array[index] === value) {
4446 return index;
4447 }
4448 }
4449 return -1;
4450 }
4451
4452 /**
4453 * This function is like `baseIndexOf` except that it accepts a comparator.
4454 *
4455 * @private
4456 * @param {Array} array The array to search.
4457 * @param {*} value The value to search for.
4458 * @param {number} fromIndex The index to search from.
4459 * @param {Function} comparator The comparator invoked per element.
4460 * @returns {number} Returns the index of the matched value, else `-1`.
4461 */
4462 function baseIndexOfWith(array, value, fromIndex, comparator) {
4463 var index = fromIndex - 1,
4464 length = array.length;
4465
4466 while (++index < length) {
4467 if (comparator(array[index], value)) {
4468 return index;
4469 }
4470 }
4471 return -1;
4472 }
4473
4474 /**
4475 * The base implementation of `_.reduce` and `_.reduceRight`, without support
4476 * for iteratee shorthands, which iterates over `collection` using `eachFunc`.
4477 *
4478 * @private
4479 * @param {Array|Object} collection The collection to iterate over.
4480 * @param {Function} iteratee The function invoked per iteration.
4481 * @param {*} accumulator The initial value.
4482 * @param {boolean} initAccum Specify using the first or last element of `collection` as the initial value.
4483 * @param {Function} eachFunc The function to iterate over `collection`.
4484 * @returns {*} Returns the accumulated value.
4485 */
4486 function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
4487 eachFunc(collection, function(value, index, collection) {
4488 accumulator = initAccum
4489 ? (initAccum = false, value)
4490 : iteratee(accumulator, value, index, collection);
4491 });
4492 return accumulator;
4493 }
4494
4495 /**
4496 * The base implementation of `_.sortBy` which uses `comparer` to define the
4497 * sort order of `array` and replaces criteria objects with their corresponding
4498 * values.
4499 *
4500 * @private
4501 * @param {Array} array The array to sort.
4502 * @param {Function} comparer The function to define sort order.
4503 * @returns {Array} Returns `array`.
4504 */
4505 function baseSortBy(array, comparer) {
4506 var length = array.length;
4507
4508 array.sort(comparer);
4509 while (length--) {
4510 array[length] = array[length].value;
4511 }
4512 return array;
4513 }
4514
4515 /**
4516 * The base implementation of `_.sum` without support for iteratee shorthands.
4517 *
4518 * @private
4519 * @param {Array} array The array to iterate over.
4520 * @param {Function} iteratee The function invoked per iteration.
4521 * @returns {number} Returns the sum.
4522 */
4523 function baseSum(array, iteratee) {
4524 var result,
4525 index = -1,
4526 length = array.length;
4527
4528 while (++index < length) {
4529 var current = iteratee(array[index]);
4530 if (current !== undefined) {
4531 result = result === undefined ? current : (result + current);
4532 }
4533 }
4534 return result;
4535 }
4536
4537 /**
4538 * The base implementation of `_.times` without support for iteratee shorthands
4539 * or max array length checks.
4540 *
4541 * @private
4542 * @param {number} n The number of times to invoke `iteratee`.
4543 * @param {Function} iteratee The function invoked per iteration.
4544 * @returns {Array} Returns the array of results.
4545 */
4546 function baseTimes(n, iteratee) {
4547 var index = -1,
4548 result = Array(n);
4549
4550 while (++index < n) {
4551 result[index] = iteratee(index);
4552 }
4553 return result;
4554 }
4555
4556 /**
4557 * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array
4558 * of key-value pairs for `object` corresponding to the property names of `props`.
4559 *
4560 * @private
4561 * @param {Object} object The object to query.
4562 * @param {Array} props The property names to get values for.
4563 * @returns {Object} Returns the new array of key-value pairs.
4564 */
4565 function baseToPairs(object, props) {
4566 return arrayMap(props, function(key) {
4567 return [key, object[key]];
4568 });
4569 }
4570
4571 /**
4572 * The base implementation of `_.unary` without support for storing wrapper metadata.
4573 *
4574 * @private
4575 * @param {Function} func The function to cap arguments for.
4576 * @returns {Function} Returns the new function.
4577 */
4578 function baseUnary(func) {
4579 return function(value) {
4580 return func(value);
4581 };
4582 }
4583
4584 /**
4585 * The base implementation of `_.values` and `_.valuesIn` which creates an
4586 * array of `object` property values corresponding to the property names
4587 * of `props`.
4588 *
4589 * @private
4590 * @param {Object} object The object to query.
4591 * @param {Array} props The property names to get values for.
4592 * @returns {Object} Returns the array of property values.
4593 */
4594 function baseValues(object, props) {
4595 return arrayMap(props, function(key) {
4596 return object[key];
4597 });
4598 }
4599
4600 /**
4601 * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
4602 * that is not found in the character symbols.
4603 *
4604 * @private
4605 * @param {Array} strSymbols The string symbols to inspect.
4606 * @param {Array} chrSymbols The character symbols to find.
4607 * @returns {number} Returns the index of the first unmatched string symbol.
4608 */
4609 function charsStartIndex(strSymbols, chrSymbols) {
4610 var index = -1,
4611 length = strSymbols.length;
4612
4613 while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
4614 return index;
4615 }
4616
4617 /**
4618 * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
4619 * that is not found in the character symbols.
4620 *
4621 * @private
4622 * @param {Array} strSymbols The string symbols to inspect.
4623 * @param {Array} chrSymbols The character symbols to find.
4624 * @returns {number} Returns the index of the last unmatched string symbol.
4625 */
4626 function charsEndIndex(strSymbols, chrSymbols) {
4627 var index = strSymbols.length;
4628
4629 while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
4630 return index;
4631 }
4632
4633 /**
4634 * Checks if `value` is a global object.
4635 *
4636 * @private
4637 * @param {*} value The value to check.
4638 * @returns {null|Object} Returns `value` if it's a global object, else `null`.
4639 */
4640 function checkGlobal(value) {
4641 return (value && value.Object === Object) ? value : null;
4642 }
4643
4644 /**
4645 * Compares values to sort them in ascending order.
4646 *
4647 * @private
4648 * @param {*} value The value to compare.
4649 * @param {*} other The other value to compare.
4650 * @returns {number} Returns the sort order indicator for `value`.
4651 */
4652 function compareAscending(value, other) {
4653 if (value !== other) {
4654 var valIsNull = value === null,
4655 valIsUndef = value === undefined,
4656 valIsReflexive = value === value;
4657
4658 var othIsNull = other === null,
4659 othIsUndef = other === undefined,
4660 othIsReflexive = other === other;
4661
4662 if ((value > other && !othIsNull) || !valIsReflexive ||
4663 (valIsNull && !othIsUndef && othIsReflexive) ||
4664 (valIsUndef && othIsReflexive)) {
4665 return 1;
4666 }
4667 if ((value < other && !valIsNull) || !othIsReflexive ||
4668 (othIsNull && !valIsUndef && valIsReflexive) ||
4669 (othIsUndef && valIsReflexive)) {
4670 return -1;
4671 }
4672 }
4673 return 0;
4674 }
4675
4676 /**
4677 * Used by `_.orderBy` to compare multiple properties of a value to another
4678 * and stable sort them.
4679 *
4680 * If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
4681 * specify an order of "desc" for descending or "asc" for ascending sort order
4682 * of corresponding values.
4683 *
4684 * @private
4685 * @param {Object} object The object to compare.
4686 * @param {Object} other The other object to compare.
4687 * @param {boolean[]|string[]} orders The order to sort by for each property.
4688 * @returns {number} Returns the sort order indicator for `object`.
4689 */
4690 function compareMultiple(object, other, orders) {
4691 var index = -1,
4692 objCriteria = object.criteria,
4693 othCriteria = other.criteria,
4694 length = objCriteria.length,
4695 ordersLength = orders.length;
4696
4697 while (++index < length) {
4698 var result = compareAscending(objCriteria[index], othCriteria[index]);
4699 if (result) {
4700 if (index >= ordersLength) {
4701 return result;
4702 }
4703 var order = orders[index];
4704 return result * (order == 'desc' ? -1 : 1);
4705 }
4706 }
4707 // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
4708 // that causes it, under certain circumstances, to provide the same value for
4709 // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
4710 // for more details.
4711 //
4712 // This also ensures a stable sort in V8 and other engines.
4713 // See https://code.google.com/p/v8/issues/detail?id=90 for more details.
4714 return object.index - other.index;
4715 }
4716
4717 /**
4718 * Gets the number of `placeholder` occurrences in `array`.
4719 *
4720 * @private
4721 * @param {Array} array The array to inspect.
4722 * @param {*} placeholder The placeholder to search for.
4723 * @returns {number} Returns the placeholder count.
4724 */
4725 function countHolders(array, placeholder) {
4726 var length = array.length,
4727 result = 0;
4728
4729 while (length--) {
4730 if (array[length] === placeholder) {
4731 result++;
4732 }
4733 }
4734 return result;
4735 }
4736
4737 /**
4738 * Used by `_.deburr` to convert latin-1 supplementary letters to basic latin letters.
4739 *
4740 * @private
4741 * @param {string} letter The matched letter to deburr.
4742 * @returns {string} Returns the deburred letter.
4743 */
4744 function deburrLetter(letter) {
4745 return deburredLetters[letter];
4746 }
4747
4748 /**
4749 * Used by `_.escape` to convert characters to HTML entities.
4750 *
4751 * @private
4752 * @param {string} chr The matched character to escape.
4753 * @returns {string} Returns the escaped character.
4754 */
4755 function escapeHtmlChar(chr) {
4756 return htmlEscapes[chr];
4757 }
4758
4759 /**
4760 * Used by `_.template` to escape characters for inclusion in compiled string literals.
4761 *
4762 * @private
4763 * @param {string} chr The matched character to escape.
4764 * @returns {string} Returns the escaped character.
4765 */
4766 function escapeStringChar(chr) {
4767 return '\\' + stringEscapes[chr];
4768 }
4769
4770 /**
4771 * Gets the index at which the first occurrence of `NaN` is found in `array`.
4772 *
4773 * @private
4774 * @param {Array} array The array to search.
4775 * @param {number} fromIndex The index to search from.
4776 * @param {boolean} [fromRight] Specify iterating from right to left.
4777 * @returns {number} Returns the index of the matched `NaN`, else `-1`.
4778 */
4779 function indexOfNaN(array, fromIndex, fromRight) {
4780 var length = array.length,
4781 index = fromIndex + (fromRight ? 0 : -1);
4782
4783 while ((fromRight ? index-- : ++index < length)) {
4784 var other = array[index];
4785 if (other !== other) {
4786 return index;
4787 }
4788 }
4789 return -1;
4790 }
4791
4792 /**
4793 * Checks if `value` is a host object in IE < 9.
4794 *
4795 * @private
4796 * @param {*} value The value to check.
4797 * @returns {boolean} Returns `true` if `value` is a host object, else `false`.
4798 */
4799 function isHostObject(value) {
4800 // Many host objects are `Object` objects that can coerce to strings
4801 // despite having improperly defined `toString` methods.
4802 var result = false;
4803 if (value != null && typeof value.toString != 'function') {
4804 try {
4805 result = !!(value + '');
4806 } catch (e) {}
4807 }
4808 return result;
4809 }
4810
4811 /**
4812 * Checks if `value` is a valid array-like index.
4813 *
4814 * @private
4815 * @param {*} value The value to check.
4816 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
4817 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
4818 */
4819 function isIndex(value, length) {
4820 value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
4821 length = length == null ? MAX_SAFE_INTEGER : length;
4822 return value > -1 && value % 1 == 0 && value < length;
4823 }
4824
4825 /**
4826 * Converts `iterator` to an array.
4827 *
4828 * @private
4829 * @param {Object} iterator The iterator to convert.
4830 * @returns {Array} Returns the converted array.
4831 */
4832 function iteratorToArray(iterator) {
4833 var data,
4834 result = [];
4835
4836 while (!(data = iterator.next()).done) {
4837 result.push(data.value);
4838 }
4839 return result;
4840 }
4841
4842 /**
4843 * Converts `map` to an array.
4844 *
4845 * @private
4846 * @param {Object} map The map to convert.
4847 * @returns {Array} Returns the converted array.
4848 */
4849 function mapToArray(map) {
4850 var index = -1,
4851 result = Array(map.size);
4852
4853 map.forEach(function(value, key) {
4854 result[++index] = [key, value];
4855 });
4856 return result;
4857 }
4858
4859 /**
4860 * Replaces all `placeholder` elements in `array` with an internal placeholder
4861 * and returns an array of their indexes.
4862 *
4863 * @private
4864 * @param {Array} array The array to modify.
4865 * @param {*} placeholder The placeholder to replace.
4866 * @returns {Array} Returns the new array of placeholder indexes.
4867 */
4868 function replaceHolders(array, placeholder) {
4869 var index = -1,
4870 length = array.length,
4871 resIndex = 0,
4872 result = [];
4873
4874 while (++index < length) {
4875 var value = array[index];
4876 if (value === placeholder || value === PLACEHOLDER) {
4877 array[index] = PLACEHOLDER;
4878 result[resIndex++] = index;
4879 }
4880 }
4881 return result;
4882 }
4883
4884 /**
4885 * Converts `set` to an array.
4886 *
4887 * @private
4888 * @param {Object} set The set to convert.
4889 * @returns {Array} Returns the converted array.
4890 */
4891 function setToArray(set) {
4892 var index = -1,
4893 result = Array(set.size);
4894
4895 set.forEach(function(value) {
4896 result[++index] = value;
4897 });
4898 return result;
4899 }
4900
4901 /**
4902 * Gets the number of symbols in `string`.
4903 *
4904 * @private
4905 * @param {string} string The string to inspect.
4906 * @returns {number} Returns the string size.
4907 */
4908 function stringSize(string) {
4909 if (!(string && reHasComplexSymbol.test(string))) {
4910 return string.length;
4911 }
4912 var result = reComplexSymbol.lastIndex = 0;
4913 while (reComplexSymbol.test(string)) {
4914 result++;
4915 }
4916 return result;
4917 }
4918
4919 /**
4920 * Converts `string` to an array.
4921 *
4922 * @private
4923 * @param {string} string The string to convert.
4924 * @returns {Array} Returns the converted array.
4925 */
4926 function stringToArray(string) {
4927 return string.match(reComplexSymbol);
4928 }
4929
4930 /**
4931 * Used by `_.unescape` to convert HTML entities to characters.
4932 *
4933 * @private
4934 * @param {string} chr The matched character to unescape.
4935 * @returns {string} Returns the unescaped character.
4936 */
4937 function unescapeHtmlChar(chr) {
4938 return htmlUnescapes[chr];
4939 }
4940
4941 /*--------------------------------------------------------------------------*/
4942
4943 /**
4944 * Create a new pristine `lodash` function using the `context` object.
4945 *
4946 * @static
4947 * @memberOf _
4948 * @category Util
4949 * @param {Object} [context=root] The context object.
4950 * @returns {Function} Returns a new `lodash` function.
4951 * @example
4952 *
4953 * _.mixin({ 'foo': _.constant('foo') });
4954 *
4955 * var lodash = _.runInContext();
4956 * lodash.mixin({ 'bar': lodash.constant('bar') });
4957 *
4958 * _.isFunction(_.foo);
4959 * // => true
4960 * _.isFunction(_.bar);
4961 * // => false
4962 *
4963 * lodash.isFunction(lodash.foo);
4964 * // => false
4965 * lodash.isFunction(lodash.bar);
4966 * // => true
4967 *
4968 * // Use `context` to mock `Date#getTime` use in `_.now`.
4969 * var mock = _.runInContext({
4970 * 'Date': function() {
4971 * return { 'getTime': getTimeMock };
4972 * }
4973 * });
4974 *
4975 * // Create a suped-up `defer` in Node.js.
4976 * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
4977 */
4978 function runInContext(context) {
4979 context = context ? _.defaults({}, context, _.pick(root, contextProps)) : root;
4980
4981 /** Built-in constructor references. */
4982 var Date = context.Date,
4983 Error = context.Error,
4984 Math = context.Math,
4985 RegExp = context.RegExp,
4986 TypeError = context.TypeError;
4987
4988 /** Used for built-in method references. */
4989 var arrayProto = context.Array.prototype,
4990 objectProto = context.Object.prototype;
4991
4992 /** Used to resolve the decompiled source of functions. */
4993 var funcToString = context.Function.prototype.toString;
4994
4995 /** Used to check objects for own properties. */
4996 var hasOwnProperty = objectProto.hasOwnProperty;
4997
4998 /** Used to generate unique IDs. */
4999 var idCounter = 0;
5000
5001 /** Used to infer the `Object` constructor. */
5002 var objectCtorString = funcToString.call(Object);
5003
5004 /**
5005 * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
5006 * of values.
5007 */
5008 var objectToString = objectProto.toString;
5009
5010 /** Used to restore the original `_` reference in `_.noConflict`. */
5011 var oldDash = root._;
5012
5013 /** Used to detect if a method is native. */
5014 var reIsNative = RegExp('^' +
5015 funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
5016 .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
5017 );
5018
5019 /** Built-in value references. */
5020 var Buffer = moduleExports ? context.Buffer : undefined,
5021 Reflect = context.Reflect,
5022 Symbol = context.Symbol,
5023 Uint8Array = context.Uint8Array,
5024 clearTimeout = context.clearTimeout,
5025 enumerate = Reflect ? Reflect.enumerate : undefined,
5026 getPrototypeOf = Object.getPrototypeOf,
5027 getOwnPropertySymbols = Object.getOwnPropertySymbols,
5028 iteratorSymbol = typeof (iteratorSymbol = Symbol && Symbol.iterator) == 'symbol' ? iteratorSymbol : undefined,
5029 objectCreate = Object.create,
5030 propertyIsEnumerable = objectProto.propertyIsEnumerable,
5031 setTimeout = context.setTimeout,
5032 splice = arrayProto.splice;
5033
5034 /* Built-in method references for those with the same name as other `lodash` methods. */
5035 var nativeCeil = Math.ceil,
5036 nativeFloor = Math.floor,
5037 nativeIsFinite = context.isFinite,
5038 nativeJoin = arrayProto.join,
5039 nativeKeys = Object.keys,
5040 nativeMax = Math.max,
5041 nativeMin = Math.min,
5042 nativeParseInt = context.parseInt,
5043 nativeRandom = Math.random,
5044 nativeReverse = arrayProto.reverse;
5045
5046 /* Built-in method references that are verified to be native. */
5047 var Map = getNative(context, 'Map'),
5048 Set = getNative(context, 'Set'),
5049 WeakMap = getNative(context, 'WeakMap'),
5050 nativeCreate = getNative(Object, 'create');
5051
5052 /** Used to store function metadata. */
5053 var metaMap = WeakMap && new WeakMap;
5054
5055 /** Detect if properties shadowing those on `Object.prototype` are non-enumerable. */
5056 var nonEnumShadows = !propertyIsEnumerable.call({ 'valueOf': 1 }, 'valueOf');
5057
5058 /** Used to lookup unminified function names. */
5059 var realNames = {};
5060
5061 /** Used to detect maps, sets, and weakmaps. */
5062 var mapCtorString = Map ? funcToString.call(Map) : '',
5063 setCtorString = Set ? funcToString.call(Set) : '',
5064 weakMapCtorString = WeakMap ? funcToString.call(WeakMap) : '';
5065
5066 /** Used to convert symbols to primitives and strings. */
5067 var symbolProto = Symbol ? Symbol.prototype : undefined,
5068 symbolValueOf = symbolProto ? symbolProto.valueOf : undefined,
5069 symbolToString = symbolProto ? symbolProto.toString : undefined;
5070
5071 /*------------------------------------------------------------------------*/
5072
5073 /**
5074 * Creates a `lodash` object which wraps `value` to enable implicit method
5075 * chaining. Methods that operate on and return arrays, collections, and
5076 * functions can be chained together. Methods that retrieve a single value or
5077 * may return a primitive value will automatically end the chain sequence and
5078 * return the unwrapped value. Otherwise, the value must be unwrapped with
5079 * `_#value`.
5080 *
5081 * Explicit chaining, which must be unwrapped with `_#value` in all cases,
5082 * may be enabled using `_.chain`.
5083 *
5084 * The execution of chained methods is lazy, that is, it's deferred until
5085 * `_#value` is implicitly or explicitly called.
5086 *
5087 * Lazy evaluation allows several methods to support shortcut fusion. Shortcut
5088 * fusion is an optimization to merge iteratee calls; this avoids the creation
5089 * of intermediate arrays and can greatly reduce the number of iteratee executions.
5090 * Sections of a chain sequence qualify for shortcut fusion if the section is
5091 * applied to an array of at least two hundred elements and any iteratees
5092 * accept only one argument. The heuristic for whether a section qualifies
5093 * for shortcut fusion is subject to change.
5094 *
5095 * Chaining is supported in custom builds as long as the `_#value` method is
5096 * directly or indirectly included in the build.
5097 *
5098 * In addition to lodash methods, wrappers have `Array` and `String` methods.
5099 *
5100 * The wrapper `Array` methods are:
5101 * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
5102 *
5103 * The wrapper `String` methods are:
5104 * `replace` and `split`
5105 *
5106 * The wrapper methods that support shortcut fusion are:
5107 * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
5108 * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
5109 * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
5110 *
5111 * The chainable wrapper methods are:
5112 * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
5113 * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
5114 * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
5115 * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
5116 * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
5117 * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
5118 * `flatten`, `flattenDeep`, `flattenDepth`, `flip`, `flow`, `flowRight`,
5119 * `fromPairs`, `functions`, `functionsIn`, `groupBy`, `initial`, `intersection`,
5120 * `intersectionBy`, `intersectionWith`, `invert`, `invertBy`, `invokeMap`,
5121 * `iteratee`, `keyBy`, `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`,
5122 * `matches`, `matchesProperty`, `memoize`, `merge`, `mergeWith`, `method`,
5123 * `methodOf`, `mixin`, `negate`, `nthArg`, `omit`, `omitBy`, `once`, `orderBy`,
5124 * `over`, `overArgs`, `overEvery`, `overSome`, `partial`, `partialRight`,
5125 * `partition`, `pick`, `pickBy`, `plant`, `property`, `propertyOf`, `pull`,
5126 * `pullAll`, `pullAllBy`, `pullAllWith`, `pullAt`, `push`, `range`,
5127 * `rangeRight`, `rearg`, `reject`, `remove`, `rest`, `reverse`, `sampleSize`,
5128 * `set`, `setWith`, `shuffle`, `slice`, `sort`, `sortBy`, `splice`, `spread`,
5129 * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `tap`, `throttle`,
5130 * `thru`, `toArray`, `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`,
5131 * `transform`, `unary`, `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`,
5132 * `uniqWith`, `unset`, `unshift`, `unzip`, `unzipWith`, `update`, `values`,
5133 * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, `zipObject`,
5134 * `zipObjectDeep`, and `zipWith`
5135 *
5136 * The wrapper methods that are **not** chainable by default are:
5137 * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
5138 * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `deburr`, `each`, `eachRight`,
5139 * `endsWith`, `eq`, `escape`, `escapeRegExp`, `every`, `find`, `findIndex`,
5140 * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `first`, `floor`,
5141 * `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`,
5142 * `get`, `gt`, `gte`, `has`, `hasIn`, `head`, `identity`, `includes`,
5143 * `indexOf`, `inRange`, `invoke`, `isArguments`, `isArray`, `isArrayBuffer`,
5144 * `isArrayLike`, `isArrayLikeObject`, `isBoolean`, `isBuffer`, `isDate`,
5145 * `isElement`, `isEmpty`, `isEqual`, `isEqualWith`, `isError`, `isFinite`,
5146 * `isFunction`, `isInteger`, `isLength`, `isMap`, `isMatch`, `isMatchWith`,
5147 * `isNaN`, `isNative`, `isNil`, `isNull`, `isNumber`, `isObject`, `isObjectLike`,
5148 * `isPlainObject`, `isRegExp`, `isSafeInteger`, `isSet`, `isString`,
5149 * `isUndefined`, `isTypedArray`, `isWeakMap`, `isWeakSet`, `join`, `kebabCase`,
5150 * `last`, `lastIndexOf`, `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`,
5151 * `maxBy`, `mean`, `min`, `minBy`, `noConflict`, `noop`, `now`, `pad`,
5152 * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
5153 * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
5154 * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
5155 * `sortedLastIndexBy`, `startCase`, `startsWith`, `subtract`, `sum`, `sumBy`,
5156 * `template`, `times`, `toInteger`, `toJSON`, `toLength`, `toLower`,
5157 * `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, `trimEnd`,
5158 * `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, `upperFirst`,
5159 * `value`, and `words`
5160 *
5161 * @name _
5162 * @constructor
5163 * @category Seq
5164 * @param {*} value The value to wrap in a `lodash` instance.
5165 * @returns {Object} Returns the new `lodash` wrapper instance.
5166 * @example
5167 *
5168 * function square(n) {
5169 * return n * n;
5170 * }
5171 *
5172 * var wrapped = _([1, 2, 3]);
5173 *
5174 * // Returns an unwrapped value.
5175 * wrapped.reduce(_.add);
5176 * // => 6
5177 *
5178 * // Returns a wrapped value.
5179 * var squares = wrapped.map(square);
5180 *
5181 * _.isArray(squares);
5182 * // => false
5183 *
5184 * _.isArray(squares.value());
5185 * // => true
5186 */
5187 function lodash(value) {
5188 if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
5189 if (value instanceof LodashWrapper) {
5190 return value;
5191 }
5192 if (hasOwnProperty.call(value, '__wrapped__')) {
5193 return wrapperClone(value);
5194 }
5195 }
5196 return new LodashWrapper(value);
5197 }
5198
5199 /**
5200 * The function whose prototype all chaining wrappers inherit from.
5201 *
5202 * @private
5203 */
5204 function baseLodash() {
5205 // No operation performed.
5206 }
5207
5208 /**
5209 * The base constructor for creating `lodash` wrapper objects.
5210 *
5211 * @private
5212 * @param {*} value The value to wrap.
5213 * @param {boolean} [chainAll] Enable chaining for all wrapper methods.
5214 */
5215 function LodashWrapper(value, chainAll) {
5216 this.__wrapped__ = value;
5217 this.__actions__ = [];
5218 this.__chain__ = !!chainAll;
5219 this.__index__ = 0;
5220 this.__values__ = undefined;
5221 }
5222
5223 /**
5224 * By default, the template delimiters used by lodash are like those in
5225 * embedded Ruby (ERB). Change the following template settings to use
5226 * alternative delimiters.
5227 *
5228 * @static
5229 * @memberOf _
5230 * @type {Object}
5231 */
5232 lodash.templateSettings = {
5233
5234 /**
5235 * Used to detect `data` property values to be HTML-escaped.
5236 *
5237 * @memberOf _.templateSettings
5238 * @type {RegExp}
5239 */
5240 'escape': reEscape,
5241
5242 /**
5243 * Used to detect code to be evaluated.
5244 *
5245 * @memberOf _.templateSettings
5246 * @type {RegExp}
5247 */
5248 'evaluate': reEvaluate,
5249
5250 /**
5251 * Used to detect `data` property values to inject.
5252 *
5253 * @memberOf _.templateSettings
5254 * @type {RegExp}
5255 */
5256 'interpolate': reInterpolate,
5257
5258 /**
5259 * Used to reference the data object in the template text.
5260 *
5261 * @memberOf _.templateSettings
5262 * @type {string}
5263 */
5264 'variable': '',
5265
5266 /**
5267 * Used to import variables into the compiled template.
5268 *
5269 * @memberOf _.templateSettings
5270 * @type {Object}
5271 */
5272 'imports': {
5273
5274 /**
5275 * A reference to the `lodash` function.
5276 *
5277 * @memberOf _.templateSettings.imports
5278 * @type {Function}
5279 */
5280 '_': lodash
5281 }
5282 };
5283
5284 /*------------------------------------------------------------------------*/
5285
5286 /**
5287 * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
5288 *
5289 * @private
5290 * @constructor
5291 * @param {*} value The value to wrap.
5292 */
5293 function LazyWrapper(value) {
5294 this.__wrapped__ = value;
5295 this.__actions__ = [];
5296 this.__dir__ = 1;
5297 this.__filtered__ = false;
5298 this.__iteratees__ = [];
5299 this.__takeCount__ = MAX_ARRAY_LENGTH;
5300 this.__views__ = [];
5301 }
5302
5303 /**
5304 * Creates a clone of the lazy wrapper object.
5305 *
5306 * @private
5307 * @name clone
5308 * @memberOf LazyWrapper
5309 * @returns {Object} Returns the cloned `LazyWrapper` object.
5310 */
5311 function lazyClone() {
5312 var result = new LazyWrapper(this.__wrapped__);
5313 result.__actions__ = copyArray(this.__actions__);
5314 result.__dir__ = this.__dir__;
5315 result.__filtered__ = this.__filtered__;
5316 result.__iteratees__ = copyArray(this.__iteratees__);
5317 result.__takeCount__ = this.__takeCount__;
5318 result.__views__ = copyArray(this.__views__);
5319 return result;
5320 }
5321
5322 /**
5323 * Reverses the direction of lazy iteration.
5324 *
5325 * @private
5326 * @name reverse
5327 * @memberOf LazyWrapper
5328 * @returns {Object} Returns the new reversed `LazyWrapper` object.
5329 */
5330 function lazyReverse() {
5331 if (this.__filtered__) {
5332 var result = new LazyWrapper(this);
5333 result.__dir__ = -1;
5334 result.__filtered__ = true;
5335 } else {
5336 result = this.clone();
5337 result.__dir__ *= -1;
5338 }
5339 return result;
5340 }
5341
5342 /**
5343 * Extracts the unwrapped value from its lazy wrapper.
5344 *
5345 * @private
5346 * @name value
5347 * @memberOf LazyWrapper
5348 * @returns {*} Returns the unwrapped value.
5349 */
5350 function lazyValue() {
5351 var array = this.__wrapped__.value(),
5352 dir = this.__dir__,
5353 isArr = isArray(array),
5354 isRight = dir < 0,
5355 arrLength = isArr ? array.length : 0,
5356 view = getView(0, arrLength, this.__views__),
5357 start = view.start,
5358 end = view.end,
5359 length = end - start,
5360 index = isRight ? end : (start - 1),
5361 iteratees = this.__iteratees__,
5362 iterLength = iteratees.length,
5363 resIndex = 0,
5364 takeCount = nativeMin(length, this.__takeCount__);
5365
5366 if (!isArr || arrLength < LARGE_ARRAY_SIZE ||
5367 (arrLength == length && takeCount == length)) {
5368 return baseWrapperValue(array, this.__actions__);
5369 }
5370 var result = [];
5371
5372 outer:
5373 while (length-- && resIndex < takeCount) {
5374 index += dir;
5375
5376 var iterIndex = -1,
5377 value = array[index];
5378
5379 while (++iterIndex < iterLength) {
5380 var data = iteratees[iterIndex],
5381 iteratee = data.iteratee,
5382 type = data.type,
5383 computed = iteratee(value);
5384
5385 if (type == LAZY_MAP_FLAG) {
5386 value = computed;
5387 } else if (!computed) {
5388 if (type == LAZY_FILTER_FLAG) {
5389 continue outer;
5390 } else {
5391 break outer;
5392 }
5393 }
5394 }
5395 result[resIndex++] = value;
5396 }
5397 return result;
5398 }
5399
5400 /*------------------------------------------------------------------------*/
5401
5402 /**
5403 * Creates an hash object.
5404 *
5405 * @private
5406 * @constructor
5407 * @returns {Object} Returns the new hash object.
5408 */
5409 function Hash() {}
5410
5411 /**
5412 * Removes `key` and its value from the hash.
5413 *
5414 * @private
5415 * @param {Object} hash The hash to modify.
5416 * @param {string} key The key of the value to remove.
5417 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
5418 */
5419 function hashDelete(hash, key) {
5420 return hashHas(hash, key) && delete hash[key];
5421 }
5422
5423 /**
5424 * Gets the hash value for `key`.
5425 *
5426 * @private
5427 * @param {Object} hash The hash to query.
5428 * @param {string} key The key of the value to get.
5429 * @returns {*} Returns the entry value.
5430 */
5431 function hashGet(hash, key) {
5432 if (nativeCreate) {
5433 var result = hash[key];
5434 return result === HASH_UNDEFINED ? undefined : result;
5435 }
5436 return hasOwnProperty.call(hash, key) ? hash[key] : undefined;
5437 }
5438
5439 /**
5440 * Checks if a hash value for `key` exists.
5441 *
5442 * @private
5443 * @param {Object} hash The hash to query.
5444 * @param {string} key The key of the entry to check.
5445 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
5446 */
5447 function hashHas(hash, key) {
5448 return nativeCreate ? hash[key] !== undefined : hasOwnProperty.call(hash, key);
5449 }
5450
5451 /**
5452 * Sets the hash `key` to `value`.
5453 *
5454 * @private
5455 * @param {Object} hash The hash to modify.
5456 * @param {string} key The key of the value to set.
5457 * @param {*} value The value to set.
5458 */
5459 function hashSet(hash, key, value) {
5460 hash[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
5461 }
5462
5463 /*------------------------------------------------------------------------*/
5464
5465 /**
5466 * Creates a map cache object to store key-value pairs.
5467 *
5468 * @private
5469 * @constructor
5470 * @param {Array} [values] The values to cache.
5471 */
5472 function MapCache(values) {
5473 var index = -1,
5474 length = values ? values.length : 0;
5475
5476 this.clear();
5477 while (++index < length) {
5478 var entry = values[index];
5479 this.set(entry[0], entry[1]);
5480 }
5481 }
5482
5483 /**
5484 * Removes all key-value entries from the map.
5485 *
5486 * @private
5487 * @name clear
5488 * @memberOf MapCache
5489 */
5490 function mapClear() {
5491 this.__data__ = {
5492 'hash': new Hash,
5493 'map': Map ? new Map : [],
5494 'string': new Hash
5495 };
5496 }
5497
5498 /**
5499 * Removes `key` and its value from the map.
5500 *
5501 * @private
5502 * @name delete
5503 * @memberOf MapCache
5504 * @param {string} key The key of the value to remove.
5505 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
5506 */
5507 function mapDelete(key) {
5508 var data = this.__data__;
5509 if (isKeyable(key)) {
5510 return hashDelete(typeof key == 'string' ? data.string : data.hash, key);
5511 }
5512 return Map ? data.map['delete'](key) : assocDelete(data.map, key);
5513 }
5514
5515 /**
5516 * Gets the map value for `key`.
5517 *
5518 * @private
5519 * @name get
5520 * @memberOf MapCache
5521 * @param {string} key The key of the value to get.
5522 * @returns {*} Returns the entry value.
5523 */
5524 function mapGet(key) {
5525 var data = this.__data__;
5526 if (isKeyable(key)) {
5527 return hashGet(typeof key == 'string' ? data.string : data.hash, key);
5528 }
5529 return Map ? data.map.get(key) : assocGet(data.map, key);
5530 }
5531
5532 /**
5533 * Checks if a map value for `key` exists.
5534 *
5535 * @private
5536 * @name has
5537 * @memberOf MapCache
5538 * @param {string} key The key of the entry to check.
5539 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
5540 */
5541 function mapHas(key) {
5542 var data = this.__data__;
5543 if (isKeyable(key)) {
5544 return hashHas(typeof key == 'string' ? data.string : data.hash, key);
5545 }
5546 return Map ? data.map.has(key) : assocHas(data.map, key);
5547 }
5548
5549 /**
5550 * Sets the map `key` to `value`.
5551 *
5552 * @private
5553 * @name set
5554 * @memberOf MapCache
5555 * @param {string} key The key of the value to set.
5556 * @param {*} value The value to set.
5557 * @returns {Object} Returns the map cache object.
5558 */
5559 function mapSet(key, value) {
5560 var data = this.__data__;
5561 if (isKeyable(key)) {
5562 hashSet(typeof key == 'string' ? data.string : data.hash, key, value);
5563 } else if (Map) {
5564 data.map.set(key, value);
5565 } else {
5566 assocSet(data.map, key, value);
5567 }
5568 return this;
5569 }
5570
5571 /*------------------------------------------------------------------------*/
5572
5573 /**
5574 *
5575 * Creates a set cache object to store unique values.
5576 *
5577 * @private
5578 * @constructor
5579 * @param {Array} [values] The values to cache.
5580 */
5581 function SetCache(values) {
5582 var index = -1,
5583 length = values ? values.length : 0;
5584
5585 this.__data__ = new MapCache;
5586 while (++index < length) {
5587 this.push(values[index]);
5588 }
5589 }
5590
5591 /**
5592 * Checks if `value` is in `cache`.
5593 *
5594 * @private
5595 * @param {Object} cache The set cache to search.
5596 * @param {*} value The value to search for.
5597 * @returns {number} Returns `true` if `value` is found, else `false`.
5598 */
5599 function cacheHas(cache, value) {
5600 var map = cache.__data__;
5601 if (isKeyable(value)) {
5602 var data = map.__data__,
5603 hash = typeof value == 'string' ? data.string : data.hash;
5604
5605 return hash[value] === HASH_UNDEFINED;
5606 }
5607 return map.has(value);
5608 }
5609
5610 /**
5611 * Adds `value` to the set cache.
5612 *
5613 * @private
5614 * @name push
5615 * @memberOf SetCache
5616 * @param {*} value The value to cache.
5617 */
5618 function cachePush(value) {
5619 var map = this.__data__;
5620 if (isKeyable(value)) {
5621 var data = map.__data__,
5622 hash = typeof value == 'string' ? data.string : data.hash;
5623
5624 hash[value] = HASH_UNDEFINED;
5625 }
5626 else {
5627 map.set(value, HASH_UNDEFINED);
5628 }
5629 }
5630
5631 /*------------------------------------------------------------------------*/
5632
5633 /**
5634 * Creates a stack cache object to store key-value pairs.
5635 *
5636 * @private
5637 * @constructor
5638 * @param {Array} [values] The values to cache.
5639 */
5640 function Stack(values) {
5641 var index = -1,
5642 length = values ? values.length : 0;
5643
5644 this.clear();
5645 while (++index < length) {
5646 var entry = values[index];
5647 this.set(entry[0], entry[1]);
5648 }
5649 }
5650
5651 /**
5652 * Removes all key-value entries from the stack.
5653 *
5654 * @private
5655 * @name clear
5656 * @memberOf Stack
5657 */
5658 function stackClear() {
5659 this.__data__ = { 'array': [], 'map': null };
5660 }
5661
5662 /**
5663 * Removes `key` and its value from the stack.
5664 *
5665 * @private
5666 * @name delete
5667 * @memberOf Stack
5668 * @param {string} key The key of the value to remove.
5669 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
5670 */
5671 function stackDelete(key) {
5672 var data = this.__data__,
5673 array = data.array;
5674
5675 return array ? assocDelete(array, key) : data.map['delete'](key);
5676 }
5677
5678 /**
5679 * Gets the stack value for `key`.
5680 *
5681 * @private
5682 * @name get
5683 * @memberOf Stack
5684 * @param {string} key The key of the value to get.
5685 * @returns {*} Returns the entry value.
5686 */
5687 function stackGet(key) {
5688 var data = this.__data__,
5689 array = data.array;
5690
5691 return array ? assocGet(array, key) : data.map.get(key);
5692 }
5693
5694 /**
5695 * Checks if a stack value for `key` exists.
5696 *
5697 * @private
5698 * @name has
5699 * @memberOf Stack
5700 * @param {string} key The key of the entry to check.
5701 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
5702 */
5703 function stackHas(key) {
5704 var data = this.__data__,
5705 array = data.array;
5706
5707 return array ? assocHas(array, key) : data.map.has(key);
5708 }
5709
5710 /**
5711 * Sets the stack `key` to `value`.
5712 *
5713 * @private
5714 * @name set
5715 * @memberOf Stack
5716 * @param {string} key The key of the value to set.
5717 * @param {*} value The value to set.
5718 * @returns {Object} Returns the stack cache object.
5719 */
5720 function stackSet(key, value) {
5721 var data = this.__data__,
5722 array = data.array;
5723
5724 if (array) {
5725 if (array.length < (LARGE_ARRAY_SIZE - 1)) {
5726 assocSet(array, key, value);
5727 } else {
5728 data.array = null;
5729 data.map = new MapCache(array);
5730 }
5731 }
5732 var map = data.map;
5733 if (map) {
5734 map.set(key, value);
5735 }
5736 return this;
5737 }
5738
5739 /*------------------------------------------------------------------------*/
5740
5741 /**
5742 * Removes `key` and its value from the associative array.
5743 *
5744 * @private
5745 * @param {Array} array The array to query.
5746 * @param {string} key The key of the value to remove.
5747 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
5748 */
5749 function assocDelete(array, key) {
5750 var index = assocIndexOf(array, key);
5751 if (index < 0) {
5752 return false;
5753 }
5754 var lastIndex = array.length - 1;
5755 if (index == lastIndex) {
5756 array.pop();
5757 } else {
5758 splice.call(array, index, 1);
5759 }
5760 return true;
5761 }
5762
5763 /**
5764 * Gets the associative array value for `key`.
5765 *
5766 * @private
5767 * @param {Array} array The array to query.
5768 * @param {string} key The key of the value to get.
5769 * @returns {*} Returns the entry value.
5770 */
5771 function assocGet(array, key) {
5772 var index = assocIndexOf(array, key);
5773 return index < 0 ? undefined : array[index][1];
5774 }
5775
5776 /**
5777 * Checks if an associative array value for `key` exists.
5778 *
5779 * @private
5780 * @param {Array} array The array to query.
5781 * @param {string} key The key of the entry to check.
5782 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
5783 */
5784 function assocHas(array, key) {
5785 return assocIndexOf(array, key) > -1;
5786 }
5787
5788 /**
5789 * Gets the index at which the first occurrence of `key` is found in `array`
5790 * of key-value pairs.
5791 *
5792 * @private
5793 * @param {Array} array The array to search.
5794 * @param {*} key The key to search for.
5795 * @returns {number} Returns the index of the matched value, else `-1`.
5796 */
5797 function assocIndexOf(array, key) {
5798 var length = array.length;
5799 while (length--) {
5800 if (eq(array[length][0], key)) {
5801 return length;
5802 }
5803 }
5804 return -1;
5805 }
5806
5807 /**
5808 * Sets the associative array `key` to `value`.
5809 *
5810 * @private
5811 * @param {Array} array The array to modify.
5812 * @param {string} key The key of the value to set.
5813 * @param {*} value The value to set.
5814 */
5815 function assocSet(array, key, value) {
5816 var index = assocIndexOf(array, key);
5817 if (index < 0) {
5818 array.push([key, value]);
5819 } else {
5820 array[index][1] = value;
5821 }
5822 }
5823
5824 /*------------------------------------------------------------------------*/
5825
5826 /**
5827 * Used by `_.defaults` to customize its `_.assignIn` use.
5828 *
5829 * @private
5830 * @param {*} objValue The destination value.
5831 * @param {*} srcValue The source value.
5832 * @param {string} key The key of the property to assign.
5833 * @param {Object} object The parent object of `objValue`.
5834 * @returns {*} Returns the value to assign.
5835 */
5836 function assignInDefaults(objValue, srcValue, key, object) {
5837 if (objValue === undefined ||
5838 (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) {
5839 return srcValue;
5840 }
5841 return objValue;
5842 }
5843
5844 /**
5845 * This function is like `assignValue` except that it doesn't assign
5846 * `undefined` values.
5847 *
5848 * @private
5849 * @param {Object} object The object to modify.
5850 * @param {string} key The key of the property to assign.
5851 * @param {*} value The value to assign.
5852 */
5853 function assignMergeValue(object, key, value) {
5854 if ((value !== undefined && !eq(object[key], value)) ||
5855 (typeof key == 'number' && value === undefined && !(key in object))) {
5856 object[key] = value;
5857 }
5858 }
5859
5860 /**
5861 * Assigns `value` to `key` of `object` if the existing value is not equivalent
5862 * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
5863 * for equality comparisons.
5864 *
5865 * @private
5866 * @param {Object} object The object to modify.
5867 * @param {string} key The key of the property to assign.
5868 * @param {*} value The value to assign.
5869 */
5870 function assignValue(object, key, value) {
5871 var objValue = object[key];
5872 if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
5873 (value === undefined && !(key in object))) {
5874 object[key] = value;
5875 }
5876 }
5877
5878 /**
5879 * Aggregates elements of `collection` on `accumulator` with keys transformed
5880 * by `iteratee` and values set by `setter`.
5881 *
5882 * @private
5883 * @param {Array|Object} collection The collection to iterate over.
5884 * @param {Function} setter The function to set `accumulator` values.
5885 * @param {Function} iteratee The iteratee to transform keys.
5886 * @param {Object} accumulator The initial aggregated object.
5887 * @returns {Function} Returns `accumulator`.
5888 */
5889 function baseAggregator(collection, setter, iteratee, accumulator) {
5890 baseEach(collection, function(value, key, collection) {
5891 setter(accumulator, value, iteratee(value), collection);
5892 });
5893 return accumulator;
5894 }
5895
5896 /**
5897 * The base implementation of `_.assign` without support for multiple sources
5898 * or `customizer` functions.
5899 *
5900 * @private
5901 * @param {Object} object The destination object.
5902 * @param {Object} source The source object.
5903 * @returns {Object} Returns `object`.
5904 */
5905 function baseAssign(object, source) {
5906 return object && copyObject(source, keys(source), object);
5907 }
5908
5909 /**
5910 * The base implementation of `_.at` without support for individual paths.
5911 *
5912 * @private
5913 * @param {Object} object The object to iterate over.
5914 * @param {string[]} paths The property paths of elements to pick.
5915 * @returns {Array} Returns the new array of picked elements.
5916 */
5917 function baseAt(object, paths) {
5918 var index = -1,
5919 isNil = object == null,
5920 length = paths.length,
5921 result = Array(length);
5922
5923 while (++index < length) {
5924 result[index] = isNil ? undefined : get(object, paths[index]);
5925 }
5926 return result;
5927 }
5928
5929 /**
5930 * Casts `value` to an empty array if it's not an array like object.
5931 *
5932 * @private
5933 * @param {*} value The value to inspect.
5934 * @returns {Array} Returns the array-like object.
5935 */
5936 function baseCastArrayLikeObject(value) {
5937 return isArrayLikeObject(value) ? value : [];
5938 }
5939
5940 /**
5941 * Casts `value` to `identity` if it's not a function.
5942 *
5943 * @private
5944 * @param {*} value The value to inspect.
5945 * @returns {Array} Returns the array-like object.
5946 */
5947 function baseCastFunction(value) {
5948 return typeof value == 'function' ? value : identity;
5949 }
5950
5951 /**
5952 * Casts `value` to a path array if it's not one.
5953 *
5954 * @private
5955 * @param {*} value The value to inspect.
5956 * @returns {Array} Returns the cast property path array.
5957 */
5958 function baseCastPath(value) {
5959 return isArray(value) ? value : stringToPath(value);
5960 }
5961
5962 /**
5963 * The base implementation of `_.clamp` which doesn't coerce arguments to numbers.
5964 *
5965 * @private
5966 * @param {number} number The number to clamp.
5967 * @param {number} [lower] The lower bound.
5968 * @param {number} upper The upper bound.
5969 * @returns {number} Returns the clamped number.
5970 */
5971 function baseClamp(number, lower, upper) {
5972 if (number === number) {
5973 if (upper !== undefined) {
5974 number = number <= upper ? number : upper;
5975 }
5976 if (lower !== undefined) {
5977 number = number >= lower ? number : lower;
5978 }
5979 }
5980 return number;
5981 }
5982
5983 /**
5984 * The base implementation of `_.clone` and `_.cloneDeep` which tracks
5985 * traversed objects.
5986 *
5987 * @private
5988 * @param {*} value The value to clone.
5989 * @param {boolean} [isDeep] Specify a deep clone.
5990 * @param {boolean} [isFull] Specify a clone including symbols.
5991 * @param {Function} [customizer] The function to customize cloning.
5992 * @param {string} [key] The key of `value`.
5993 * @param {Object} [object] The parent object of `value`.
5994 * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
5995 * @returns {*} Returns the cloned value.
5996 */
5997 function baseClone(value, isDeep, isFull, customizer, key, object, stack) {
5998 var result;
5999 if (customizer) {
6000 result = object ? customizer(value, key, object, stack) : customizer(value);
6001 }
6002 if (result !== undefined) {
6003 return result;
6004 }
6005 if (!isObject(value)) {
6006 return value;
6007 }
6008 var isArr = isArray(value);
6009 if (isArr) {
6010 result = initCloneArray(value);
6011 if (!isDeep) {
6012 return copyArray(value, result);
6013 }
6014 } else {
6015 var tag = getTag(value),
6016 isFunc = tag == funcTag || tag == genTag;
6017
6018 if (isBuffer(value)) {
6019 return cloneBuffer(value, isDeep);
6020 }
6021 if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
6022 if (isHostObject(value)) {
6023 return object ? value : {};
6024 }
6025 result = initCloneObject(isFunc ? {} : value);
6026 if (!isDeep) {
6027 result = baseAssign(result, value);
6028 return isFull ? copySymbols(value, result) : result;
6029 }
6030 } else {
6031 if (!cloneableTags[tag]) {
6032 return object ? value : {};
6033 }
6034 result = initCloneByTag(value, tag, isDeep);
6035 }
6036 }
6037 // Check for circular references and return its corresponding clone.
6038 stack || (stack = new Stack);
6039 var stacked = stack.get(value);
6040 if (stacked) {
6041 return stacked;
6042 }
6043 stack.set(value, result);
6044
6045 // Recursively populate clone (susceptible to call stack limits).
6046 (isArr ? arrayEach : baseForOwn)(value, function(subValue, key) {
6047 assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack));
6048 });
6049 return (isFull && !isArr) ? copySymbols(value, result) : result;
6050 }
6051
6052 /**
6053 * The base implementation of `_.conforms` which doesn't clone `source`.
6054 *
6055 * @private
6056 * @param {Object} source The object of property predicates to conform to.
6057 * @returns {Function} Returns the new function.
6058 */
6059 function baseConforms(source) {
6060 var props = keys(source),
6061 length = props.length;
6062
6063 return function(object) {
6064 if (object == null) {
6065 return !length;
6066 }
6067 var index = length;
6068 while (index--) {
6069 var key = props[index],
6070 predicate = source[key],
6071 value = object[key];
6072
6073 if ((value === undefined && !(key in Object(object))) || !predicate(value)) {
6074 return false;
6075 }
6076 }
6077 return true;
6078 };
6079 }
6080
6081 /**
6082 * The base implementation of `_.create` without support for assigning
6083 * properties to the created object.
6084 *
6085 * @private
6086 * @param {Object} prototype The object to inherit from.
6087 * @returns {Object} Returns the new object.
6088 */
6089 function baseCreate(proto) {
6090 return isObject(proto) ? objectCreate(proto) : {};
6091 }
6092
6093 /**
6094 * The base implementation of `_.delay` and `_.defer` which accepts an array
6095 * of `func` arguments.
6096 *
6097 * @private
6098 * @param {Function} func The function to delay.
6099 * @param {number} wait The number of milliseconds to delay invocation.
6100 * @param {Object} args The arguments to provide to `func`.
6101 * @returns {number} Returns the timer id.
6102 */
6103 function baseDelay(func, wait, args) {
6104 if (typeof func != 'function') {
6105 throw new TypeError(FUNC_ERROR_TEXT);
6106 }
6107 return setTimeout(function() { func.apply(undefined, args); }, wait);
6108 }
6109
6110 /**
6111 * The base implementation of methods like `_.difference` without support for
6112 * excluding multiple arrays or iteratee shorthands.
6113 *
6114 * @private
6115 * @param {Array} array The array to inspect.
6116 * @param {Array} values The values to exclude.
6117 * @param {Function} [iteratee] The iteratee invoked per element.
6118 * @param {Function} [comparator] The comparator invoked per element.
6119 * @returns {Array} Returns the new array of filtered values.
6120 */
6121 function baseDifference(array, values, iteratee, comparator) {
6122 var index = -1,
6123 includes = arrayIncludes,
6124 isCommon = true,
6125 length = array.length,
6126 result = [],
6127 valuesLength = values.length;
6128
6129 if (!length) {
6130 return result;
6131 }
6132 if (iteratee) {
6133 values = arrayMap(values, baseUnary(iteratee));
6134 }
6135 if (comparator) {
6136 includes = arrayIncludesWith;
6137 isCommon = false;
6138 }
6139 else if (values.length >= LARGE_ARRAY_SIZE) {
6140 includes = cacheHas;
6141 isCommon = false;
6142 values = new SetCache(values);
6143 }
6144 outer:
6145 while (++index < length) {
6146 var value = array[index],
6147 computed = iteratee ? iteratee(value) : value;
6148
6149 if (isCommon && computed === computed) {
6150 var valuesIndex = valuesLength;
6151 while (valuesIndex--) {
6152 if (values[valuesIndex] === computed) {
6153 continue outer;
6154 }
6155 }
6156 result.push(value);
6157 }
6158 else if (!includes(values, computed, comparator)) {
6159 result.push(value);
6160 }
6161 }
6162 return result;
6163 }
6164
6165 /**
6166 * The base implementation of `_.forEach` without support for iteratee shorthands.
6167 *
6168 * @private
6169 * @param {Array|Object} collection The collection to iterate over.
6170 * @param {Function} iteratee The function invoked per iteration.
6171 * @returns {Array|Object} Returns `collection`.
6172 */
6173 var baseEach = createBaseEach(baseForOwn);
6174
6175 /**
6176 * The base implementation of `_.forEachRight` without support for iteratee shorthands.
6177 *
6178 * @private
6179 * @param {Array|Object} collection The collection to iterate over.
6180 * @param {Function} iteratee The function invoked per iteration.
6181 * @returns {Array|Object} Returns `collection`.
6182 */
6183 var baseEachRight = createBaseEach(baseForOwnRight, true);
6184
6185 /**
6186 * The base implementation of `_.every` without support for iteratee shorthands.
6187 *
6188 * @private
6189 * @param {Array|Object} collection The collection to iterate over.
6190 * @param {Function} predicate The function invoked per iteration.
6191 * @returns {boolean} Returns `true` if all elements pass the predicate check, else `false`
6192 */
6193 function baseEvery(collection, predicate) {
6194 var result = true;
6195 baseEach(collection, function(value, index, collection) {
6196 result = !!predicate(value, index, collection);
6197 return result;
6198 });
6199 return result;
6200 }
6201
6202 /**
6203 * The base implementation of `_.fill` without an iteratee call guard.
6204 *
6205 * @private
6206 * @param {Array} array The array to fill.
6207 * @param {*} value The value to fill `array` with.
6208 * @param {number} [start=0] The start position.
6209 * @param {number} [end=array.length] The end position.
6210 * @returns {Array} Returns `array`.
6211 */
6212 function baseFill(array, value, start, end) {
6213 var length = array.length;
6214
6215 start = toInteger(start);
6216 if (start < 0) {
6217 start = -start > length ? 0 : (length + start);
6218 }
6219 end = (end === undefined || end > length) ? length : toInteger(end);
6220 if (end < 0) {
6221 end += length;
6222 }
6223 end = start > end ? 0 : toLength(end);
6224 while (start < end) {
6225 array[start++] = value;
6226 }
6227 return array;
6228 }
6229
6230 /**
6231 * The base implementation of `_.filter` without support for iteratee shorthands.
6232 *
6233 * @private
6234 * @param {Array|Object} collection The collection to iterate over.
6235 * @param {Function} predicate The function invoked per iteration.
6236 * @returns {Array} Returns the new filtered array.
6237 */
6238 function baseFilter(collection, predicate) {
6239 var result = [];
6240 baseEach(collection, function(value, index, collection) {
6241 if (predicate(value, index, collection)) {
6242 result.push(value);
6243 }
6244 });
6245 return result;
6246 }
6247
6248 /**
6249 * The base implementation of `_.flatten` with support for restricting flattening.
6250 *
6251 * @private
6252 * @param {Array} array The array to flatten.
6253 * @param {number} depth The maximum recursion depth.
6254 * @param {boolean} [isStrict] Restrict flattening to arrays-like objects.
6255 * @param {Array} [result=[]] The initial result value.
6256 * @returns {Array} Returns the new flattened array.
6257 */
6258 function baseFlatten(array, depth, isStrict, result) {
6259 result || (result = []);
6260
6261 var index = -1,
6262 length = array.length;
6263
6264 while (++index < length) {
6265 var value = array[index];
6266 if (depth > 0 && isArrayLikeObject(value) &&
6267 (isStrict || isArray(value) || isArguments(value))) {
6268 if (depth > 1) {
6269 // Recursively flatten arrays (susceptible to call stack limits).
6270 baseFlatten(value, depth - 1, isStrict, result);
6271 } else {
6272 arrayPush(result, value);
6273 }
6274 } else if (!isStrict) {
6275 result[result.length] = value;
6276 }
6277 }
6278 return result;
6279 }
6280
6281 /**
6282 * The base implementation of `baseForIn` and `baseForOwn` which iterates
6283 * over `object` properties returned by `keysFunc` invoking `iteratee` for
6284 * each property. Iteratee functions may exit iteration early by explicitly
6285 * returning `false`.
6286 *
6287 * @private
6288 * @param {Object} object The object to iterate over.
6289 * @param {Function} iteratee The function invoked per iteration.
6290 * @param {Function} keysFunc The function to get the keys of `object`.
6291 * @returns {Object} Returns `object`.
6292 */
6293 var baseFor = createBaseFor();
6294
6295 /**
6296 * This function is like `baseFor` except that it iterates over properties
6297 * in the opposite order.
6298 *
6299 * @private
6300 * @param {Object} object The object to iterate over.
6301 * @param {Function} iteratee The function invoked per iteration.
6302 * @param {Function} keysFunc The function to get the keys of `object`.
6303 * @returns {Object} Returns `object`.
6304 */
6305 var baseForRight = createBaseFor(true);
6306
6307 /**
6308 * The base implementation of `_.forIn` without support for iteratee shorthands.
6309 *
6310 * @private
6311 * @param {Object} object The object to iterate over.
6312 * @param {Function} iteratee The function invoked per iteration.
6313 * @returns {Object} Returns `object`.
6314 */
6315 function baseForIn(object, iteratee) {
6316 return object == null ? object : baseFor(object, iteratee, keysIn);
6317 }
6318
6319 /**
6320 * The base implementation of `_.forOwn` without support for iteratee shorthands.
6321 *
6322 * @private
6323 * @param {Object} object The object to iterate over.
6324 * @param {Function} iteratee The function invoked per iteration.
6325 * @returns {Object} Returns `object`.
6326 */
6327 function baseForOwn(object, iteratee) {
6328 return object && baseFor(object, iteratee, keys);
6329 }
6330
6331 /**
6332 * The base implementation of `_.forOwnRight` without support for iteratee shorthands.
6333 *
6334 * @private
6335 * @param {Object} object The object to iterate over.
6336 * @param {Function} iteratee The function invoked per iteration.
6337 * @returns {Object} Returns `object`.
6338 */
6339 function baseForOwnRight(object, iteratee) {
6340 return object && baseForRight(object, iteratee, keys);
6341 }
6342
6343 /**
6344 * The base implementation of `_.functions` which creates an array of
6345 * `object` function property names filtered from `props`.
6346 *
6347 * @private
6348 * @param {Object} object The object to inspect.
6349 * @param {Array} props The property names to filter.
6350 * @returns {Array} Returns the new array of filtered property names.
6351 */
6352 function baseFunctions(object, props) {
6353 return arrayFilter(props, function(key) {
6354 return isFunction(object[key]);
6355 });
6356 }
6357
6358 /**
6359 * The base implementation of `_.get` without support for default values.
6360 *
6361 * @private
6362 * @param {Object} object The object to query.
6363 * @param {Array|string} path The path of the property to get.
6364 * @returns {*} Returns the resolved value.
6365 */
6366 function baseGet(object, path) {
6367 path = isKey(path, object) ? [path + ''] : baseCastPath(path);
6368
6369 var index = 0,
6370 length = path.length;
6371
6372 while (object != null && index < length) {
6373 object = object[path[index++]];
6374 }
6375 return (index && index == length) ? object : undefined;
6376 }
6377
6378 /**
6379 * The base implementation of `_.has` without support for deep paths.
6380 *
6381 * @private
6382 * @param {Object} object The object to query.
6383 * @param {Array|string} key The key to check.
6384 * @returns {boolean} Returns `true` if `key` exists, else `false`.
6385 */
6386 function baseHas(object, key) {
6387 // Avoid a bug in IE 10-11 where objects with a [[Prototype]] of `null`,
6388 // that are composed entirely of index properties, return `false` for
6389 // `hasOwnProperty` checks of them.
6390 return hasOwnProperty.call(object, key) ||
6391 (typeof object == 'object' && key in object && getPrototypeOf(object) === null);
6392 }
6393
6394 /**
6395 * The base implementation of `_.hasIn` without support for deep paths.
6396 *
6397 * @private
6398 * @param {Object} object The object to query.
6399 * @param {Array|string} key The key to check.
6400 * @returns {boolean} Returns `true` if `key` exists, else `false`.
6401 */
6402 function baseHasIn(object, key) {
6403 return key in Object(object);
6404 }
6405
6406 /**
6407 * The base implementation of `_.inRange` which doesn't coerce arguments to numbers.
6408 *
6409 * @private
6410 * @param {number} number The number to check.
6411 * @param {number} start The start of the range.
6412 * @param {number} end The end of the range.
6413 * @returns {boolean} Returns `true` if `number` is in the range, else `false`.
6414 */
6415 function baseInRange(number, start, end) {
6416 return number >= nativeMin(start, end) && number < nativeMax(start, end);
6417 }
6418
6419 /**
6420 * The base implementation of methods like `_.intersection`, without support
6421 * for iteratee shorthands, that accepts an array of arrays to inspect.
6422 *
6423 * @private
6424 * @param {Array} arrays The arrays to inspect.
6425 * @param {Function} [iteratee] The iteratee invoked per element.
6426 * @param {Function} [comparator] The comparator invoked per element.
6427 * @returns {Array} Returns the new array of shared values.
6428 */
6429 function baseIntersection(arrays, iteratee, comparator) {
6430 var includes = comparator ? arrayIncludesWith : arrayIncludes,
6431 length = arrays[0].length,
6432 othLength = arrays.length,
6433 othIndex = othLength,
6434 caches = Array(othLength),
6435 maxLength = Infinity,
6436 result = [];
6437
6438 while (othIndex--) {
6439 var array = arrays[othIndex];
6440 if (othIndex && iteratee) {
6441 array = arrayMap(array, baseUnary(iteratee));
6442 }
6443 maxLength = nativeMin(array.length, maxLength);
6444 caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))
6445 ? new SetCache(othIndex && array)
6446 : undefined;
6447 }
6448 array = arrays[0];
6449
6450 var index = -1,
6451 seen = caches[0];
6452
6453 outer:
6454 while (++index < length && result.length < maxLength) {
6455 var value = array[index],
6456 computed = iteratee ? iteratee(value) : value;
6457
6458 if (!(seen
6459 ? cacheHas(seen, computed)
6460 : includes(result, computed, comparator)
6461 )) {
6462 othIndex = othLength;
6463 while (--othIndex) {
6464 var cache = caches[othIndex];
6465 if (!(cache
6466 ? cacheHas(cache, computed)
6467 : includes(arrays[othIndex], computed, comparator))
6468 ) {
6469 continue outer;
6470 }
6471 }
6472 if (seen) {
6473 seen.push(computed);
6474 }
6475 result.push(value);
6476 }
6477 }
6478 return result;
6479 }
6480
6481 /**
6482 * The base implementation of `_.invert` and `_.invertBy` which inverts
6483 * `object` with values transformed by `iteratee` and set by `setter`.
6484 *
6485 * @private
6486 * @param {Object} object The object to iterate over.
6487 * @param {Function} setter The function to set `accumulator` values.
6488 * @param {Function} iteratee The iteratee to transform values.
6489 * @param {Object} accumulator The initial inverted object.
6490 * @returns {Function} Returns `accumulator`.
6491 */
6492 function baseInverter(object, setter, iteratee, accumulator) {
6493 baseForOwn(object, function(value, key, object) {
6494 setter(accumulator, iteratee(value), key, object);
6495 });
6496 return accumulator;
6497 }
6498
6499 /**
6500 * The base implementation of `_.invoke` without support for individual
6501 * method arguments.
6502 *
6503 * @private
6504 * @param {Object} object The object to query.
6505 * @param {Array|string} path The path of the method to invoke.
6506 * @param {Array} args The arguments to invoke the method with.
6507 * @returns {*} Returns the result of the invoked method.
6508 */
6509 function baseInvoke(object, path, args) {
6510 if (!isKey(path, object)) {
6511 path = baseCastPath(path);
6512 object = parent(object, path);
6513 path = last(path);
6514 }
6515 var func = object == null ? object : object[path];
6516 return func == null ? undefined : apply(func, object, args);
6517 }
6518
6519 /**
6520 * The base implementation of `_.isEqual` which supports partial comparisons
6521 * and tracks traversed objects.
6522 *
6523 * @private
6524 * @param {*} value The value to compare.
6525 * @param {*} other The other value to compare.
6526 * @param {Function} [customizer] The function to customize comparisons.
6527 * @param {boolean} [bitmask] The bitmask of comparison flags.
6528 * The bitmask may be composed of the following flags:
6529 * 1 - Unordered comparison
6530 * 2 - Partial comparison
6531 * @param {Object} [stack] Tracks traversed `value` and `other` objects.
6532 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
6533 */
6534 function baseIsEqual(value, other, customizer, bitmask, stack) {
6535 if (value === other) {
6536 return true;
6537 }
6538 if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
6539 return value !== value && other !== other;
6540 }
6541 return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack);
6542 }
6543
6544 /**
6545 * A specialized version of `baseIsEqual` for arrays and objects which performs
6546 * deep comparisons and tracks traversed objects enabling objects with circular
6547 * references to be compared.
6548 *
6549 * @private
6550 * @param {Object} object The object to compare.
6551 * @param {Object} other The other object to compare.
6552 * @param {Function} equalFunc The function to determine equivalents of values.
6553 * @param {Function} [customizer] The function to customize comparisons.
6554 * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual` for more details.
6555 * @param {Object} [stack] Tracks traversed `object` and `other` objects.
6556 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
6557 */
6558 function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) {
6559 var objIsArr = isArray(object),
6560 othIsArr = isArray(other),
6561 objTag = arrayTag,
6562 othTag = arrayTag;
6563
6564 if (!objIsArr) {
6565 objTag = getTag(object);
6566 objTag = objTag == argsTag ? objectTag : objTag;
6567 }
6568 if (!othIsArr) {
6569 othTag = getTag(other);
6570 othTag = othTag == argsTag ? objectTag : othTag;
6571 }
6572 var objIsObj = objTag == objectTag && !isHostObject(object),
6573 othIsObj = othTag == objectTag && !isHostObject(other),
6574 isSameTag = objTag == othTag;
6575
6576 if (isSameTag && !objIsObj) {
6577 stack || (stack = new Stack);
6578 return (objIsArr || isTypedArray(object))
6579 ? equalArrays(object, other, equalFunc, customizer, bitmask, stack)
6580 : equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack);
6581 }
6582 if (!(bitmask & PARTIAL_COMPARE_FLAG)) {
6583 var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
6584 othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
6585
6586 if (objIsWrapped || othIsWrapped) {
6587 stack || (stack = new Stack);
6588 return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, customizer, bitmask, stack);
6589 }
6590 }
6591 if (!isSameTag) {
6592 return false;
6593 }
6594 stack || (stack = new Stack);
6595 return equalObjects(object, other, equalFunc, customizer, bitmask, stack);
6596 }
6597
6598 /**
6599 * The base implementation of `_.isMatch` without support for iteratee shorthands.
6600 *
6601 * @private
6602 * @param {Object} object The object to inspect.
6603 * @param {Object} source The object of property values to match.
6604 * @param {Array} matchData The property names, values, and compare flags to match.
6605 * @param {Function} [customizer] The function to customize comparisons.
6606 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
6607 */
6608 function baseIsMatch(object, source, matchData, customizer) {
6609 var index = matchData.length,
6610 length = index,
6611 noCustomizer = !customizer;
6612
6613 if (object == null) {
6614 return !length;
6615 }
6616 object = Object(object);
6617 while (index--) {
6618 var data = matchData[index];
6619 if ((noCustomizer && data[2])
6620 ? data[1] !== object[data[0]]
6621 : !(data[0] in object)
6622 ) {
6623 return false;
6624 }
6625 }
6626 while (++index < length) {
6627 data = matchData[index];
6628 var key = data[0],
6629 objValue = object[key],
6630 srcValue = data[1];
6631
6632 if (noCustomizer && data[2]) {
6633 if (objValue === undefined && !(key in object)) {
6634 return false;
6635 }
6636 } else {
6637 var stack = new Stack,
6638 result = customizer ? customizer(objValue, srcValue, key, object, source, stack) : undefined;
6639
6640 if (!(result === undefined
6641 ? baseIsEqual(srcValue, objValue, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack)
6642 : result
6643 )) {
6644 return false;
6645 }
6646 }
6647 }
6648 return true;
6649 }
6650
6651 /**
6652 * The base implementation of `_.iteratee`.
6653 *
6654 * @private
6655 * @param {*} [value=_.identity] The value to convert to an iteratee.
6656 * @returns {Function} Returns the iteratee.
6657 */
6658 function baseIteratee(value) {
6659 var type = typeof value;
6660 if (type == 'function') {
6661 return value;
6662 }
6663 if (value == null) {
6664 return identity;
6665 }
6666 if (type == 'object') {
6667 return isArray(value)
6668 ? baseMatchesProperty(value[0], value[1])
6669 : baseMatches(value);
6670 }
6671 return property(value);
6672 }
6673
6674 /**
6675 * The base implementation of `_.keys` which doesn't skip the constructor
6676 * property of prototypes or treat sparse arrays as dense.
6677 *
6678 * @private
6679 * @param {Object} object The object to query.
6680 * @returns {Array} Returns the array of property names.
6681 */
6682 function baseKeys(object) {
6683 return nativeKeys(Object(object));
6684 }
6685
6686 /**
6687 * The base implementation of `_.keysIn` which doesn't skip the constructor
6688 * property of prototypes or treat sparse arrays as dense.
6689 *
6690 * @private
6691 * @param {Object} object The object to query.
6692 * @returns {Array} Returns the array of property names.
6693 */
6694 function baseKeysIn(object) {
6695 object = object == null ? object : Object(object);
6696
6697 var result = [];
6698 for (var key in object) {
6699 result.push(key);
6700 }
6701 return result;
6702 }
6703
6704 // Fallback for IE < 9 with es6-shim.
6705 if (enumerate && !propertyIsEnumerable.call({ 'valueOf': 1 }, 'valueOf')) {
6706 baseKeysIn = function(object) {
6707 return iteratorToArray(enumerate(object));
6708 };
6709 }
6710
6711 /**
6712 * The base implementation of `_.map` without support for iteratee shorthands.
6713 *
6714 * @private
6715 * @param {Array|Object} collection The collection to iterate over.
6716 * @param {Function} iteratee The function invoked per iteration.
6717 * @returns {Array} Returns the new mapped array.
6718 */
6719 function baseMap(collection, iteratee) {
6720 var index = -1,
6721 result = isArrayLike(collection) ? Array(collection.length) : [];
6722
6723 baseEach(collection, function(value, key, collection) {
6724 result[++index] = iteratee(value, key, collection);
6725 });
6726 return result;
6727 }
6728
6729 /**
6730 * The base implementation of `_.matches` which doesn't clone `source`.
6731 *
6732 * @private
6733 * @param {Object} source The object of property values to match.
6734 * @returns {Function} Returns the new function.
6735 */
6736 function baseMatches(source) {
6737 var matchData = getMatchData(source);
6738 if (matchData.length == 1 && matchData[0][2]) {
6739 var key = matchData[0][0],
6740 value = matchData[0][1];
6741
6742 return function(object) {
6743 if (object == null) {
6744 return false;
6745 }
6746 return object[key] === value &&
6747 (value !== undefined || (key in Object(object)));
6748 };
6749 }
6750 return function(object) {
6751 return object === source || baseIsMatch(object, source, matchData);
6752 };
6753 }
6754
6755 /**
6756 * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
6757 *
6758 * @private
6759 * @param {string} path The path of the property to get.
6760 * @param {*} srcValue The value to match.
6761 * @returns {Function} Returns the new function.
6762 */
6763 function baseMatchesProperty(path, srcValue) {
6764 return function(object) {
6765 var objValue = get(object, path);
6766 return (objValue === undefined && objValue === srcValue)
6767 ? hasIn(object, path)
6768 : baseIsEqual(srcValue, objValue, undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG);
6769 };
6770 }
6771
6772 /**
6773 * The base implementation of `_.merge` without support for multiple sources.
6774 *
6775 * @private
6776 * @param {Object} object The destination object.
6777 * @param {Object} source The source object.
6778 * @param {number} srcIndex The index of `source`.
6779 * @param {Function} [customizer] The function to customize merged values.
6780 * @param {Object} [stack] Tracks traversed source values and their merged counterparts.
6781 */
6782 function baseMerge(object, source, srcIndex, customizer, stack) {
6783 if (object === source) {
6784 return;
6785 }
6786 var props = (isArray(source) || isTypedArray(source))
6787 ? undefined
6788 : keysIn(source);
6789
6790 arrayEach(props || source, function(srcValue, key) {
6791 if (props) {
6792 key = srcValue;
6793 srcValue = source[key];
6794 }
6795 if (isObject(srcValue)) {
6796 stack || (stack = new Stack);
6797 baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
6798 }
6799 else {
6800 var newValue = customizer
6801 ? customizer(object[key], srcValue, (key + ''), object, source, stack)
6802 : undefined;
6803
6804 if (newValue === undefined) {
6805 newValue = srcValue;
6806 }
6807 assignMergeValue(object, key, newValue);
6808 }
6809 });
6810 }
6811
6812 /**
6813 * A specialized version of `baseMerge` for arrays and objects which performs
6814 * deep merges and tracks traversed objects enabling objects with circular
6815 * references to be merged.
6816 *
6817 * @private
6818 * @param {Object} object The destination object.
6819 * @param {Object} source The source object.
6820 * @param {string} key The key of the value to merge.
6821 * @param {number} srcIndex The index of `source`.
6822 * @param {Function} mergeFunc The function to merge values.
6823 * @param {Function} [customizer] The function to customize assigned values.
6824 * @param {Object} [stack] Tracks traversed source values and their merged counterparts.
6825 */
6826 function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
6827 var objValue = object[key],
6828 srcValue = source[key],
6829 stacked = stack.get(srcValue);
6830
6831 if (stacked) {
6832 assignMergeValue(object, key, stacked);
6833 return;
6834 }
6835 var newValue = customizer
6836 ? customizer(objValue, srcValue, (key + ''), object, source, stack)
6837 : undefined;
6838
6839 var isCommon = newValue === undefined;
6840
6841 if (isCommon) {
6842 newValue = srcValue;
6843 if (isArray(srcValue) || isTypedArray(srcValue)) {
6844 if (isArray(objValue)) {
6845 newValue = objValue;
6846 }
6847 else if (isArrayLikeObject(objValue)) {
6848 newValue = copyArray(objValue);
6849 }
6850 else {
6851 isCommon = false;
6852 newValue = baseClone(srcValue, !customizer);
6853 }
6854 }
6855 else if (isPlainObject(srcValue) || isArguments(srcValue)) {
6856 if (isArguments(objValue)) {
6857 newValue = toPlainObject(objValue);
6858 }
6859 else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) {
6860 isCommon = false;
6861 newValue = baseClone(srcValue, !customizer);
6862 }
6863 else {
6864 newValue = objValue;
6865 }
6866 }
6867 else {
6868 isCommon = false;
6869 }
6870 }
6871 stack.set(srcValue, newValue);
6872
6873 if (isCommon) {
6874 // Recursively merge objects and arrays (susceptible to call stack limits).
6875 mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
6876 }
6877 stack['delete'](srcValue);
6878 assignMergeValue(object, key, newValue);
6879 }
6880
6881 /**
6882 * The base implementation of `_.orderBy` without param guards.
6883 *
6884 * @private
6885 * @param {Array|Object} collection The collection to iterate over.
6886 * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
6887 * @param {string[]} orders The sort orders of `iteratees`.
6888 * @returns {Array} Returns the new sorted array.
6889 */
6890 function baseOrderBy(collection, iteratees, orders) {
6891 var index = -1;
6892 iteratees = arrayMap(iteratees.length ? iteratees : Array(1), getIteratee());
6893
6894 var result = baseMap(collection, function(value, key, collection) {
6895 var criteria = arrayMap(iteratees, function(iteratee) {
6896 return iteratee(value);
6897 });
6898 return { 'criteria': criteria, 'index': ++index, 'value': value };
6899 });
6900
6901 return baseSortBy(result, function(object, other) {
6902 return compareMultiple(object, other, orders);
6903 });
6904 }
6905
6906 /**
6907 * The base implementation of `_.pick` without support for individual
6908 * property names.
6909 *
6910 * @private
6911 * @param {Object} object The source object.
6912 * @param {string[]} props The property names to pick.
6913 * @returns {Object} Returns the new object.
6914 */
6915 function basePick(object, props) {
6916 object = Object(object);
6917 return arrayReduce(props, function(result, key) {
6918 if (key in object) {
6919 result[key] = object[key];
6920 }
6921 return result;
6922 }, {});
6923 }
6924
6925 /**
6926 * The base implementation of `_.pickBy` without support for iteratee shorthands.
6927 *
6928 * @private
6929 * @param {Object} object The source object.
6930 * @param {Function} predicate The function invoked per property.
6931 * @returns {Object} Returns the new object.
6932 */
6933 function basePickBy(object, predicate) {
6934 var result = {};
6935 baseForIn(object, function(value, key) {
6936 if (predicate(value, key)) {
6937 result[key] = value;
6938 }
6939 });
6940 return result;
6941 }
6942
6943 /**
6944 * The base implementation of `_.property` without support for deep paths.
6945 *
6946 * @private
6947 * @param {string} key The key of the property to get.
6948 * @returns {Function} Returns the new function.
6949 */
6950 function baseProperty(key) {
6951 return function(object) {
6952 return object == null ? undefined : object[key];
6953 };
6954 }
6955
6956 /**
6957 * A specialized version of `baseProperty` which supports deep paths.
6958 *
6959 * @private
6960 * @param {Array|string} path The path of the property to get.
6961 * @returns {Function} Returns the new function.
6962 */
6963 function basePropertyDeep(path) {
6964 return function(object) {
6965 return baseGet(object, path);
6966 };
6967 }
6968
6969 /**
6970 * The base implementation of `_.pullAllBy` without support for iteratee
6971 * shorthands.
6972 *
6973 * @private
6974 * @param {Array} array The array to modify.
6975 * @param {Array} values The values to remove.
6976 * @param {Function} [iteratee] The iteratee invoked per element.
6977 * @param {Function} [comparator] The comparator invoked per element.
6978 * @returns {Array} Returns `array`.
6979 */
6980 function basePullAll(array, values, iteratee, comparator) {
6981 var indexOf = comparator ? baseIndexOfWith : baseIndexOf,
6982 index = -1,
6983 length = values.length,
6984 seen = array;
6985
6986 if (iteratee) {
6987 seen = arrayMap(array, baseUnary(iteratee));
6988 }
6989 while (++index < length) {
6990 var fromIndex = 0,
6991 value = values[index],
6992 computed = iteratee ? iteratee(value) : value;
6993
6994 while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) {
6995 if (seen !== array) {
6996 splice.call(seen, fromIndex, 1);
6997 }
6998 splice.call(array, fromIndex, 1);
6999 }
7000 }
7001 return array;
7002 }
7003
7004 /**
7005 * The base implementation of `_.pullAt` without support for individual
7006 * indexes or capturing the removed elements.
7007 *
7008 * @private
7009 * @param {Array} array The array to modify.
7010 * @param {number[]} indexes The indexes of elements to remove.
7011 * @returns {Array} Returns `array`.
7012 */
7013 function basePullAt(array, indexes) {
7014 var length = array ? indexes.length : 0,
7015 lastIndex = length - 1;
7016
7017 while (length--) {
7018 var index = indexes[length];
7019 if (lastIndex == length || index != previous) {
7020 var previous = index;
7021 if (isIndex(index)) {
7022 splice.call(array, index, 1);
7023 }
7024 else if (!isKey(index, array)) {
7025 var path = baseCastPath(index),
7026 object = parent(array, path);
7027
7028 if (object != null) {
7029 delete object[last(path)];
7030 }
7031 }
7032 else {
7033 delete array[index];
7034 }
7035 }
7036 }
7037 return array;
7038 }
7039
7040 /**
7041 * The base implementation of `_.random` without support for returning
7042 * floating-point numbers.
7043 *
7044 * @private
7045 * @param {number} lower The lower bound.
7046 * @param {number} upper The upper bound.
7047 * @returns {number} Returns the random number.
7048 */
7049 function baseRandom(lower, upper) {
7050 return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
7051 }
7052
7053 /**
7054 * The base implementation of `_.range` and `_.rangeRight` which doesn't
7055 * coerce arguments to numbers.
7056 *
7057 * @private
7058 * @param {number} start The start of the range.
7059 * @param {number} end The end of the range.
7060 * @param {number} step The value to increment or decrement by.
7061 * @param {boolean} [fromRight] Specify iterating from right to left.
7062 * @returns {Array} Returns the new array of numbers.
7063 */
7064 function baseRange(start, end, step, fromRight) {
7065 var index = -1,
7066 length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
7067 result = Array(length);
7068
7069 while (length--) {
7070 result[fromRight ? length : ++index] = start;
7071 start += step;
7072 }
7073 return result;
7074 }
7075
7076 /**
7077 * The base implementation of `_.set`.
7078 *
7079 * @private
7080 * @param {Object} object The object to query.
7081 * @param {Array|string} path The path of the property to set.
7082 * @param {*} value The value to set.
7083 * @param {Function} [customizer] The function to customize path creation.
7084 * @returns {Object} Returns `object`.
7085 */
7086 function baseSet(object, path, value, customizer) {
7087 path = isKey(path, object) ? [path + ''] : baseCastPath(path);
7088
7089 var index = -1,
7090 length = path.length,
7091 lastIndex = length - 1,
7092 nested = object;
7093
7094 while (nested != null && ++index < length) {
7095 var key = path[index];
7096 if (isObject(nested)) {
7097 var newValue = value;
7098 if (index != lastIndex) {
7099 var objValue = nested[key];
7100 newValue = customizer ? customizer(objValue, key, nested) : undefined;
7101 if (newValue === undefined) {
7102 newValue = objValue == null
7103 ? (isIndex(path[index + 1]) ? [] : {})
7104 : objValue;
7105 }
7106 }
7107 assignValue(nested, key, newValue);
7108 }
7109 nested = nested[key];
7110 }
7111 return object;
7112 }
7113
7114 /**
7115 * The base implementation of `setData` without support for hot loop detection.
7116 *
7117 * @private
7118 * @param {Function} func The function to associate metadata with.
7119 * @param {*} data The metadata.
7120 * @returns {Function} Returns `func`.
7121 */
7122 var baseSetData = !metaMap ? identity : function(func, data) {
7123 metaMap.set(func, data);
7124 return func;
7125 };
7126
7127 /**
7128 * The base implementation of `_.slice` without an iteratee call guard.
7129 *
7130 * @private
7131 * @param {Array} array The array to slice.
7132 * @param {number} [start=0] The start position.
7133 * @param {number} [end=array.length] The end position.
7134 * @returns {Array} Returns the slice of `array`.
7135 */
7136 function baseSlice(array, start, end) {
7137 var index = -1,
7138 length = array.length;
7139
7140 if (start < 0) {
7141 start = -start > length ? 0 : (length + start);
7142 }
7143 end = end > length ? length : end;
7144 if (end < 0) {
7145 end += length;
7146 }
7147 length = start > end ? 0 : ((end - start) >>> 0);
7148 start >>>= 0;
7149
7150 var result = Array(length);
7151 while (++index < length) {
7152 result[index] = array[index + start];
7153 }
7154 return result;
7155 }
7156
7157 /**
7158 * The base implementation of `_.some` without support for iteratee shorthands.
7159 *
7160 * @private
7161 * @param {Array|Object} collection The collection to iterate over.
7162 * @param {Function} predicate The function invoked per iteration.
7163 * @returns {boolean} Returns `true` if any element passes the predicate check, else `false`.
7164 */
7165 function baseSome(collection, predicate) {
7166 var result;
7167
7168 baseEach(collection, function(value, index, collection) {
7169 result = predicate(value, index, collection);
7170 return !result;
7171 });
7172 return !!result;
7173 }
7174
7175 /**
7176 * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which
7177 * performs a binary search of `array` to determine the index at which `value`
7178 * should be inserted into `array` in order to maintain its sort order.
7179 *
7180 * @private
7181 * @param {Array} array The sorted array to inspect.
7182 * @param {*} value The value to evaluate.
7183 * @param {boolean} [retHighest] Specify returning the highest qualified index.
7184 * @returns {number} Returns the index at which `value` should be inserted
7185 * into `array`.
7186 */
7187 function baseSortedIndex(array, value, retHighest) {
7188 var low = 0,
7189 high = array ? array.length : low;
7190
7191 if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
7192 while (low < high) {
7193 var mid = (low + high) >>> 1,
7194 computed = array[mid];
7195
7196 if ((retHighest ? (computed <= value) : (computed < value)) && computed !== null) {
7197 low = mid + 1;
7198 } else {
7199 high = mid;
7200 }
7201 }
7202 return high;
7203 }
7204 return baseSortedIndexBy(array, value, identity, retHighest);
7205 }
7206
7207 /**
7208 * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy`
7209 * which invokes `iteratee` for `value` and each element of `array` to compute
7210 * their sort ranking. The iteratee is invoked with one argument; (value).
7211 *
7212 * @private
7213 * @param {Array} array The sorted array to inspect.
7214 * @param {*} value The value to evaluate.
7215 * @param {Function} iteratee The iteratee invoked per element.
7216 * @param {boolean} [retHighest] Specify returning the highest qualified index.
7217 * @returns {number} Returns the index at which `value` should be inserted into `array`.
7218 */
7219 function baseSortedIndexBy(array, value, iteratee, retHighest) {
7220 value = iteratee(value);
7221
7222 var low = 0,
7223 high = array ? array.length : 0,
7224 valIsNaN = value !== value,
7225 valIsNull = value === null,
7226 valIsUndef = value === undefined;
7227
7228 while (low < high) {
7229 var mid = nativeFloor((low + high) / 2),
7230 computed = iteratee(array[mid]),
7231 isDef = computed !== undefined,
7232 isReflexive = computed === computed;
7233
7234 if (valIsNaN) {
7235 var setLow = isReflexive || retHighest;
7236 } else if (valIsNull) {
7237 setLow = isReflexive && isDef && (retHighest || computed != null);
7238 } else if (valIsUndef) {
7239 setLow = isReflexive && (retHighest || isDef);
7240 } else if (computed == null) {
7241 setLow = false;
7242 } else {
7243 setLow = retHighest ? (computed <= value) : (computed < value);
7244 }
7245 if (setLow) {
7246 low = mid + 1;
7247 } else {
7248 high = mid;
7249 }
7250 }
7251 return nativeMin(high, MAX_ARRAY_INDEX);
7252 }
7253
7254 /**
7255 * The base implementation of `_.sortedUniq`.
7256 *
7257 * @private
7258 * @param {Array} array The array to inspect.
7259 * @returns {Array} Returns the new duplicate free array.
7260 */
7261 function baseSortedUniq(array) {
7262 return baseSortedUniqBy(array);
7263 }
7264
7265 /**
7266 * The base implementation of `_.sortedUniqBy` without support for iteratee
7267 * shorthands.
7268 *
7269 * @private
7270 * @param {Array} array The array to inspect.
7271 * @param {Function} [iteratee] The iteratee invoked per element.
7272 * @returns {Array} Returns the new duplicate free array.
7273 */
7274 function baseSortedUniqBy(array, iteratee) {
7275 var index = 0,
7276 length = array.length,
7277 value = array[0],
7278 computed = iteratee ? iteratee(value) : value,
7279 seen = computed,
7280 resIndex = 1,
7281 result = [value];
7282
7283 while (++index < length) {
7284 value = array[index],
7285 computed = iteratee ? iteratee(value) : value;
7286
7287 if (!eq(computed, seen)) {
7288 seen = computed;
7289 result[resIndex++] = value;
7290 }
7291 }
7292 return result;
7293 }
7294
7295 /**
7296 * The base implementation of `_.uniqBy` without support for iteratee shorthands.
7297 *
7298 * @private
7299 * @param {Array} array The array to inspect.
7300 * @param {Function} [iteratee] The iteratee invoked per element.
7301 * @param {Function} [comparator] The comparator invoked per element.
7302 * @returns {Array} Returns the new duplicate free array.
7303 */
7304 function baseUniq(array, iteratee, comparator) {
7305 var index = -1,
7306 includes = arrayIncludes,
7307 length = array.length,
7308 isCommon = true,
7309 result = [],
7310 seen = result;
7311
7312 if (comparator) {
7313 isCommon = false;
7314 includes = arrayIncludesWith;
7315 }
7316 else if (length >= LARGE_ARRAY_SIZE) {
7317 var set = iteratee ? null : createSet(array);
7318 if (set) {
7319 return setToArray(set);
7320 }
7321 isCommon = false;
7322 includes = cacheHas;
7323 seen = new SetCache;
7324 }
7325 else {
7326 seen = iteratee ? [] : result;
7327 }
7328 outer:
7329 while (++index < length) {
7330 var value = array[index],
7331 computed = iteratee ? iteratee(value) : value;
7332
7333 if (isCommon && computed === computed) {
7334 var seenIndex = seen.length;
7335 while (seenIndex--) {
7336 if (seen[seenIndex] === computed) {
7337 continue outer;
7338 }
7339 }
7340 if (iteratee) {
7341 seen.push(computed);
7342 }
7343 result.push(value);
7344 }
7345 else if (!includes(seen, computed, comparator)) {
7346 if (seen !== result) {
7347 seen.push(computed);
7348 }
7349 result.push(value);
7350 }
7351 }
7352 return result;
7353 }
7354
7355 /**
7356 * The base implementation of `_.unset`.
7357 *
7358 * @private
7359 * @param {Object} object The object to modify.
7360 * @param {Array|string} path The path of the property to unset.
7361 * @returns {boolean} Returns `true` if the property is deleted, else `false`.
7362 */
7363 function baseUnset(object, path) {
7364 path = isKey(path, object) ? [path + ''] : baseCastPath(path);
7365 object = parent(object, path);
7366 var key = last(path);
7367 return (object != null && has(object, key)) ? delete object[key] : true;
7368 }
7369
7370 /**
7371 * The base implementation of `_.update`.
7372 *
7373 * @private
7374 * @param {Object} object The object to query.
7375 * @param {Array|string} path The path of the property to update.
7376 * @param {Function} updater The function to produce the updated value.
7377 * @param {Function} [customizer] The function to customize path creation.
7378 * @returns {Object} Returns `object`.
7379 */
7380 function baseUpdate(object, path, updater, customizer) {
7381 return baseSet(object, path, updater(baseGet(object, path)), customizer);
7382 }
7383
7384 /**
7385 * The base implementation of methods like `_.dropWhile` and `_.takeWhile`
7386 * without support for iteratee shorthands.
7387 *
7388 * @private
7389 * @param {Array} array The array to query.
7390 * @param {Function} predicate The function invoked per iteration.
7391 * @param {boolean} [isDrop] Specify dropping elements instead of taking them.
7392 * @param {boolean} [fromRight] Specify iterating from right to left.
7393 * @returns {Array} Returns the slice of `array`.
7394 */
7395 function baseWhile(array, predicate, isDrop, fromRight) {
7396 var length = array.length,
7397 index = fromRight ? length : -1;
7398
7399 while ((fromRight ? index-- : ++index < length) &&
7400 predicate(array[index], index, array)) {}
7401
7402 return isDrop
7403 ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))
7404 : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));
7405 }
7406
7407 /**
7408 * The base implementation of `wrapperValue` which returns the result of
7409 * performing a sequence of actions on the unwrapped `value`, where each
7410 * successive action is supplied the return value of the previous.
7411 *
7412 * @private
7413 * @param {*} value The unwrapped value.
7414 * @param {Array} actions Actions to perform to resolve the unwrapped value.
7415 * @returns {*} Returns the resolved value.
7416 */
7417 function baseWrapperValue(value, actions) {
7418 var result = value;
7419 if (result instanceof LazyWrapper) {
7420 result = result.value();
7421 }
7422 return arrayReduce(actions, function(result, action) {
7423 return action.func.apply(action.thisArg, arrayPush([result], action.args));
7424 }, result);
7425 }
7426
7427 /**
7428 * The base implementation of methods like `_.xor`, without support for
7429 * iteratee shorthands, that accepts an array of arrays to inspect.
7430 *
7431 * @private
7432 * @param {Array} arrays The arrays to inspect.
7433 * @param {Function} [iteratee] The iteratee invoked per element.
7434 * @param {Function} [comparator] The comparator invoked per element.
7435 * @returns {Array} Returns the new array of values.
7436 */
7437 function baseXor(arrays, iteratee, comparator) {
7438 var index = -1,
7439 length = arrays.length;
7440
7441 while (++index < length) {
7442 var result = result
7443 ? arrayPush(
7444 baseDifference(result, arrays[index], iteratee, comparator),
7445 baseDifference(arrays[index], result, iteratee, comparator)
7446 )
7447 : arrays[index];
7448 }
7449 return (result && result.length) ? baseUniq(result, iteratee, comparator) : [];
7450 }
7451
7452 /**
7453 * This base implementation of `_.zipObject` which assigns values using `assignFunc`.
7454 *
7455 * @private
7456 * @param {Array} props The property names.
7457 * @param {Array} values The property values.
7458 * @param {Function} assignFunc The function to assign values.
7459 * @returns {Object} Returns the new object.
7460 */
7461 function baseZipObject(props, values, assignFunc) {
7462 var index = -1,
7463 length = props.length,
7464 valsLength = values.length,
7465 result = {};
7466
7467 while (++index < length) {
7468 assignFunc(result, props[index], index < valsLength ? values[index] : undefined);
7469 }
7470 return result;
7471 }
7472
7473 /**
7474 * Creates a clone of `buffer`.
7475 *
7476 * @private
7477 * @param {Buffer} buffer The buffer to clone.
7478 * @param {boolean} [isDeep] Specify a deep clone.
7479 * @returns {Buffer} Returns the cloned buffer.
7480 */
7481 function cloneBuffer(buffer, isDeep) {
7482 if (isDeep) {
7483 return buffer.slice();
7484 }
7485 var result = new buffer.constructor(buffer.length);
7486 buffer.copy(result);
7487 return result;
7488 }
7489
7490 /**
7491 * Creates a clone of `arrayBuffer`.
7492 *
7493 * @private
7494 * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
7495 * @returns {ArrayBuffer} Returns the cloned array buffer.
7496 */
7497 function cloneArrayBuffer(arrayBuffer) {
7498 var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
7499 new Uint8Array(result).set(new Uint8Array(arrayBuffer));
7500 return result;
7501 }
7502
7503 /**
7504 * Creates a clone of `map`.
7505 *
7506 * @private
7507 * @param {Object} map The map to clone.
7508 * @returns {Object} Returns the cloned map.
7509 */
7510 function cloneMap(map) {
7511 return arrayReduce(mapToArray(map), addMapEntry, new map.constructor);
7512 }
7513
7514 /**
7515 * Creates a clone of `regexp`.
7516 *
7517 * @private
7518 * @param {Object} regexp The regexp to clone.
7519 * @returns {Object} Returns the cloned regexp.
7520 */
7521 function cloneRegExp(regexp) {
7522 var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
7523 result.lastIndex = regexp.lastIndex;
7524 return result;
7525 }
7526
7527 /**
7528 * Creates a clone of `set`.
7529 *
7530 * @private
7531 * @param {Object} set The set to clone.
7532 * @returns {Object} Returns the cloned set.
7533 */
7534 function cloneSet(set) {
7535 return arrayReduce(setToArray(set), addSetEntry, new set.constructor);
7536 }
7537
7538 /**
7539 * Creates a clone of the `symbol` object.
7540 *
7541 * @private
7542 * @param {Object} symbol The symbol object to clone.
7543 * @returns {Object} Returns the cloned symbol object.
7544 */
7545 function cloneSymbol(symbol) {
7546 return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
7547 }
7548
7549 /**
7550 * Creates a clone of `typedArray`.
7551 *
7552 * @private
7553 * @param {Object} typedArray The typed array to clone.
7554 * @param {boolean} [isDeep] Specify a deep clone.
7555 * @returns {Object} Returns the cloned typed array.
7556 */
7557 function cloneTypedArray(typedArray, isDeep) {
7558 var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
7559 return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
7560 }
7561
7562 /**
7563 * Creates an array that is the composition of partially applied arguments,
7564 * placeholders, and provided arguments into a single array of arguments.
7565 *
7566 * @private
7567 * @param {Array|Object} args The provided arguments.
7568 * @param {Array} partials The arguments to prepend to those provided.
7569 * @param {Array} holders The `partials` placeholder indexes.
7570 * @params {boolean} [isCurried] Specify composing for a curried function.
7571 * @returns {Array} Returns the new array of composed arguments.
7572 */
7573 function composeArgs(args, partials, holders, isCurried) {
7574 var argsIndex = -1,
7575 argsLength = args.length,
7576 holdersLength = holders.length,
7577 leftIndex = -1,
7578 leftLength = partials.length,
7579 rangeLength = nativeMax(argsLength - holdersLength, 0),
7580 result = Array(leftLength + rangeLength),
7581 isUncurried = !isCurried;
7582
7583 while (++leftIndex < leftLength) {
7584 result[leftIndex] = partials[leftIndex];
7585 }
7586 while (++argsIndex < holdersLength) {
7587 if (isUncurried || argsIndex < argsLength) {
7588 result[holders[argsIndex]] = args[argsIndex];
7589 }
7590 }
7591 while (rangeLength--) {
7592 result[leftIndex++] = args[argsIndex++];
7593 }
7594 return result;
7595 }
7596
7597 /**
7598 * This function is like `composeArgs` except that the arguments composition
7599 * is tailored for `_.partialRight`.
7600 *
7601 * @private
7602 * @param {Array|Object} args The provided arguments.
7603 * @param {Array} partials The arguments to append to those provided.
7604 * @param {Array} holders The `partials` placeholder indexes.
7605 * @params {boolean} [isCurried] Specify composing for a curried function.
7606 * @returns {Array} Returns the new array of composed arguments.
7607 */
7608 function composeArgsRight(args, partials, holders, isCurried) {
7609 var argsIndex = -1,
7610 argsLength = args.length,
7611 holdersIndex = -1,
7612 holdersLength = holders.length,
7613 rightIndex = -1,
7614 rightLength = partials.length,
7615 rangeLength = nativeMax(argsLength - holdersLength, 0),
7616 result = Array(rangeLength + rightLength),
7617 isUncurried = !isCurried;
7618
7619 while (++argsIndex < rangeLength) {
7620 result[argsIndex] = args[argsIndex];
7621 }
7622 var offset = argsIndex;
7623 while (++rightIndex < rightLength) {
7624 result[offset + rightIndex] = partials[rightIndex];
7625 }
7626 while (++holdersIndex < holdersLength) {
7627 if (isUncurried || argsIndex < argsLength) {
7628 result[offset + holders[holdersIndex]] = args[argsIndex++];
7629 }
7630 }
7631 return result;
7632 }
7633
7634 /**
7635 * Copies the values of `source` to `array`.
7636 *
7637 * @private
7638 * @param {Array} source The array to copy values from.
7639 * @param {Array} [array=[]] The array to copy values to.
7640 * @returns {Array} Returns `array`.
7641 */
7642 function copyArray(source, array) {
7643 var index = -1,
7644 length = source.length;
7645
7646 array || (array = Array(length));
7647 while (++index < length) {
7648 array[index] = source[index];
7649 }
7650 return array;
7651 }
7652
7653 /**
7654 * Copies properties of `source` to `object`.
7655 *
7656 * @private
7657 * @param {Object} source The object to copy properties from.
7658 * @param {Array} props The property names to copy.
7659 * @param {Object} [object={}] The object to copy properties to.
7660 * @returns {Object} Returns `object`.
7661 */
7662 function copyObject(source, props, object) {
7663 return copyObjectWith(source, props, object);
7664 }
7665
7666 /**
7667 * This function is like `copyObject` except that it accepts a function to
7668 * customize copied values.
7669 *
7670 * @private
7671 * @param {Object} source The object to copy properties from.
7672 * @param {Array} props The property names to copy.
7673 * @param {Object} [object={}] The object to copy properties to.
7674 * @param {Function} [customizer] The function to customize copied values.
7675 * @returns {Object} Returns `object`.
7676 */
7677 function copyObjectWith(source, props, object, customizer) {
7678 object || (object = {});
7679
7680 var index = -1,
7681 length = props.length;
7682
7683 while (++index < length) {
7684 var key = props[index];
7685
7686 var newValue = customizer
7687 ? customizer(object[key], source[key], key, object, source)
7688 : source[key];
7689
7690 assignValue(object, key, newValue);
7691 }
7692 return object;
7693 }
7694
7695 /**
7696 * Copies own symbol properties of `source` to `object`.
7697 *
7698 * @private
7699 * @param {Object} source The object to copy symbols from.
7700 * @param {Object} [object={}] The object to copy symbols to.
7701 * @returns {Object} Returns `object`.
7702 */
7703 function copySymbols(source, object) {
7704 return copyObject(source, getSymbols(source), object);
7705 }
7706
7707 /**
7708 * Creates a function like `_.groupBy`.
7709 *
7710 * @private
7711 * @param {Function} setter The function to set accumulator values.
7712 * @param {Function} [initializer] The accumulator object initializer.
7713 * @returns {Function} Returns the new aggregator function.
7714 */
7715 function createAggregator(setter, initializer) {
7716 return function(collection, iteratee) {
7717 var func = isArray(collection) ? arrayAggregator : baseAggregator,
7718 accumulator = initializer ? initializer() : {};
7719
7720 return func(collection, setter, getIteratee(iteratee), accumulator);
7721 };
7722 }
7723
7724 /**
7725 * Creates a function like `_.assign`.
7726 *
7727 * @private
7728 * @param {Function} assigner The function to assign values.
7729 * @returns {Function} Returns the new assigner function.
7730 */
7731 function createAssigner(assigner) {
7732 return rest(function(object, sources) {
7733 var index = -1,
7734 length = sources.length,
7735 customizer = length > 1 ? sources[length - 1] : undefined,
7736 guard = length > 2 ? sources[2] : undefined;
7737
7738 customizer = typeof customizer == 'function'
7739 ? (length--, customizer)
7740 : undefined;
7741
7742 if (guard && isIterateeCall(sources[0], sources[1], guard)) {
7743 customizer = length < 3 ? undefined : customizer;
7744 length = 1;
7745 }
7746 object = Object(object);
7747 while (++index < length) {
7748 var source = sources[index];
7749 if (source) {
7750 assigner(object, source, index, customizer);
7751 }
7752 }
7753 return object;
7754 });
7755 }
7756
7757 /**
7758 * Creates a `baseEach` or `baseEachRight` function.
7759 *
7760 * @private
7761 * @param {Function} eachFunc The function to iterate over a collection.
7762 * @param {boolean} [fromRight] Specify iterating from right to left.
7763 * @returns {Function} Returns the new base function.
7764 */
7765 function createBaseEach(eachFunc, fromRight) {
7766 return function(collection, iteratee) {
7767 if (collection == null) {
7768 return collection;
7769 }
7770 if (!isArrayLike(collection)) {
7771 return eachFunc(collection, iteratee);
7772 }
7773 var length = collection.length,
7774 index = fromRight ? length : -1,
7775 iterable = Object(collection);
7776
7777 while ((fromRight ? index-- : ++index < length)) {
7778 if (iteratee(iterable[index], index, iterable) === false) {
7779 break;
7780 }
7781 }
7782 return collection;
7783 };
7784 }
7785
7786 /**
7787 * Creates a base function for methods like `_.forIn`.
7788 *
7789 * @private
7790 * @param {boolean} [fromRight] Specify iterating from right to left.
7791 * @returns {Function} Returns the new base function.
7792 */
7793 function createBaseFor(fromRight) {
7794 return function(object, iteratee, keysFunc) {
7795 var index = -1,
7796 iterable = Object(object),
7797 props = keysFunc(object),
7798 length = props.length;
7799
7800 while (length--) {
7801 var key = props[fromRight ? length : ++index];
7802 if (iteratee(iterable[key], key, iterable) === false) {
7803 break;
7804 }
7805 }
7806 return object;
7807 };
7808 }
7809
7810 /**
7811 * Creates a function that wraps `func` to invoke it with the optional `this`
7812 * binding of `thisArg`.
7813 *
7814 * @private
7815 * @param {Function} func The function to wrap.
7816 * @param {number} bitmask The bitmask of wrapper flags. See `createWrapper` for more details.
7817 * @param {*} [thisArg] The `this` binding of `func`.
7818 * @returns {Function} Returns the new wrapped function.
7819 */
7820 function createBaseWrapper(func, bitmask, thisArg) {
7821 var isBind = bitmask & BIND_FLAG,
7822 Ctor = createCtorWrapper(func);
7823
7824 function wrapper() {
7825 var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
7826 return fn.apply(isBind ? thisArg : this, arguments);
7827 }
7828 return wrapper;
7829 }
7830
7831 /**
7832 * Creates a function like `_.lowerFirst`.
7833 *
7834 * @private
7835 * @param {string} methodName The name of the `String` case method to use.
7836 * @returns {Function} Returns the new function.
7837 */
7838 function createCaseFirst(methodName) {
7839 return function(string) {
7840 string = toString(string);
7841
7842 var strSymbols = reHasComplexSymbol.test(string)
7843 ? stringToArray(string)
7844 : undefined;
7845
7846 var chr = strSymbols ? strSymbols[0] : string.charAt(0),
7847 trailing = strSymbols ? strSymbols.slice(1).join('') : string.slice(1);
7848
7849 return chr[methodName]() + trailing;
7850 };
7851 }
7852
7853 /**
7854 * Creates a function like `_.camelCase`.
7855 *
7856 * @private
7857 * @param {Function} callback The function to combine each word.
7858 * @returns {Function} Returns the new compounder function.
7859 */
7860 function createCompounder(callback) {
7861 return function(string) {
7862 return arrayReduce(words(deburr(string)), callback, '');
7863 };
7864 }
7865
7866 /**
7867 * Creates a function that produces an instance of `Ctor` regardless of
7868 * whether it was invoked as part of a `new` expression or by `call` or `apply`.
7869 *
7870 * @private
7871 * @param {Function} Ctor The constructor to wrap.
7872 * @returns {Function} Returns the new wrapped function.
7873 */
7874 function createCtorWrapper(Ctor) {
7875 return function() {
7876 // Use a `switch` statement to work with class constructors.
7877 // See http://ecma-international.org/ecma-262/6.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
7878 // for more details.
7879 var args = arguments;
7880 switch (args.length) {
7881 case 0: return new Ctor;
7882 case 1: return new Ctor(args[0]);
7883 case 2: return new Ctor(args[0], args[1]);
7884 case 3: return new Ctor(args[0], args[1], args[2]);
7885 case 4: return new Ctor(args[0], args[1], args[2], args[3]);
7886 case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
7887 case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
7888 case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
7889 }
7890 var thisBinding = baseCreate(Ctor.prototype),
7891 result = Ctor.apply(thisBinding, args);
7892
7893 // Mimic the constructor's `return` behavior.
7894 // See https://es5.github.io/#x13.2.2 for more details.
7895 return isObject(result) ? result : thisBinding;
7896 };
7897 }
7898
7899 /**
7900 * Creates a function that wraps `func` to enable currying.
7901 *
7902 * @private
7903 * @param {Function} func The function to wrap.
7904 * @param {number} bitmask The bitmask of wrapper flags. See `createWrapper` for more details.
7905 * @param {number} arity The arity of `func`.
7906 * @returns {Function} Returns the new wrapped function.
7907 */
7908 function createCurryWrapper(func, bitmask, arity) {
7909 var Ctor = createCtorWrapper(func);
7910
7911 function wrapper() {
7912 var length = arguments.length,
7913 args = Array(length),
7914 index = length,
7915 placeholder = getPlaceholder(wrapper);
7916
7917 while (index--) {
7918 args[index] = arguments[index];
7919 }
7920 var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
7921 ? []
7922 : replaceHolders(args, placeholder);
7923
7924 length -= holders.length;
7925 if (length < arity) {
7926 return createRecurryWrapper(
7927 func, bitmask, createHybridWrapper, wrapper.placeholder, undefined,
7928 args, holders, undefined, undefined, arity - length);
7929 }
7930 var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
7931 return apply(fn, this, args);
7932 }
7933 return wrapper;
7934 }
7935
7936 /**
7937 * Creates a `_.flow` or `_.flowRight` function.
7938 *
7939 * @private
7940 * @param {boolean} [fromRight] Specify iterating from right to left.
7941 * @returns {Function} Returns the new flow function.
7942 */
7943 function createFlow(fromRight) {
7944 return rest(function(funcs) {
7945 funcs = baseFlatten(funcs, 1);
7946
7947 var length = funcs.length,
7948 index = length,
7949 prereq = LodashWrapper.prototype.thru;
7950
7951 if (fromRight) {
7952 funcs.reverse();
7953 }
7954 while (index--) {
7955 var func = funcs[index];
7956 if (typeof func != 'function') {
7957 throw new TypeError(FUNC_ERROR_TEXT);
7958 }
7959 if (prereq && !wrapper && getFuncName(func) == 'wrapper') {
7960 var wrapper = new LodashWrapper([], true);
7961 }
7962 }
7963 index = wrapper ? index : length;
7964 while (++index < length) {
7965 func = funcs[index];
7966
7967 var funcName = getFuncName(func),
7968 data = funcName == 'wrapper' ? getData(func) : undefined;
7969
7970 if (data && isLaziable(data[0]) &&
7971 data[1] == (ARY_FLAG | CURRY_FLAG | PARTIAL_FLAG | REARG_FLAG) &&
7972 !data[4].length && data[9] == 1
7973 ) {
7974 wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);
7975 } else {
7976 wrapper = (func.length == 1 && isLaziable(func)) ? wrapper[funcName]() : wrapper.thru(func);
7977 }
7978 }
7979 return function() {
7980 var args = arguments,
7981 value = args[0];
7982
7983 if (wrapper && args.length == 1 &&
7984 isArray(value) && value.length >= LARGE_ARRAY_SIZE) {
7985 return wrapper.plant(value).value();
7986 }
7987 var index = 0,
7988 result = length ? funcs[index].apply(this, args) : value;
7989
7990 while (++index < length) {
7991 result = funcs[index].call(this, result);
7992 }
7993 return result;
7994 };
7995 });
7996 }
7997
7998 /**
7999 * Creates a function that wraps `func` to invoke it with optional `this`
8000 * binding of `thisArg`, partial application, and currying.
8001 *
8002 * @private
8003 * @param {Function|string} func The function or method name to wrap.
8004 * @param {number} bitmask The bitmask of wrapper flags. See `createWrapper` for more details.
8005 * @param {*} [thisArg] The `this` binding of `func`.
8006 * @param {Array} [partials] The arguments to prepend to those provided to the new function.
8007 * @param {Array} [holders] The `partials` placeholder indexes.
8008 * @param {Array} [partialsRight] The arguments to append to those provided to the new function.
8009 * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
8010 * @param {Array} [argPos] The argument positions of the new function.
8011 * @param {number} [ary] The arity cap of `func`.
8012 * @param {number} [arity] The arity of `func`.
8013 * @returns {Function} Returns the new wrapped function.
8014 */
8015 function createHybridWrapper(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
8016 var isAry = bitmask & ARY_FLAG,
8017 isBind = bitmask & BIND_FLAG,
8018 isBindKey = bitmask & BIND_KEY_FLAG,
8019 isCurried = bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG),
8020 isFlip = bitmask & FLIP_FLAG,
8021 Ctor = isBindKey ? undefined : createCtorWrapper(func);
8022
8023 function wrapper() {
8024 var length = arguments.length,
8025 index = length,
8026 args = Array(length);
8027
8028 while (index--) {
8029 args[index] = arguments[index];
8030 }
8031 if (isCurried) {
8032 var placeholder = getPlaceholder(wrapper),
8033 holdersCount = countHolders(args, placeholder);
8034 }
8035 if (partials) {
8036 args = composeArgs(args, partials, holders, isCurried);
8037 }
8038 if (partialsRight) {
8039 args = composeArgsRight(args, partialsRight, holdersRight, isCurried);
8040 }
8041 length -= holdersCount;
8042 if (isCurried && length < arity) {
8043 var newHolders = replaceHolders(args, placeholder);
8044 return createRecurryWrapper(
8045 func, bitmask, createHybridWrapper, wrapper.placeholder, thisArg,
8046 args, newHolders, argPos, ary, arity - length
8047 );
8048 }
8049 var thisBinding = isBind ? thisArg : this,
8050 fn = isBindKey ? thisBinding[func] : func;
8051
8052 length = args.length;
8053 if (argPos) {
8054 args = reorder(args, argPos);
8055 } else if (isFlip && length > 1) {
8056 args.reverse();
8057 }
8058 if (isAry && ary < length) {
8059 args.length = ary;
8060 }
8061 if (this && this !== root && this instanceof wrapper) {
8062 fn = Ctor || createCtorWrapper(fn);
8063 }
8064 return fn.apply(thisBinding, args);
8065 }
8066 return wrapper;
8067 }
8068
8069 /**
8070 * Creates a function like `_.invertBy`.
8071 *
8072 * @private
8073 * @param {Function} setter The function to set accumulator values.
8074 * @param {Function} toIteratee The function to resolve iteratees.
8075 * @returns {Function} Returns the new inverter function.
8076 */
8077 function createInverter(setter, toIteratee) {
8078 return function(object, iteratee) {
8079 return baseInverter(object, setter, toIteratee(iteratee), {});
8080 };
8081 }
8082
8083 /**
8084 * Creates a function like `_.over`.
8085 *
8086 * @private
8087 * @param {Function} arrayFunc The function to iterate over iteratees.
8088 * @returns {Function} Returns the new invoker function.
8089 */
8090 function createOver(arrayFunc) {
8091 return rest(function(iteratees) {
8092 iteratees = arrayMap(baseFlatten(iteratees, 1), getIteratee());
8093 return rest(function(args) {
8094 var thisArg = this;
8095 return arrayFunc(iteratees, function(iteratee) {
8096 return apply(iteratee, thisArg, args);
8097 });
8098 });
8099 });
8100 }
8101
8102 /**
8103 * Creates the padding for `string` based on `length`. The `chars` string
8104 * is truncated if the number of characters exceeds `length`.
8105 *
8106 * @private
8107 * @param {string} string The string to create padding for.
8108 * @param {number} [length=0] The padding length.
8109 * @param {string} [chars=' '] The string used as padding.
8110 * @returns {string} Returns the padding for `string`.
8111 */
8112 function createPadding(string, length, chars) {
8113 length = toInteger(length);
8114
8115 var strLength = stringSize(string);
8116 if (!length || strLength >= length) {
8117 return '';
8118 }
8119 var padLength = length - strLength;
8120 chars = chars === undefined ? ' ' : (chars + '');
8121
8122 var result = repeat(chars, nativeCeil(padLength / stringSize(chars)));
8123 return reHasComplexSymbol.test(chars)
8124 ? stringToArray(result).slice(0, padLength).join('')
8125 : result.slice(0, padLength);
8126 }
8127
8128 /**
8129 * Creates a function that wraps `func` to invoke it with the optional `this`
8130 * binding of `thisArg` and the `partials` prepended to those provided to
8131 * the wrapper.
8132 *
8133 * @private
8134 * @param {Function} func The function to wrap.
8135 * @param {number} bitmask The bitmask of wrapper flags. See `createWrapper` for more details.
8136 * @param {*} thisArg The `this` binding of `func`.
8137 * @param {Array} partials The arguments to prepend to those provided to the new function.
8138 * @returns {Function} Returns the new wrapped function.
8139 */
8140 function createPartialWrapper(func, bitmask, thisArg, partials) {
8141 var isBind = bitmask & BIND_FLAG,
8142 Ctor = createCtorWrapper(func);
8143
8144 function wrapper() {
8145 var argsIndex = -1,
8146 argsLength = arguments.length,
8147 leftIndex = -1,
8148 leftLength = partials.length,
8149 args = Array(leftLength + argsLength),
8150 fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
8151
8152 while (++leftIndex < leftLength) {
8153 args[leftIndex] = partials[leftIndex];
8154 }
8155 while (argsLength--) {
8156 args[leftIndex++] = arguments[++argsIndex];
8157 }
8158 return apply(fn, isBind ? thisArg : this, args);
8159 }
8160 return wrapper;
8161 }
8162
8163 /**
8164 * Creates a `_.range` or `_.rangeRight` function.
8165 *
8166 * @private
8167 * @param {boolean} [fromRight] Specify iterating from right to left.
8168 * @returns {Function} Returns the new range function.
8169 */
8170 function createRange(fromRight) {
8171 return function(start, end, step) {
8172 if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {
8173 end = step = undefined;
8174 }
8175 // Ensure the sign of `-0` is preserved.
8176 start = toNumber(start);
8177 start = start === start ? start : 0;
8178 if (end === undefined) {
8179 end = start;
8180 start = 0;
8181 } else {
8182 end = toNumber(end) || 0;
8183 }
8184 step = step === undefined ? (start < end ? 1 : -1) : (toNumber(step) || 0);
8185 return baseRange(start, end, step, fromRight);
8186 };
8187 }
8188
8189 /**
8190 * Creates a function that wraps `func` to continue currying.
8191 *
8192 * @private
8193 * @param {Function} func The function to wrap.
8194 * @param {number} bitmask The bitmask of wrapper flags. See `createWrapper` for more details.
8195 * @param {Function} wrapFunc The function to create the `func` wrapper.
8196 * @param {*} placeholder The placeholder value.
8197 * @param {*} [thisArg] The `this` binding of `func`.
8198 * @param {Array} [partials] The arguments to prepend to those provided to the new function.
8199 * @param {Array} [holders] The `partials` placeholder indexes.
8200 * @param {Array} [argPos] The argument positions of the new function.
8201 * @param {number} [ary] The arity cap of `func`.
8202 * @param {number} [arity] The arity of `func`.
8203 * @returns {Function} Returns the new wrapped function.
8204 */
8205 function createRecurryWrapper(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
8206 var isCurry = bitmask & CURRY_FLAG,
8207 newArgPos = argPos ? copyArray(argPos) : undefined,
8208 newHolders = isCurry ? holders : undefined,
8209 newHoldersRight = isCurry ? undefined : holders,
8210 newPartials = isCurry ? partials : undefined,
8211 newPartialsRight = isCurry ? undefined : partials;
8212
8213 bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG);
8214 bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG);
8215
8216 if (!(bitmask & CURRY_BOUND_FLAG)) {
8217 bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG);
8218 }
8219 var newData = [
8220 func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,
8221 newHoldersRight, newArgPos, ary, arity
8222 ];
8223
8224 var result = wrapFunc.apply(undefined, newData);
8225 if (isLaziable(func)) {
8226 setData(result, newData);
8227 }
8228 result.placeholder = placeholder;
8229 return result;
8230 }
8231
8232 /**
8233 * Creates a function like `_.round`.
8234 *
8235 * @private
8236 * @param {string} methodName The name of the `Math` method to use when rounding.
8237 * @returns {Function} Returns the new round function.
8238 */
8239 function createRound(methodName) {
8240 var func = Math[methodName];
8241 return function(number, precision) {
8242 number = toNumber(number);
8243 precision = toInteger(precision);
8244 if (precision) {
8245 // Shift with exponential notation to avoid floating-point issues.
8246 // See [MDN](https://mdn.io/round#Examples) for more details.
8247 var pair = (toString(number) + 'e').split('e'),
8248 value = func(pair[0] + 'e' + (+pair[1] + precision));
8249
8250 pair = (toString(value) + 'e').split('e');
8251 return +(pair[0] + 'e' + (+pair[1] - precision));
8252 }
8253 return func(number);
8254 };
8255 }
8256
8257 /**
8258 * Creates a set of `values`.
8259 *
8260 * @private
8261 * @param {Array} values The values to add to the set.
8262 * @returns {Object} Returns the new set.
8263 */
8264 var createSet = !(Set && new Set([1, 2]).size === 2) ? noop : function(values) {
8265 return new Set(values);
8266 };
8267
8268 /**
8269 * Creates a function that either curries or invokes `func` with optional
8270 * `this` binding and partially applied arguments.
8271 *
8272 * @private
8273 * @param {Function|string} func The function or method name to wrap.
8274 * @param {number} bitmask The bitmask of wrapper flags.
8275 * The bitmask may be composed of the following flags:
8276 * 1 - `_.bind`
8277 * 2 - `_.bindKey`
8278 * 4 - `_.curry` or `_.curryRight` of a bound function
8279 * 8 - `_.curry`
8280 * 16 - `_.curryRight`
8281 * 32 - `_.partial`
8282 * 64 - `_.partialRight`
8283 * 128 - `_.rearg`
8284 * 256 - `_.ary`
8285 * @param {*} [thisArg] The `this` binding of `func`.
8286 * @param {Array} [partials] The arguments to be partially applied.
8287 * @param {Array} [holders] The `partials` placeholder indexes.
8288 * @param {Array} [argPos] The argument positions of the new function.
8289 * @param {number} [ary] The arity cap of `func`.
8290 * @param {number} [arity] The arity of `func`.
8291 * @returns {Function} Returns the new wrapped function.
8292 */
8293 function createWrapper(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
8294 var isBindKey = bitmask & BIND_KEY_FLAG;
8295 if (!isBindKey && typeof func != 'function') {
8296 throw new TypeError(FUNC_ERROR_TEXT);
8297 }
8298 var length = partials ? partials.length : 0;
8299 if (!length) {
8300 bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG);
8301 partials = holders = undefined;
8302 }
8303 ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);
8304 arity = arity === undefined ? arity : toInteger(arity);
8305 length -= holders ? holders.length : 0;
8306
8307 if (bitmask & PARTIAL_RIGHT_FLAG) {
8308 var partialsRight = partials,
8309 holdersRight = holders;
8310
8311 partials = holders = undefined;
8312 }
8313 var data = isBindKey ? undefined : getData(func);
8314
8315 var newData = [
8316 func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
8317 argPos, ary, arity
8318 ];
8319
8320 if (data) {
8321 mergeData(newData, data);
8322 }
8323 func = newData[0];
8324 bitmask = newData[1];
8325 thisArg = newData[2];
8326 partials = newData[3];
8327 holders = newData[4];
8328 arity = newData[9] = newData[9] == null
8329 ? (isBindKey ? 0 : func.length)
8330 : nativeMax(newData[9] - length, 0);
8331
8332 if (!arity && bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG)) {
8333 bitmask &= ~(CURRY_FLAG | CURRY_RIGHT_FLAG);
8334 }
8335 if (!bitmask || bitmask == BIND_FLAG) {
8336 var result = createBaseWrapper(func, bitmask, thisArg);
8337 } else if (bitmask == CURRY_FLAG || bitmask == CURRY_RIGHT_FLAG) {
8338 result = createCurryWrapper(func, bitmask, arity);
8339 } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !holders.length) {
8340 result = createPartialWrapper(func, bitmask, thisArg, partials);
8341 } else {
8342 result = createHybridWrapper.apply(undefined, newData);
8343 }
8344 var setter = data ? baseSetData : setData;
8345 return setter(result, newData);
8346 }
8347
8348 /**
8349 * A specialized version of `baseIsEqualDeep` for arrays with support for
8350 * partial deep comparisons.
8351 *
8352 * @private
8353 * @param {Array} array The array to compare.
8354 * @param {Array} other The other array to compare.
8355 * @param {Function} equalFunc The function to determine equivalents of values.
8356 * @param {Function} customizer The function to customize comparisons.
8357 * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` for more details.
8358 * @param {Object} stack Tracks traversed `array` and `other` objects.
8359 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
8360 */
8361 function equalArrays(array, other, equalFunc, customizer, bitmask, stack) {
8362 var index = -1,
8363 isPartial = bitmask & PARTIAL_COMPARE_FLAG,
8364 isUnordered = bitmask & UNORDERED_COMPARE_FLAG,
8365 arrLength = array.length,
8366 othLength = other.length;
8367
8368 if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
8369 return false;
8370 }
8371 // Assume cyclic values are equal.
8372 var stacked = stack.get(array);
8373 if (stacked) {
8374 return stacked == other;
8375 }
8376 var result = true;
8377 stack.set(array, other);
8378
8379 // Ignore non-index properties.
8380 while (++index < arrLength) {
8381 var arrValue = array[index],
8382 othValue = other[index];
8383
8384 if (customizer) {
8385 var compared = isPartial
8386 ? customizer(othValue, arrValue, index, other, array, stack)
8387 : customizer(arrValue, othValue, index, array, other, stack);
8388 }
8389 if (compared !== undefined) {
8390 if (compared) {
8391 continue;
8392 }
8393 result = false;
8394 break;
8395 }
8396 // Recursively compare arrays (susceptible to call stack limits).
8397 if (isUnordered) {
8398 if (!arraySome(other, function(othValue) {
8399 return arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack);
8400 })) {
8401 result = false;
8402 break;
8403 }
8404 } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) {
8405 result = false;
8406 break;
8407 }
8408 }
8409 stack['delete'](array);
8410 return result;
8411 }
8412
8413 /**
8414 * A specialized version of `baseIsEqualDeep` for comparing objects of
8415 * the same `toStringTag`.
8416 *
8417 * **Note:** This function only supports comparing values with tags of
8418 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
8419 *
8420 * @private
8421 * @param {Object} object The object to compare.
8422 * @param {Object} other The other object to compare.
8423 * @param {string} tag The `toStringTag` of the objects to compare.
8424 * @param {Function} equalFunc The function to determine equivalents of values.
8425 * @param {Function} customizer The function to customize comparisons.
8426 * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` for more details.
8427 * @param {Object} stack Tracks traversed `object` and `other` objects.
8428 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
8429 */
8430 function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) {
8431 switch (tag) {
8432 case arrayBufferTag:
8433 if ((object.byteLength != other.byteLength) ||
8434 !equalFunc(new Uint8Array(object), new Uint8Array(other))) {
8435 return false;
8436 }
8437 return true;
8438
8439 case boolTag:
8440 case dateTag:
8441 // Coerce dates and booleans to numbers, dates to milliseconds and booleans
8442 // to `1` or `0` treating invalid dates coerced to `NaN` as not equal.
8443 return +object == +other;
8444
8445 case errorTag:
8446 return object.name == other.name && object.message == other.message;
8447
8448 case numberTag:
8449 // Treat `NaN` vs. `NaN` as equal.
8450 return (object != +object) ? other != +other : object == +other;
8451
8452 case regexpTag:
8453 case stringTag:
8454 // Coerce regexes to strings and treat strings primitives and string
8455 // objects as equal. See https://es5.github.io/#x15.10.6.4 for more details.
8456 return object == (other + '');
8457
8458 case mapTag:
8459 var convert = mapToArray;
8460
8461 case setTag:
8462 var isPartial = bitmask & PARTIAL_COMPARE_FLAG;
8463 convert || (convert = setToArray);
8464
8465 if (object.size != other.size && !isPartial) {
8466 return false;
8467 }
8468 // Assume cyclic values are equal.
8469 var stacked = stack.get(object);
8470 if (stacked) {
8471 return stacked == other;
8472 }
8473 // Recursively compare objects (susceptible to call stack limits).
8474 return equalArrays(convert(object), convert(other), equalFunc, customizer, bitmask | UNORDERED_COMPARE_FLAG, stack.set(object, other));
8475
8476 case symbolTag:
8477 if (symbolValueOf) {
8478 return symbolValueOf.call(object) == symbolValueOf.call(other);
8479 }
8480 }
8481 return false;
8482 }
8483
8484 /**
8485 * A specialized version of `baseIsEqualDeep` for objects with support for
8486 * partial deep comparisons.
8487 *
8488 * @private
8489 * @param {Object} object The object to compare.
8490 * @param {Object} other The other object to compare.
8491 * @param {Function} equalFunc The function to determine equivalents of values.
8492 * @param {Function} customizer The function to customize comparisons.
8493 * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` for more details.
8494 * @param {Object} stack Tracks traversed `object` and `other` objects.
8495 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
8496 */
8497 function equalObjects(object, other, equalFunc, customizer, bitmask, stack) {
8498 var isPartial = bitmask & PARTIAL_COMPARE_FLAG,
8499 objProps = keys(object),
8500 objLength = objProps.length,
8501 othProps = keys(other),
8502 othLength = othProps.length;
8503
8504 if (objLength != othLength && !isPartial) {
8505 return false;
8506 }
8507 var index = objLength;
8508 while (index--) {
8509 var key = objProps[index];
8510 if (!(isPartial ? key in other : baseHas(other, key))) {
8511 return false;
8512 }
8513 }
8514 // Assume cyclic values are equal.
8515 var stacked = stack.get(object);
8516 if (stacked) {
8517 return stacked == other;
8518 }
8519 var result = true;
8520 stack.set(object, other);
8521
8522 var skipCtor = isPartial;
8523 while (++index < objLength) {
8524 key = objProps[index];
8525 var objValue = object[key],
8526 othValue = other[key];
8527
8528 if (customizer) {
8529 var compared = isPartial
8530 ? customizer(othValue, objValue, key, other, object, stack)
8531 : customizer(objValue, othValue, key, object, other, stack);
8532 }
8533 // Recursively compare objects (susceptible to call stack limits).
8534 if (!(compared === undefined
8535 ? (objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack))
8536 : compared
8537 )) {
8538 result = false;
8539 break;
8540 }
8541 skipCtor || (skipCtor = key == 'constructor');
8542 }
8543 if (result && !skipCtor) {
8544 var objCtor = object.constructor,
8545 othCtor = other.constructor;
8546
8547 // Non `Object` object instances with different constructors are not equal.
8548 if (objCtor != othCtor &&
8549 ('constructor' in object && 'constructor' in other) &&
8550 !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
8551 typeof othCtor == 'function' && othCtor instanceof othCtor)) {
8552 result = false;
8553 }
8554 }
8555 stack['delete'](object);
8556 return result;
8557 }
8558
8559 /**
8560 * Gets metadata for `func`.
8561 *
8562 * @private
8563 * @param {Function} func The function to query.
8564 * @returns {*} Returns the metadata for `func`.
8565 */
8566 var getData = !metaMap ? noop : function(func) {
8567 return metaMap.get(func);
8568 };
8569
8570 /**
8571 * Gets the name of `func`.
8572 *
8573 * @private
8574 * @param {Function} func The function to query.
8575 * @returns {string} Returns the function name.
8576 */
8577 function getFuncName(func) {
8578 var result = (func.name + ''),
8579 array = realNames[result],
8580 length = hasOwnProperty.call(realNames, result) ? array.length : 0;
8581
8582 while (length--) {
8583 var data = array[length],
8584 otherFunc = data.func;
8585 if (otherFunc == null || otherFunc == func) {
8586 return data.name;
8587 }
8588 }
8589 return result;
8590 }
8591
8592 /**
8593 * Gets the appropriate "iteratee" function. If the `_.iteratee` method is
8594 * customized this function returns the custom method, otherwise it returns
8595 * `baseIteratee`. If arguments are provided the chosen function is invoked
8596 * with them and its result is returned.
8597 *
8598 * @private
8599 * @param {*} [value] The value to convert to an iteratee.
8600 * @param {number} [arity] The arity of the created iteratee.
8601 * @returns {Function} Returns the chosen function or its result.
8602 */
8603 function getIteratee() {
8604 var result = lodash.iteratee || iteratee;
8605 result = result === iteratee ? baseIteratee : result;
8606 return arguments.length ? result(arguments[0], arguments[1]) : result;
8607 }
8608
8609 /**
8610 * Gets the "length" property value of `object`.
8611 *
8612 * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
8613 * that affects Safari on at least iOS 8.1-8.3 ARM64.
8614 *
8615 * @private
8616 * @param {Object} object The object to query.
8617 * @returns {*} Returns the "length" value.
8618 */
8619 var getLength = baseProperty('length');
8620
8621 /**
8622 * Gets the property names, values, and compare flags of `object`.
8623 *
8624 * @private
8625 * @param {Object} object The object to query.
8626 * @returns {Array} Returns the match data of `object`.
8627 */
8628 function getMatchData(object) {
8629 var result = toPairs(object),
8630 length = result.length;
8631
8632 while (length--) {
8633 result[length][2] = isStrictComparable(result[length][1]);
8634 }
8635 return result;
8636 }
8637
8638 /**
8639 * Gets the native function at `key` of `object`.
8640 *
8641 * @private
8642 * @param {Object} object The object to query.
8643 * @param {string} key The key of the method to get.
8644 * @returns {*} Returns the function if it's native, else `undefined`.
8645 */
8646 function getNative(object, key) {
8647 var value = object[key];
8648 return isNative(value) ? value : undefined;
8649 }
8650
8651 /**
8652 * Gets the argument placeholder value for `func`.
8653 *
8654 * @private
8655 * @param {Function} func The function to inspect.
8656 * @returns {*} Returns the placeholder value.
8657 */
8658 function getPlaceholder(func) {
8659 var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func;
8660 return object.placeholder;
8661 }
8662
8663 /**
8664 * Creates an array of the own symbol properties of `object`.
8665 *
8666 * @private
8667 * @param {Object} object The object to query.
8668 * @returns {Array} Returns the array of symbols.
8669 */
8670 var getSymbols = getOwnPropertySymbols || function() {
8671 return [];
8672 };
8673
8674 /**
8675 * Gets the `toStringTag` of `value`.
8676 *
8677 * @private
8678 * @param {*} value The value to query.
8679 * @returns {string} Returns the `toStringTag`.
8680 */
8681 function getTag(value) {
8682 return objectToString.call(value);
8683 }
8684
8685 // Fallback for IE 11 providing `toStringTag` values for maps, sets, and weakmaps.
8686 if ((Map && getTag(new Map) != mapTag) ||
8687 (Set && getTag(new Set) != setTag) ||
8688 (WeakMap && getTag(new WeakMap) != weakMapTag)) {
8689 getTag = function(value) {
8690 var result = objectToString.call(value),
8691 Ctor = result == objectTag ? value.constructor : null,
8692 ctorString = typeof Ctor == 'function' ? funcToString.call(Ctor) : '';
8693
8694 if (ctorString) {
8695 switch (ctorString) {
8696 case mapCtorString: return mapTag;
8697 case setCtorString: return setTag;
8698 case weakMapCtorString: return weakMapTag;
8699 }
8700 }
8701 return result;
8702 };
8703 }
8704
8705 /**
8706 * Gets the view, applying any `transforms` to the `start` and `end` positions.
8707 *
8708 * @private
8709 * @param {number} start The start of the view.
8710 * @param {number} end The end of the view.
8711 * @param {Array} transforms The transformations to apply to the view.
8712 * @returns {Object} Returns an object containing the `start` and `end`
8713 * positions of the view.
8714 */
8715 function getView(start, end, transforms) {
8716 var index = -1,
8717 length = transforms.length;
8718
8719 while (++index < length) {
8720 var data = transforms[index],
8721 size = data.size;
8722
8723 switch (data.type) {
8724 case 'drop': start += size; break;
8725 case 'dropRight': end -= size; break;
8726 case 'take': end = nativeMin(end, start + size); break;
8727 case 'takeRight': start = nativeMax(start, end - size); break;
8728 }
8729 }
8730 return { 'start': start, 'end': end };
8731 }
8732
8733 /**
8734 * Checks if `path` exists on `object`.
8735 *
8736 * @private
8737 * @param {Object} object The object to query.
8738 * @param {Array|string} path The path to check.
8739 * @param {Function} hasFunc The function to check properties.
8740 * @returns {boolean} Returns `true` if `path` exists, else `false`.
8741 */
8742 function hasPath(object, path, hasFunc) {
8743 if (object == null) {
8744 return false;
8745 }
8746 var result = hasFunc(object, path);
8747 if (!result && !isKey(path)) {
8748 path = baseCastPath(path);
8749 object = parent(object, path);
8750 if (object != null) {
8751 path = last(path);
8752 result = hasFunc(object, path);
8753 }
8754 }
8755 var length = object ? object.length : undefined;
8756 return result || (
8757 !!length && isLength(length) && isIndex(path, length) &&
8758 (isArray(object) || isString(object) || isArguments(object))
8759 );
8760 }
8761
8762 /**
8763 * Initializes an array clone.
8764 *
8765 * @private
8766 * @param {Array} array The array to clone.
8767 * @returns {Array} Returns the initialized clone.
8768 */
8769 function initCloneArray(array) {
8770 var length = array.length,
8771 result = array.constructor(length);
8772
8773 // Add properties assigned by `RegExp#exec`.
8774 if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
8775 result.index = array.index;
8776 result.input = array.input;
8777 }
8778 return result;
8779 }
8780
8781 /**
8782 * Initializes an object clone.
8783 *
8784 * @private
8785 * @param {Object} object The object to clone.
8786 * @returns {Object} Returns the initialized clone.
8787 */
8788 function initCloneObject(object) {
8789 return (typeof object.constructor == 'function' && !isPrototype(object))
8790 ? baseCreate(getPrototypeOf(object))
8791 : {};
8792 }
8793
8794 /**
8795 * Initializes an object clone based on its `toStringTag`.
8796 *
8797 * **Note:** This function only supports cloning values with tags of
8798 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
8799 *
8800 * @private
8801 * @param {Object} object The object to clone.
8802 * @param {string} tag The `toStringTag` of the object to clone.
8803 * @param {boolean} [isDeep] Specify a deep clone.
8804 * @returns {Object} Returns the initialized clone.
8805 */
8806 function initCloneByTag(object, tag, isDeep) {
8807 var Ctor = object.constructor;
8808 switch (tag) {
8809 case arrayBufferTag:
8810 return cloneArrayBuffer(object);
8811
8812 case boolTag:
8813 case dateTag:
8814 return new Ctor(+object);
8815
8816 case float32Tag: case float64Tag:
8817 case int8Tag: case int16Tag: case int32Tag:
8818 case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
8819 return cloneTypedArray(object, isDeep);
8820
8821 case mapTag:
8822 return cloneMap(object);
8823
8824 case numberTag:
8825 case stringTag:
8826 return new Ctor(object);
8827
8828 case regexpTag:
8829 return cloneRegExp(object);
8830
8831 case setTag:
8832 return cloneSet(object);
8833
8834 case symbolTag:
8835 return cloneSymbol(object);
8836 }
8837 }
8838
8839 /**
8840 * Creates an array of index keys for `object` values of arrays,
8841 * `arguments` objects, and strings, otherwise `null` is returned.
8842 *
8843 * @private
8844 * @param {Object} object The object to query.
8845 * @returns {Array|null} Returns index keys, else `null`.
8846 */
8847 function indexKeys(object) {
8848 var length = object ? object.length : undefined;
8849 if (isLength(length) &&
8850 (isArray(object) || isString(object) || isArguments(object))) {
8851 return baseTimes(length, String);
8852 }
8853 return null;
8854 }
8855
8856 /**
8857 * Checks if the given arguments are from an iteratee call.
8858 *
8859 * @private
8860 * @param {*} value The potential iteratee value argument.
8861 * @param {*} index The potential iteratee index or key argument.
8862 * @param {*} object The potential iteratee object argument.
8863 * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`.
8864 */
8865 function isIterateeCall(value, index, object) {
8866 if (!isObject(object)) {
8867 return false;
8868 }
8869 var type = typeof index;
8870 if (type == 'number'
8871 ? (isArrayLike(object) && isIndex(index, object.length))
8872 : (type == 'string' && index in object)) {
8873 return eq(object[index], value);
8874 }
8875 return false;
8876 }
8877
8878 /**
8879 * Checks if `value` is a property name and not a property path.
8880 *
8881 * @private
8882 * @param {*} value The value to check.
8883 * @param {Object} [object] The object to query keys on.
8884 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
8885 */
8886 function isKey(value, object) {
8887 if (typeof value == 'number') {
8888 return true;
8889 }
8890 return !isArray(value) &&
8891 (reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
8892 (object != null && value in Object(object)));
8893 }
8894
8895 /**
8896 * Checks if `value` is suitable for use as unique object key.
8897 *
8898 * @private
8899 * @param {*} value The value to check.
8900 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
8901 */
8902 function isKeyable(value) {
8903 var type = typeof value;
8904 return type == 'number' || type == 'boolean' ||
8905 (type == 'string' && value != '__proto__') || value == null;
8906 }
8907
8908 /**
8909 * Checks if `func` has a lazy counterpart.
8910 *
8911 * @private
8912 * @param {Function} func The function to check.
8913 * @returns {boolean} Returns `true` if `func` has a lazy counterpart, else `false`.
8914 */
8915 function isLaziable(func) {
8916 var funcName = getFuncName(func),
8917 other = lodash[funcName];
8918
8919 if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {
8920 return false;
8921 }
8922 if (func === other) {
8923 return true;
8924 }
8925 var data = getData(other);
8926 return !!data && func === data[0];
8927 }
8928
8929 /**
8930 * Checks if `value` is likely a prototype object.
8931 *
8932 * @private
8933 * @param {*} value The value to check.
8934 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
8935 */
8936 function isPrototype(value) {
8937 var Ctor = value && value.constructor,
8938 proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
8939
8940 return value === proto;
8941 }
8942
8943 /**
8944 * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
8945 *
8946 * @private
8947 * @param {*} value The value to check.
8948 * @returns {boolean} Returns `true` if `value` if suitable for strict
8949 * equality comparisons, else `false`.
8950 */
8951 function isStrictComparable(value) {
8952 return value === value && !isObject(value);
8953 }
8954
8955 /**
8956 * Merges the function metadata of `source` into `data`.
8957 *
8958 * Merging metadata reduces the number of wrappers used to invoke a function.
8959 * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
8960 * may be applied regardless of execution order. Methods like `_.ary` and `_.rearg`
8961 * modify function arguments, making the order in which they are executed important,
8962 * preventing the merging of metadata. However, we make an exception for a safe
8963 * combined case where curried functions have `_.ary` and or `_.rearg` applied.
8964 *
8965 * @private
8966 * @param {Array} data The destination metadata.
8967 * @param {Array} source The source metadata.
8968 * @returns {Array} Returns `data`.
8969 */
8970 function mergeData(data, source) {
8971 var bitmask = data[1],
8972 srcBitmask = source[1],
8973 newBitmask = bitmask | srcBitmask,
8974 isCommon = newBitmask < (BIND_FLAG | BIND_KEY_FLAG | ARY_FLAG);
8975
8976 var isCombo =
8977 ((srcBitmask == ARY_FLAG) && (bitmask == CURRY_FLAG)) ||
8978 ((srcBitmask == ARY_FLAG) && (bitmask == REARG_FLAG) && (data[7].length <= source[8])) ||
8979 ((srcBitmask == (ARY_FLAG | REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == CURRY_FLAG));
8980
8981 // Exit early if metadata can't be merged.
8982 if (!(isCommon || isCombo)) {
8983 return data;
8984 }
8985 // Use source `thisArg` if available.
8986 if (srcBitmask & BIND_FLAG) {
8987 data[2] = source[2];
8988 // Set when currying a bound function.
8989 newBitmask |= bitmask & BIND_FLAG ? 0 : CURRY_BOUND_FLAG;
8990 }
8991 // Compose partial arguments.
8992 var value = source[3];
8993 if (value) {
8994 var partials = data[3];
8995 data[3] = partials ? composeArgs(partials, value, source[4]) : copyArray(value);
8996 data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : copyArray(source[4]);
8997 }
8998 // Compose partial right arguments.
8999 value = source[5];
9000 if (value) {
9001 partials = data[5];
9002 data[5] = partials ? composeArgsRight(partials, value, source[6]) : copyArray(value);
9003 data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : copyArray(source[6]);
9004 }
9005 // Use source `argPos` if available.
9006 value = source[7];
9007 if (value) {
9008 data[7] = copyArray(value);
9009 }
9010 // Use source `ary` if it's smaller.
9011 if (srcBitmask & ARY_FLAG) {
9012 data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
9013 }
9014 // Use source `arity` if one is not provided.
9015 if (data[9] == null) {
9016 data[9] = source[9];
9017 }
9018 // Use source `func` and merge bitmasks.
9019 data[0] = source[0];
9020 data[1] = newBitmask;
9021
9022 return data;
9023 }
9024
9025 /**
9026 * Used by `_.defaultsDeep` to customize its `_.merge` use.
9027 *
9028 * @private
9029 * @param {*} objValue The destination value.
9030 * @param {*} srcValue The source value.
9031 * @param {string} key The key of the property to merge.
9032 * @param {Object} object The parent object of `objValue`.
9033 * @param {Object} source The parent object of `srcValue`.
9034 * @param {Object} [stack] Tracks traversed source values and their merged counterparts.
9035 * @returns {*} Returns the value to assign.
9036 */
9037 function mergeDefaults(objValue, srcValue, key, object, source, stack) {
9038 if (isObject(objValue) && isObject(srcValue)) {
9039 baseMerge(objValue, srcValue, undefined, mergeDefaults, stack.set(srcValue, objValue));
9040 }
9041 return objValue;
9042 }
9043
9044 /**
9045 * Gets the parent value at `path` of `object`.
9046 *
9047 * @private
9048 * @param {Object} object The object to query.
9049 * @param {Array} path The path to get the parent value of.
9050 * @returns {*} Returns the parent value.
9051 */
9052 function parent(object, path) {
9053 return path.length == 1 ? object : get(object, baseSlice(path, 0, -1));
9054 }
9055
9056 /**
9057 * Reorder `array` according to the specified indexes where the element at
9058 * the first index is assigned as the first element, the element at
9059 * the second index is assigned as the second element, and so on.
9060 *
9061 * @private
9062 * @param {Array} array The array to reorder.
9063 * @param {Array} indexes The arranged array indexes.
9064 * @returns {Array} Returns `array`.
9065 */
9066 function reorder(array, indexes) {
9067 var arrLength = array.length,
9068 length = nativeMin(indexes.length, arrLength),
9069 oldArray = copyArray(array);
9070
9071 while (length--) {
9072 var index = indexes[length];
9073 array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
9074 }
9075 return array;
9076 }
9077
9078 /**
9079 * Sets metadata for `func`.
9080 *
9081 * **Note:** If this function becomes hot, i.e. is invoked a lot in a short
9082 * period of time, it will trip its breaker and transition to an identity function
9083 * to avoid garbage collection pauses in V8. See [V8 issue 2070](https://code.google.com/p/v8/issues/detail?id=2070)
9084 * for more details.
9085 *
9086 * @private
9087 * @param {Function} func The function to associate metadata with.
9088 * @param {*} data The metadata.
9089 * @returns {Function} Returns `func`.
9090 */
9091 var setData = (function() {
9092 var count = 0,
9093 lastCalled = 0;
9094
9095 return function(key, value) {
9096 var stamp = now(),
9097 remaining = HOT_SPAN - (stamp - lastCalled);
9098
9099 lastCalled = stamp;
9100 if (remaining > 0) {
9101 if (++count >= HOT_COUNT) {
9102 return key;
9103 }
9104 } else {
9105 count = 0;
9106 }
9107 return baseSetData(key, value);
9108 };
9109 }());
9110
9111 /**
9112 * Converts `string` to a property path array.
9113 *
9114 * @private
9115 * @param {string} string The string to convert.
9116 * @returns {Array} Returns the property path array.
9117 */
9118 function stringToPath(string) {
9119 var result = [];
9120 toString(string).replace(rePropName, function(match, number, quote, string) {
9121 result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
9122 });
9123 return result;
9124 }
9125
9126 /**
9127 * Creates a clone of `wrapper`.
9128 *
9129 * @private
9130 * @param {Object} wrapper The wrapper to clone.
9131 * @returns {Object} Returns the cloned wrapper.
9132 */
9133 function wrapperClone(wrapper) {
9134 if (wrapper instanceof LazyWrapper) {
9135 return wrapper.clone();
9136 }
9137 var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
9138 result.__actions__ = copyArray(wrapper.__actions__);
9139 result.__index__ = wrapper.__index__;
9140 result.__values__ = wrapper.__values__;
9141 return result;
9142 }
9143
9144 /*------------------------------------------------------------------------*/
9145
9146 /**
9147 * Creates an array of elements split into groups the length of `size`.
9148 * If `array` can't be split evenly, the final chunk will be the remaining
9149 * elements.
9150 *
9151 * @static
9152 * @memberOf _
9153 * @category Array
9154 * @param {Array} array The array to process.
9155 * @param {number} [size=0] The length of each chunk.
9156 * @returns {Array} Returns the new array containing chunks.
9157 * @example
9158 *
9159 * _.chunk(['a', 'b', 'c', 'd'], 2);
9160 * // => [['a', 'b'], ['c', 'd']]
9161 *
9162 * _.chunk(['a', 'b', 'c', 'd'], 3);
9163 * // => [['a', 'b', 'c'], ['d']]
9164 */
9165 function chunk(array, size) {
9166 size = nativeMax(toInteger(size), 0);
9167
9168 var length = array ? array.length : 0;
9169 if (!length || size < 1) {
9170 return [];
9171 }
9172 var index = 0,
9173 resIndex = 0,
9174 result = Array(nativeCeil(length / size));
9175
9176 while (index < length) {
9177 result[resIndex++] = baseSlice(array, index, (index += size));
9178 }
9179 return result;
9180 }
9181
9182 /**
9183 * Creates an array with all falsey values removed. The values `false`, `null`,
9184 * `0`, `""`, `undefined`, and `NaN` are falsey.
9185 *
9186 * @static
9187 * @memberOf _
9188 * @category Array
9189 * @param {Array} array The array to compact.
9190 * @returns {Array} Returns the new array of filtered values.
9191 * @example
9192 *
9193 * _.compact([0, 1, false, 2, '', 3]);
9194 * // => [1, 2, 3]
9195 */
9196 function compact(array) {
9197 var index = -1,
9198 length = array ? array.length : 0,
9199 resIndex = 0,
9200 result = [];
9201
9202 while (++index < length) {
9203 var value = array[index];
9204 if (value) {
9205 result[resIndex++] = value;
9206 }
9207 }
9208 return result;
9209 }
9210
9211 /**
9212 * Creates a new array concatenating `array` with any additional arrays
9213 * and/or values.
9214 *
9215 * @static
9216 * @memberOf _
9217 * @category Array
9218 * @param {Array} array The array to concatenate.
9219 * @param {...*} [values] The values to concatenate.
9220 * @returns {Array} Returns the new concatenated array.
9221 * @example
9222 *
9223 * var array = [1];
9224 * var other = _.concat(array, 2, [3], [[4]]);
9225 *
9226 * console.log(other);
9227 * // => [1, 2, 3, [4]]
9228 *
9229 * console.log(array);
9230 * // => [1]
9231 */
9232 var concat = rest(function(array, values) {
9233 if (!isArray(array)) {
9234 array = array == null ? [] : [Object(array)];
9235 }
9236 values = baseFlatten(values, 1);
9237 return arrayConcat(array, values);
9238 });
9239
9240 /**
9241 * Creates an array of unique `array` values not included in the other
9242 * given arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
9243 * for equality comparisons. The order of result values is determined by the
9244 * order they occur in the first array.
9245 *
9246 * @static
9247 * @memberOf _
9248 * @category Array
9249 * @param {Array} array The array to inspect.
9250 * @param {...Array} [values] The values to exclude.
9251 * @returns {Array} Returns the new array of filtered values.
9252 * @example
9253 *
9254 * _.difference([3, 2, 1], [4, 2]);
9255 * // => [3, 1]
9256 */
9257 var difference = rest(function(array, values) {
9258 return isArrayLikeObject(array)
9259 ? baseDifference(array, baseFlatten(values, 1, true))
9260 : [];
9261 });
9262
9263 /**
9264 * This method is like `_.difference` except that it accepts `iteratee` which
9265 * is invoked for each element of `array` and `values` to generate the criterion
9266 * by which they're compared. Result values are chosen from the first array.
9267 * The iteratee is invoked with one argument: (value).
9268 *
9269 * @static
9270 * @memberOf _
9271 * @category Array
9272 * @param {Array} array The array to inspect.
9273 * @param {...Array} [values] The values to exclude.
9274 * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element.
9275 * @returns {Array} Returns the new array of filtered values.
9276 * @example
9277 *
9278 * _.differenceBy([3.1, 2.2, 1.3], [4.4, 2.5], Math.floor);
9279 * // => [3.1, 1.3]
9280 *
9281 * // The `_.property` iteratee shorthand.
9282 * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');
9283 * // => [{ 'x': 2 }]
9284 */
9285 var differenceBy = rest(function(array, values) {
9286 var iteratee = last(values);
9287 if (isArrayLikeObject(iteratee)) {
9288 iteratee = undefined;
9289 }
9290 return isArrayLikeObject(array)
9291 ? baseDifference(array, baseFlatten(values, 1, true), getIteratee(iteratee))
9292 : [];
9293 });
9294
9295 /**
9296 * This method is like `_.difference` except that it accepts `comparator`
9297 * which is invoked to compare elements of `array` to `values`. Result values
9298 * are chosen from the first array. The comparator is invoked with two arguments:
9299 * (arrVal, othVal).
9300 *
9301 * @static
9302 * @memberOf _
9303 * @category Array
9304 * @param {Array} array The array to inspect.
9305 * @param {...Array} [values] The values to exclude.
9306 * @param {Function} [comparator] The comparator invoked per element.
9307 * @returns {Array} Returns the new array of filtered values.
9308 * @example
9309 *
9310 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
9311 *
9312 * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);
9313 * // => [{ 'x': 2, 'y': 1 }]
9314 */
9315 var differenceWith = rest(function(array, values) {
9316 var comparator = last(values);
9317 if (isArrayLikeObject(comparator)) {
9318 comparator = undefined;
9319 }
9320 return isArrayLikeObject(array)
9321 ? baseDifference(array, baseFlatten(values, 1, true), undefined, comparator)
9322 : [];
9323 });
9324
9325 /**
9326 * Creates a slice of `array` with `n` elements dropped from the beginning.
9327 *
9328 * @static
9329 * @memberOf _
9330 * @category Array
9331 * @param {Array} array The array to query.
9332 * @param {number} [n=1] The number of elements to drop.
9333 * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
9334 * @returns {Array} Returns the slice of `array`.
9335 * @example
9336 *
9337 * _.drop([1, 2, 3]);
9338 * // => [2, 3]
9339 *
9340 * _.drop([1, 2, 3], 2);
9341 * // => [3]
9342 *
9343 * _.drop([1, 2, 3], 5);
9344 * // => []
9345 *
9346 * _.drop([1, 2, 3], 0);
9347 * // => [1, 2, 3]
9348 */
9349 function drop(array, n, guard) {
9350 var length = array ? array.length : 0;
9351 if (!length) {
9352 return [];
9353 }
9354 n = (guard || n === undefined) ? 1 : toInteger(n);
9355 return baseSlice(array, n < 0 ? 0 : n, length);
9356 }
9357
9358 /**
9359 * Creates a slice of `array` with `n` elements dropped from the end.
9360 *
9361 * @static
9362 * @memberOf _
9363 * @category Array
9364 * @param {Array} array The array to query.
9365 * @param {number} [n=1] The number of elements to drop.
9366 * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
9367 * @returns {Array} Returns the slice of `array`.
9368 * @example
9369 *
9370 * _.dropRight([1, 2, 3]);
9371 * // => [1, 2]
9372 *
9373 * _.dropRight([1, 2, 3], 2);
9374 * // => [1]
9375 *
9376 * _.dropRight([1, 2, 3], 5);
9377 * // => []
9378 *
9379 * _.dropRight([1, 2, 3], 0);
9380 * // => [1, 2, 3]
9381 */
9382 function dropRight(array, n, guard) {
9383 var length = array ? array.length : 0;
9384 if (!length) {
9385 return [];
9386 }
9387 n = (guard || n === undefined) ? 1 : toInteger(n);
9388 n = length - n;
9389 return baseSlice(array, 0, n < 0 ? 0 : n);
9390 }
9391
9392 /**
9393 * Creates a slice of `array` excluding elements dropped from the end.
9394 * Elements are dropped until `predicate` returns falsey. The predicate is
9395 * invoked with three arguments: (value, index, array).
9396 *
9397 * @static
9398 * @memberOf _
9399 * @category Array
9400 * @param {Array} array The array to query.
9401 * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
9402 * @returns {Array} Returns the slice of `array`.
9403 * @example
9404 *
9405 * var users = [
9406 * { 'user': 'barney', 'active': true },
9407 * { 'user': 'fred', 'active': false },
9408 * { 'user': 'pebbles', 'active': false }
9409 * ];
9410 *
9411 * _.dropRightWhile(users, function(o) { return !o.active; });
9412 * // => objects for ['barney']
9413 *
9414 * // The `_.matches` iteratee shorthand.
9415 * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false });
9416 * // => objects for ['barney', 'fred']
9417 *
9418 * // The `_.matchesProperty` iteratee shorthand.
9419 * _.dropRightWhile(users, ['active', false]);
9420 * // => objects for ['barney']
9421 *
9422 * // The `_.property` iteratee shorthand.
9423 * _.dropRightWhile(users, 'active');
9424 * // => objects for ['barney', 'fred', 'pebbles']
9425 */
9426 function dropRightWhile(array, predicate) {
9427 return (array && array.length)
9428 ? baseWhile(array, getIteratee(predicate, 3), true, true)
9429 : [];
9430 }
9431
9432 /**
9433 * Creates a slice of `array` excluding elements dropped from the beginning.
9434 * Elements are dropped until `predicate` returns falsey. The predicate is
9435 * invoked with three arguments: (value, index, array).
9436 *
9437 * @static
9438 * @memberOf _
9439 * @category Array
9440 * @param {Array} array The array to query.
9441 * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
9442 * @returns {Array} Returns the slice of `array`.
9443 * @example
9444 *
9445 * var users = [
9446 * { 'user': 'barney', 'active': false },
9447 * { 'user': 'fred', 'active': false },
9448 * { 'user': 'pebbles', 'active': true }
9449 * ];
9450 *
9451 * _.dropWhile(users, function(o) { return !o.active; });
9452 * // => objects for ['pebbles']
9453 *
9454 * // The `_.matches` iteratee shorthand.
9455 * _.dropWhile(users, { 'user': 'barney', 'active': false });
9456 * // => objects for ['fred', 'pebbles']
9457 *
9458 * // The `_.matchesProperty` iteratee shorthand.
9459 * _.dropWhile(users, ['active', false]);
9460 * // => objects for ['pebbles']
9461 *
9462 * // The `_.property` iteratee shorthand.
9463 * _.dropWhile(users, 'active');
9464 * // => objects for ['barney', 'fred', 'pebbles']
9465 */
9466 function dropWhile(array, predicate) {
9467 return (array && array.length)
9468 ? baseWhile(array, getIteratee(predicate, 3), true)
9469 : [];
9470 }
9471
9472 /**
9473 * Fills elements of `array` with `value` from `start` up to, but not
9474 * including, `end`.
9475 *
9476 * **Note:** This method mutates `array`.
9477 *
9478 * @static
9479 * @memberOf _
9480 * @category Array
9481 * @param {Array} array The array to fill.
9482 * @param {*} value The value to fill `array` with.
9483 * @param {number} [start=0] The start position.
9484 * @param {number} [end=array.length] The end position.
9485 * @returns {Array} Returns `array`.
9486 * @example
9487 *
9488 * var array = [1, 2, 3];
9489 *
9490 * _.fill(array, 'a');
9491 * console.log(array);
9492 * // => ['a', 'a', 'a']
9493 *
9494 * _.fill(Array(3), 2);
9495 * // => [2, 2, 2]
9496 *
9497 * _.fill([4, 6, 8, 10], '*', 1, 3);
9498 * // => [4, '*', '*', 10]
9499 */
9500 function fill(array, value, start, end) {
9501 var length = array ? array.length : 0;
9502 if (!length) {
9503 return [];
9504 }
9505 if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {
9506 start = 0;
9507 end = length;
9508 }
9509 return baseFill(array, value, start, end);
9510 }
9511
9512 /**
9513 * This method is like `_.find` except that it returns the index of the first
9514 * element `predicate` returns truthy for instead of the element itself.
9515 *
9516 * @static
9517 * @memberOf _
9518 * @category Array
9519 * @param {Array} array The array to search.
9520 * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
9521 * @returns {number} Returns the index of the found element, else `-1`.
9522 * @example
9523 *
9524 * var users = [
9525 * { 'user': 'barney', 'active': false },
9526 * { 'user': 'fred', 'active': false },
9527 * { 'user': 'pebbles', 'active': true }
9528 * ];
9529 *
9530 * _.findIndex(users, function(o) { return o.user == 'barney'; });
9531 * // => 0
9532 *
9533 * // The `_.matches` iteratee shorthand.
9534 * _.findIndex(users, { 'user': 'fred', 'active': false });
9535 * // => 1
9536 *
9537 * // The `_.matchesProperty` iteratee shorthand.
9538 * _.findIndex(users, ['active', false]);
9539 * // => 0
9540 *
9541 * // The `_.property` iteratee shorthand.
9542 * _.findIndex(users, 'active');
9543 * // => 2
9544 */
9545 function findIndex(array, predicate) {
9546 return (array && array.length)
9547 ? baseFindIndex(array, getIteratee(predicate, 3))
9548 : -1;
9549 }
9550
9551 /**
9552 * This method is like `_.findIndex` except that it iterates over elements
9553 * of `collection` from right to left.
9554 *
9555 * @static
9556 * @memberOf _
9557 * @category Array
9558 * @param {Array} array The array to search.
9559 * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
9560 * @returns {number} Returns the index of the found element, else `-1`.
9561 * @example
9562 *
9563 * var users = [
9564 * { 'user': 'barney', 'active': true },
9565 * { 'user': 'fred', 'active': false },
9566 * { 'user': 'pebbles', 'active': false }
9567 * ];
9568 *
9569 * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });
9570 * // => 2
9571 *
9572 * // The `_.matches` iteratee shorthand.
9573 * _.findLastIndex(users, { 'user': 'barney', 'active': true });
9574 * // => 0
9575 *
9576 * // The `_.matchesProperty` iteratee shorthand.
9577 * _.findLastIndex(users, ['active', false]);
9578 * // => 2
9579 *
9580 * // The `_.property` iteratee shorthand.
9581 * _.findLastIndex(users, 'active');
9582 * // => 0
9583 */
9584 function findLastIndex(array, predicate) {
9585 return (array && array.length)
9586 ? baseFindIndex(array, getIteratee(predicate, 3), true)
9587 : -1;
9588 }
9589
9590 /**
9591 * Flattens `array` a single level deep.
9592 *
9593 * @static
9594 * @memberOf _
9595 * @category Array
9596 * @param {Array} array The array to flatten.
9597 * @returns {Array} Returns the new flattened array.
9598 * @example
9599 *
9600 * _.flatten([1, [2, [3, [4]], 5]]);
9601 * // => [1, 2, [3, [4]], 5]
9602 */
9603 function flatten(array) {
9604 var length = array ? array.length : 0;
9605 return length ? baseFlatten(array, 1) : [];
9606 }
9607
9608 /**
9609 * Recursively flattens `array`.
9610 *
9611 * @static
9612 * @memberOf _
9613 * @category Array
9614 * @param {Array} array The array to flatten.
9615 * @returns {Array} Returns the new flattened array.
9616 * @example
9617 *
9618 * _.flattenDeep([1, [2, [3, [4]], 5]]);
9619 * // => [1, 2, 3, 4, 5]
9620 */
9621 function flattenDeep(array) {
9622 var length = array ? array.length : 0;
9623 return length ? baseFlatten(array, INFINITY) : [];
9624 }
9625
9626 /**
9627 * Recursively flatten `array` up to `depth` times.
9628 *
9629 * @static
9630 * @memberOf _
9631 * @category Array
9632 * @param {Array} array The array to flatten.
9633 * @param {number} [depth=1] The maximum recursion depth.
9634 * @returns {Array} Returns the new flattened array.
9635 * @example
9636 *
9637 * var array = [1, [2, [3, [4]], 5]];
9638 *
9639 * _.flattenDepth(array, 1);
9640 * // => [1, 2, [3, [4]], 5]
9641 *
9642 * _.flattenDepth(array, 2);
9643 * // => [1, 2, 3, [4], 5]
9644 */
9645 function flattenDepth(array, depth) {
9646 var length = array ? array.length : 0;
9647 if (!length) {
9648 return [];
9649 }
9650 depth = depth === undefined ? 1 : toInteger(depth);
9651 return baseFlatten(array, depth);
9652 }
9653
9654 /**
9655 * The inverse of `_.toPairs`; this method returns an object composed
9656 * from key-value `pairs`.
9657 *
9658 * @static
9659 * @memberOf _
9660 * @category Array
9661 * @param {Array} pairs The key-value pairs.
9662 * @returns {Object} Returns the new object.
9663 * @example
9664 *
9665 * _.fromPairs([['fred', 30], ['barney', 40]]);
9666 * // => { 'fred': 30, 'barney': 40 }
9667 */
9668 function fromPairs(pairs) {
9669 var index = -1,
9670 length = pairs ? pairs.length : 0,
9671 result = {};
9672
9673 while (++index < length) {
9674 var pair = pairs[index];
9675 result[pair[0]] = pair[1];
9676 }
9677 return result;
9678 }
9679
9680 /**
9681 * Gets the first element of `array`.
9682 *
9683 * @static
9684 * @memberOf _
9685 * @alias first
9686 * @category Array
9687 * @param {Array} array The array to query.
9688 * @returns {*} Returns the first element of `array`.
9689 * @example
9690 *
9691 * _.head([1, 2, 3]);
9692 * // => 1
9693 *
9694 * _.head([]);
9695 * // => undefined
9696 */
9697 function head(array) {
9698 return array ? array[0] : undefined;
9699 }
9700
9701 /**
9702 * Gets the index at which the first occurrence of `value` is found in `array`
9703 * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
9704 * for equality comparisons. If `fromIndex` is negative, it's used as the offset
9705 * from the end of `array`.
9706 *
9707 * @static
9708 * @memberOf _
9709 * @category Array
9710 * @param {Array} array The array to search.
9711 * @param {*} value The value to search for.
9712 * @param {number} [fromIndex=0] The index to search from.
9713 * @returns {number} Returns the index of the matched value, else `-1`.
9714 * @example
9715 *
9716 * _.indexOf([1, 2, 1, 2], 2);
9717 * // => 1
9718 *
9719 * // Search from the `fromIndex`.
9720 * _.indexOf([1, 2, 1, 2], 2, 2);
9721 * // => 3
9722 */
9723 function indexOf(array, value, fromIndex) {
9724 var length = array ? array.length : 0;
9725 if (!length) {
9726 return -1;
9727 }
9728 fromIndex = toInteger(fromIndex);
9729 if (fromIndex < 0) {
9730 fromIndex = nativeMax(length + fromIndex, 0);
9731 }
9732 return baseIndexOf(array, value, fromIndex);
9733 }
9734
9735 /**
9736 * Gets all but the last element of `array`.
9737 *
9738 * @static
9739 * @memberOf _
9740 * @category Array
9741 * @param {Array} array The array to query.
9742 * @returns {Array} Returns the slice of `array`.
9743 * @example
9744 *
9745 * _.initial([1, 2, 3]);
9746 * // => [1, 2]
9747 */
9748 function initial(array) {
9749 return dropRight(array, 1);
9750 }
9751
9752 /**
9753 * Creates an array of unique values that are included in all given arrays
9754 * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
9755 * for equality comparisons. The order of result values is determined by the
9756 * order they occur in the first array.
9757 *
9758 * @static
9759 * @memberOf _
9760 * @category Array
9761 * @param {...Array} [arrays] The arrays to inspect.
9762 * @returns {Array} Returns the new array of intersecting values.
9763 * @example
9764 *
9765 * _.intersection([2, 1], [4, 2], [1, 2]);
9766 * // => [2]
9767 */
9768 var intersection = rest(function(arrays) {
9769 var mapped = arrayMap(arrays, baseCastArrayLikeObject);
9770 return (mapped.length && mapped[0] === arrays[0])
9771 ? baseIntersection(mapped)
9772 : [];
9773 });
9774
9775 /**
9776 * This method is like `_.intersection` except that it accepts `iteratee`
9777 * which is invoked for each element of each `arrays` to generate the criterion
9778 * by which they're compared. Result values are chosen from the first array.
9779 * The iteratee is invoked with one argument: (value).
9780 *
9781 * @static
9782 * @memberOf _
9783 * @category Array
9784 * @param {...Array} [arrays] The arrays to inspect.
9785 * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element.
9786 * @returns {Array} Returns the new array of intersecting values.
9787 * @example
9788 *
9789 * _.intersectionBy([2.1, 1.2], [4.3, 2.4], Math.floor);
9790 * // => [2.1]
9791 *
9792 * // The `_.property` iteratee shorthand.
9793 * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
9794 * // => [{ 'x': 1 }]
9795 */
9796 var intersectionBy = rest(function(arrays) {
9797 var iteratee = last(arrays),
9798 mapped = arrayMap(arrays, baseCastArrayLikeObject);
9799
9800 if (iteratee === last(mapped)) {
9801 iteratee = undefined;
9802 } else {
9803 mapped.pop();
9804 }
9805 return (mapped.length && mapped[0] === arrays[0])
9806 ? baseIntersection(mapped, getIteratee(iteratee))
9807 : [];
9808 });
9809
9810 /**
9811 * This method is like `_.intersection` except that it accepts `comparator`
9812 * which is invoked to compare elements of `arrays`. Result values are chosen
9813 * from the first array. The comparator is invoked with two arguments:
9814 * (arrVal, othVal).
9815 *
9816 * @static
9817 * @memberOf _
9818 * @category Array
9819 * @param {...Array} [arrays] The arrays to inspect.
9820 * @param {Function} [comparator] The comparator invoked per element.
9821 * @returns {Array} Returns the new array of intersecting values.
9822 * @example
9823 *
9824 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
9825 * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
9826 *
9827 * _.intersectionWith(objects, others, _.isEqual);
9828 * // => [{ 'x': 1, 'y': 2 }]
9829 */
9830 var intersectionWith = rest(function(arrays) {
9831 var comparator = last(arrays),
9832 mapped = arrayMap(arrays, baseCastArrayLikeObject);
9833
9834 if (comparator === last(mapped)) {
9835 comparator = undefined;
9836 } else {
9837 mapped.pop();
9838 }
9839 return (mapped.length && mapped[0] === arrays[0])
9840 ? baseIntersection(mapped, undefined, comparator)
9841 : [];
9842 });
9843
9844 /**
9845 * Converts all elements in `array` into a string separated by `separator`.
9846 *
9847 * @static
9848 * @memberOf _
9849 * @category Array
9850 * @param {Array} array The array to convert.
9851 * @param {string} [separator=','] The element separator.
9852 * @returns {string} Returns the joined string.
9853 * @example
9854 *
9855 * _.join(['a', 'b', 'c'], '~');
9856 * // => 'a~b~c'
9857 */
9858 function join(array, separator) {
9859 return array ? nativeJoin.call(array, separator) : '';
9860 }
9861
9862 /**
9863 * Gets the last element of `array`.
9864 *
9865 * @static
9866 * @memberOf _
9867 * @category Array
9868 * @param {Array} array The array to query.
9869 * @returns {*} Returns the last element of `array`.
9870 * @example
9871 *
9872 * _.last([1, 2, 3]);
9873 * // => 3
9874 */
9875 function last(array) {
9876 var length = array ? array.length : 0;
9877 return length ? array[length - 1] : undefined;
9878 }
9879
9880 /**
9881 * This method is like `_.indexOf` except that it iterates over elements of
9882 * `array` from right to left.
9883 *
9884 * @static
9885 * @memberOf _
9886 * @category Array
9887 * @param {Array} array The array to search.
9888 * @param {*} value The value to search for.
9889 * @param {number} [fromIndex=array.length-1] The index to search from.
9890 * @returns {number} Returns the index of the matched value, else `-1`.
9891 * @example
9892 *
9893 * _.lastIndexOf([1, 2, 1, 2], 2);
9894 * // => 3
9895 *
9896 * // Search from the `fromIndex`.
9897 * _.lastIndexOf([1, 2, 1, 2], 2, 2);
9898 * // => 1
9899 */
9900 function lastIndexOf(array, value, fromIndex) {
9901 var length = array ? array.length : 0;
9902 if (!length) {
9903 return -1;
9904 }
9905 var index = length;
9906 if (fromIndex !== undefined) {
9907 index = toInteger(fromIndex);
9908 index = (index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1)) + 1;
9909 }
9910 if (value !== value) {
9911 return indexOfNaN(array, index, true);
9912 }
9913 while (index--) {
9914 if (array[index] === value) {
9915 return index;
9916 }
9917 }
9918 return -1;
9919 }
9920
9921 /**
9922 * Removes all given values from `array` using
9923 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
9924 * for equality comparisons.
9925 *
9926 * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove`
9927 * to remove elements from an array by predicate.
9928 *
9929 * @static
9930 * @memberOf _
9931 * @category Array
9932 * @param {Array} array The array to modify.
9933 * @param {...*} [values] The values to remove.
9934 * @returns {Array} Returns `array`.
9935 * @example
9936 *
9937 * var array = [1, 2, 3, 1, 2, 3];
9938 *
9939 * _.pull(array, 2, 3);
9940 * console.log(array);
9941 * // => [1, 1]
9942 */
9943 var pull = rest(pullAll);
9944
9945 /**
9946 * This method is like `_.pull` except that it accepts an array of values to remove.
9947 *
9948 * **Note:** Unlike `_.difference`, this method mutates `array`.
9949 *
9950 * @static
9951 * @memberOf _
9952 * @category Array
9953 * @param {Array} array The array to modify.
9954 * @param {Array} values The values to remove.
9955 * @returns {Array} Returns `array`.
9956 * @example
9957 *
9958 * var array = [1, 2, 3, 1, 2, 3];
9959 *
9960 * _.pullAll(array, [2, 3]);
9961 * console.log(array);
9962 * // => [1, 1]
9963 */
9964 function pullAll(array, values) {
9965 return (array && array.length && values && values.length)
9966 ? basePullAll(array, values)
9967 : array;
9968 }
9969
9970 /**
9971 * This method is like `_.pullAll` except that it accepts `iteratee` which is
9972 * invoked for each element of `array` and `values` to generate the criterion
9973 * by which they're compared. The iteratee is invoked with one argument: (value).
9974 *
9975 * **Note:** Unlike `_.differenceBy`, this method mutates `array`.
9976 *
9977 * @static
9978 * @memberOf _
9979 * @category Array
9980 * @param {Array} array The array to modify.
9981 * @param {Array} values The values to remove.
9982 * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element.
9983 * @returns {Array} Returns `array`.
9984 * @example
9985 *
9986 * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];
9987 *
9988 * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');
9989 * console.log(array);
9990 * // => [{ 'x': 2 }]
9991 */
9992 function pullAllBy(array, values, iteratee) {
9993 return (array && array.length && values && values.length)
9994 ? basePullAll(array, values, getIteratee(iteratee))
9995 : array;
9996 }
9997
9998 /**
9999 * This method is like `_.pullAll` except that it accepts `comparator` which
10000 * is invoked to compare elements of `array` to `values`. The comparator is
10001 * invoked with two arguments: (arrVal, othVal).
10002 *
10003 * **Note:** Unlike `_.differenceWith`, this method mutates `array`.
10004 *
10005 * @static
10006 * @memberOf _
10007 * @category Array
10008 * @param {Array} array The array to modify.
10009 * @param {Array} values The values to remove.
10010 * @param {Function} [comparator] The comparator invoked per element.
10011 * @returns {Array} Returns `array`.
10012 * @example
10013 *
10014 * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }];
10015 *
10016 * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual);
10017 * console.log(array);
10018 * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]
10019 */
10020 function pullAllWith(array, values, comparator) {
10021 return (array && array.length && values && values.length)
10022 ? basePullAll(array, values, undefined, comparator)
10023 : array;
10024 }
10025
10026 /**
10027 * Removes elements from `array` corresponding to `indexes` and returns an
10028 * array of removed elements.
10029 *
10030 * **Note:** Unlike `_.at`, this method mutates `array`.
10031 *
10032 * @static
10033 * @memberOf _
10034 * @category Array
10035 * @param {Array} array The array to modify.
10036 * @param {...(number|number[])} [indexes] The indexes of elements to remove,
10037 * specified individually or in arrays.
10038 * @returns {Array} Returns the new array of removed elements.
10039 * @example
10040 *
10041 * var array = [5, 10, 15, 20];
10042 * var evens = _.pullAt(array, 1, 3);
10043 *
10044 * console.log(array);
10045 * // => [5, 15]
10046 *
10047 * console.log(evens);
10048 * // => [10, 20]
10049 */
10050 var pullAt = rest(function(array, indexes) {
10051 indexes = arrayMap(baseFlatten(indexes, 1), String);
10052
10053 var result = baseAt(array, indexes);
10054 basePullAt(array, indexes.sort(compareAscending));
10055 return result;
10056 });
10057
10058 /**
10059 * Removes all elements from `array` that `predicate` returns truthy for
10060 * and returns an array of the removed elements. The predicate is invoked
10061 * with three arguments: (value, index, array).
10062 *
10063 * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`
10064 * to pull elements from an array by value.
10065 *
10066 * @static
10067 * @memberOf _
10068 * @category Array
10069 * @param {Array} array The array to modify.
10070 * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
10071 * @returns {Array} Returns the new array of removed elements.
10072 * @example
10073 *
10074 * var array = [1, 2, 3, 4];
10075 * var evens = _.remove(array, function(n) {
10076 * return n % 2 == 0;
10077 * });
10078 *
10079 * console.log(array);
10080 * // => [1, 3]
10081 *
10082 * console.log(evens);
10083 * // => [2, 4]
10084 */
10085 function remove(array, predicate) {
10086 var result = [];
10087 if (!(array && array.length)) {
10088 return result;
10089 }
10090 var index = -1,
10091 indexes = [],
10092 length = array.length;
10093
10094 predicate = getIteratee(predicate, 3);
10095 while (++index < length) {
10096 var value = array[index];
10097 if (predicate(value, index, array)) {
10098 result.push(value);
10099 indexes.push(index);
10100 }
10101 }
10102 basePullAt(array, indexes);
10103 return result;
10104 }
10105
10106 /**
10107 * Reverses `array` so that the first element becomes the last, the second
10108 * element becomes the second to last, and so on.
10109 *
10110 * **Note:** This method mutates `array` and is based on
10111 * [`Array#reverse`](https://mdn.io/Array/reverse).
10112 *
10113 * @static
10114 * @memberOf _
10115 * @category Array
10116 * @returns {Array} Returns `array`.
10117 * @example
10118 *
10119 * var array = [1, 2, 3];
10120 *
10121 * _.reverse(array);
10122 * // => [3, 2, 1]
10123 *
10124 * console.log(array);
10125 * // => [3, 2, 1]
10126 */
10127 function reverse(array) {
10128 return array ? nativeReverse.call(array) : array;
10129 }
10130
10131 /**
10132 * Creates a slice of `array` from `start` up to, but not including, `end`.
10133 *
10134 * **Note:** This method is used instead of [`Array#slice`](https://mdn.io/Array/slice)
10135 * to ensure dense arrays are returned.
10136 *
10137 * @static
10138 * @memberOf _
10139 * @category Array
10140 * @param {Array} array The array to slice.
10141 * @param {number} [start=0] The start position.
10142 * @param {number} [end=array.length] The end position.
10143 * @returns {Array} Returns the slice of `array`.
10144 */
10145 function slice(array, start, end) {
10146 var length = array ? array.length : 0;
10147 if (!length) {
10148 return [];
10149 }
10150 if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {
10151 start = 0;
10152 end = length;
10153 }
10154 else {
10155 start = start == null ? 0 : toInteger(start);
10156 end = end === undefined ? length : toInteger(end);
10157 }
10158 return baseSlice(array, start, end);
10159 }
10160
10161 /**
10162 * Uses a binary search to determine the lowest index at which `value` should
10163 * be inserted into `array` in order to maintain its sort order.
10164 *
10165 * @static
10166 * @memberOf _
10167 * @category Array
10168 * @param {Array} array The sorted array to inspect.
10169 * @param {*} value The value to evaluate.
10170 * @returns {number} Returns the index at which `value` should be inserted into `array`.
10171 * @example
10172 *
10173 * _.sortedIndex([30, 50], 40);
10174 * // => 1
10175 *
10176 * _.sortedIndex([4, 5], 4);
10177 * // => 0
10178 */
10179 function sortedIndex(array, value) {
10180 return baseSortedIndex(array, value);
10181 }
10182
10183 /**
10184 * This method is like `_.sortedIndex` except that it accepts `iteratee`
10185 * which is invoked for `value` and each element of `array` to compute their
10186 * sort ranking. The iteratee is invoked with one argument: (value).
10187 *
10188 * @static
10189 * @memberOf _
10190 * @category Array
10191 * @param {Array} array The sorted array to inspect.
10192 * @param {*} value The value to evaluate.
10193 * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element.
10194 * @returns {number} Returns the index at which `value` should be inserted into `array`.
10195 * @example
10196 *
10197 * var dict = { 'thirty': 30, 'forty': 40, 'fifty': 50 };
10198 *
10199 * _.sortedIndexBy(['thirty', 'fifty'], 'forty', _.propertyOf(dict));
10200 * // => 1
10201 *
10202 * // The `_.property` iteratee shorthand.
10203 * _.sortedIndexBy([{ 'x': 4 }, { 'x': 5 }], { 'x': 4 }, 'x');
10204 * // => 0
10205 */
10206 function sortedIndexBy(array, value, iteratee) {
10207 return baseSortedIndexBy(array, value, getIteratee(iteratee));
10208 }
10209
10210 /**
10211 * This method is like `_.indexOf` except that it performs a binary
10212 * search on a sorted `array`.
10213 *
10214 * @static
10215 * @memberOf _
10216 * @category Array
10217 * @param {Array} array The array to search.
10218 * @param {*} value The value to search for.
10219 * @returns {number} Returns the index of the matched value, else `-1`.
10220 * @example
10221 *
10222 * _.sortedIndexOf([1, 1, 2, 2], 2);
10223 * // => 2
10224 */
10225 function sortedIndexOf(array, value) {
10226 var length = array ? array.length : 0;
10227 if (length) {
10228 var index = baseSortedIndex(array, value);
10229 if (index < length && eq(array[index], value)) {
10230 return index;
10231 }
10232 }
10233 return -1;
10234 }
10235
10236 /**
10237 * This method is like `_.sortedIndex` except that it returns the highest
10238 * index at which `value` should be inserted into `array` in order to
10239 * maintain its sort order.
10240 *
10241 * @static
10242 * @memberOf _
10243 * @category Array
10244 * @param {Array} array The sorted array to inspect.
10245 * @param {*} value The value to evaluate.
10246 * @returns {number} Returns the index at which `value` should be inserted into `array`.
10247 * @example
10248 *
10249 * _.sortedLastIndex([4, 5], 4);
10250 * // => 1
10251 */
10252 function sortedLastIndex(array, value) {
10253 return baseSortedIndex(array, value, true);
10254 }
10255
10256 /**
10257 * This method is like `_.sortedLastIndex` except that it accepts `iteratee`
10258 * which is invoked for `value` and each element of `array` to compute their
10259 * sort ranking. The iteratee is invoked with one argument: (value).
10260 *
10261 * @static
10262 * @memberOf _
10263 * @category Array
10264 * @param {Array} array The sorted array to inspect.
10265 * @param {*} value The value to evaluate.
10266 * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element.
10267 * @returns {number} Returns the index at which `value` should be inserted into `array`.
10268 * @example
10269 *
10270 * // The `_.property` iteratee shorthand.
10271 * _.sortedLastIndexBy([{ 'x': 4 }, { 'x': 5 }], { 'x': 4 }, 'x');
10272 * // => 1
10273 */
10274 function sortedLastIndexBy(array, value, iteratee) {
10275 return baseSortedIndexBy(array, value, getIteratee(iteratee), true);
10276 }
10277
10278 /**
10279 * This method is like `_.lastIndexOf` except that it performs a binary
10280 * search on a sorted `array`.
10281 *
10282 * @static
10283 * @memberOf _
10284 * @category Array
10285 * @param {Array} array The array to search.
10286 * @param {*} value The value to search for.
10287 * @returns {number} Returns the index of the matched value, else `-1`.
10288 * @example
10289 *
10290 * _.sortedLastIndexOf([1, 1, 2, 2], 2);
10291 * // => 3
10292 */
10293 function sortedLastIndexOf(array, value) {
10294 var length = array ? array.length : 0;
10295 if (length) {
10296 var index = baseSortedIndex(array, value, true) - 1;
10297 if (eq(array[index], value)) {
10298 return index;
10299 }
10300 }
10301 return -1;
10302 }
10303
10304 /**
10305 * This method is like `_.uniq` except that it's designed and optimized
10306 * for sorted arrays.
10307 *
10308 * @static
10309 * @memberOf _
10310 * @category Array
10311 * @param {Array} array The array to inspect.
10312 * @returns {Array} Returns the new duplicate free array.
10313 * @example
10314 *
10315 * _.sortedUniq([1, 1, 2]);
10316 * // => [1, 2]
10317 */
10318 function sortedUniq(array) {
10319 return (array && array.length)
10320 ? baseSortedUniq(array)
10321 : [];
10322 }
10323
10324 /**
10325 * This method is like `_.uniqBy` except that it's designed and optimized
10326 * for sorted arrays.
10327 *
10328 * @static
10329 * @memberOf _
10330 * @category Array
10331 * @param {Array} array The array to inspect.
10332 * @param {Function} [iteratee] The iteratee invoked per element.
10333 * @returns {Array} Returns the new duplicate free array.
10334 * @example
10335 *
10336 * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);
10337 * // => [1.1, 2.3]
10338 */
10339 function sortedUniqBy(array, iteratee) {
10340 return (array && array.length)
10341 ? baseSortedUniqBy(array, getIteratee(iteratee))
10342 : [];
10343 }
10344
10345 /**
10346 * Gets all but the first element of `array`.
10347 *
10348 * @static
10349 * @memberOf _
10350 * @category Array
10351 * @param {Array} array The array to query.
10352 * @returns {Array} Returns the slice of `array`.
10353 * @example
10354 *
10355 * _.tail([1, 2, 3]);
10356 * // => [2, 3]
10357 */
10358 function tail(array) {
10359 return drop(array, 1);
10360 }
10361
10362 /**
10363 * Creates a slice of `array` with `n` elements taken from the beginning.
10364 *
10365 * @static
10366 * @memberOf _
10367 * @category Array
10368 * @param {Array} array The array to query.
10369 * @param {number} [n=1] The number of elements to take.
10370 * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
10371 * @returns {Array} Returns the slice of `array`.
10372 * @example
10373 *
10374 * _.take([1, 2, 3]);
10375 * // => [1]
10376 *
10377 * _.take([1, 2, 3], 2);
10378 * // => [1, 2]
10379 *
10380 * _.take([1, 2, 3], 5);
10381 * // => [1, 2, 3]
10382 *
10383 * _.take([1, 2, 3], 0);
10384 * // => []
10385 */
10386 function take(array, n, guard) {
10387 if (!(array && array.length)) {
10388 return [];
10389 }
10390 n = (guard || n === undefined) ? 1 : toInteger(n);
10391 return baseSlice(array, 0, n < 0 ? 0 : n);
10392 }
10393
10394 /**
10395 * Creates a slice of `array` with `n` elements taken from the end.
10396 *
10397 * @static
10398 * @memberOf _
10399 * @category Array
10400 * @param {Array} array The array to query.
10401 * @param {number} [n=1] The number of elements to take.
10402 * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
10403 * @returns {Array} Returns the slice of `array`.
10404 * @example
10405 *
10406 * _.takeRight([1, 2, 3]);
10407 * // => [3]
10408 *
10409 * _.takeRight([1, 2, 3], 2);
10410 * // => [2, 3]
10411 *
10412 * _.takeRight([1, 2, 3], 5);
10413 * // => [1, 2, 3]
10414 *
10415 * _.takeRight([1, 2, 3], 0);
10416 * // => []
10417 */
10418 function takeRight(array, n, guard) {
10419 var length = array ? array.length : 0;
10420 if (!length) {
10421 return [];
10422 }
10423 n = (guard || n === undefined) ? 1 : toInteger(n);
10424 n = length - n;
10425 return baseSlice(array, n < 0 ? 0 : n, length);
10426 }
10427
10428 /**
10429 * Creates a slice of `array` with elements taken from the end. Elements are
10430 * taken until `predicate` returns falsey. The predicate is invoked with three
10431 * arguments: (value, index, array).
10432 *
10433 * @static
10434 * @memberOf _
10435 * @category Array
10436 * @param {Array} array The array to query.
10437 * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
10438 * @returns {Array} Returns the slice of `array`.
10439 * @example
10440 *
10441 * var users = [
10442 * { 'user': 'barney', 'active': true },
10443 * { 'user': 'fred', 'active': false },
10444 * { 'user': 'pebbles', 'active': false }
10445 * ];
10446 *
10447 * _.takeRightWhile(users, function(o) { return !o.active; });
10448 * // => objects for ['fred', 'pebbles']
10449 *
10450 * // The `_.matches` iteratee shorthand.
10451 * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false });
10452 * // => objects for ['pebbles']
10453 *
10454 * // The `_.matchesProperty` iteratee shorthand.
10455 * _.takeRightWhile(users, ['active', false]);
10456 * // => objects for ['fred', 'pebbles']
10457 *
10458 * // The `_.property` iteratee shorthand.
10459 * _.takeRightWhile(users, 'active');
10460 * // => []
10461 */
10462 function takeRightWhile(array, predicate) {
10463 return (array && array.length)
10464 ? baseWhile(array, getIteratee(predicate, 3), false, true)
10465 : [];
10466 }
10467
10468 /**
10469 * Creates a slice of `array` with elements taken from the beginning. Elements
10470 * are taken until `predicate` returns falsey. The predicate is invoked with
10471 * three arguments: (value, index, array).
10472 *
10473 * @static
10474 * @memberOf _
10475 * @category Array
10476 * @param {Array} array The array to query.
10477 * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
10478 * @returns {Array} Returns the slice of `array`.
10479 * @example
10480 *
10481 * var users = [
10482 * { 'user': 'barney', 'active': false },
10483 * { 'user': 'fred', 'active': false},
10484 * { 'user': 'pebbles', 'active': true }
10485 * ];
10486 *
10487 * _.takeWhile(users, function(o) { return !o.active; });
10488 * // => objects for ['barney', 'fred']
10489 *
10490 * // The `_.matches` iteratee shorthand.
10491 * _.takeWhile(users, { 'user': 'barney', 'active': false });
10492 * // => objects for ['barney']
10493 *
10494 * // The `_.matchesProperty` iteratee shorthand.
10495 * _.takeWhile(users, ['active', false]);
10496 * // => objects for ['barney', 'fred']
10497 *
10498 * // The `_.property` iteratee shorthand.
10499 * _.takeWhile(users, 'active');
10500 * // => []
10501 */
10502 function takeWhile(array, predicate) {
10503 return (array && array.length)
10504 ? baseWhile(array, getIteratee(predicate, 3))
10505 : [];
10506 }
10507
10508 /**
10509 * Creates an array of unique values, in order, from all given arrays using
10510 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
10511 * for equality comparisons.
10512 *
10513 * @static
10514 * @memberOf _
10515 * @category Array
10516 * @param {...Array} [arrays] The arrays to inspect.
10517 * @returns {Array} Returns the new array of combined values.
10518 * @example
10519 *
10520 * _.union([2, 1], [4, 2], [1, 2]);
10521 * // => [2, 1, 4]
10522 */
10523 var union = rest(function(arrays) {
10524 return baseUniq(baseFlatten(arrays, 1, true));
10525 });
10526
10527 /**
10528 * This method is like `_.union` except that it accepts `iteratee` which is
10529 * invoked for each element of each `arrays` to generate the criterion by which
10530 * uniqueness is computed. The iteratee is invoked with one argument: (value).
10531 *
10532 * @static
10533 * @memberOf _
10534 * @category Array
10535 * @param {...Array} [arrays] The arrays to inspect.
10536 * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element.
10537 * @returns {Array} Returns the new array of combined values.
10538 * @example
10539 *
10540 * _.unionBy([2.1, 1.2], [4.3, 2.4], Math.floor);
10541 * // => [2.1, 1.2, 4.3]
10542 *
10543 * // The `_.property` iteratee shorthand.
10544 * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
10545 * // => [{ 'x': 1 }, { 'x': 2 }]
10546 */
10547 var unionBy = rest(function(arrays) {
10548 var iteratee = last(arrays);
10549 if (isArrayLikeObject(iteratee)) {
10550 iteratee = undefined;
10551 }
10552 return baseUniq(baseFlatten(arrays, 1, true), getIteratee(iteratee));
10553 });
10554
10555 /**
10556 * This method is like `_.union` except that it accepts `comparator` which
10557 * is invoked to compare elements of `arrays`. The comparator is invoked
10558 * with two arguments: (arrVal, othVal).
10559 *
10560 * @static
10561 * @memberOf _
10562 * @category Array
10563 * @param {...Array} [arrays] The arrays to inspect.
10564 * @param {Function} [comparator] The comparator invoked per element.
10565 * @returns {Array} Returns the new array of combined values.
10566 * @example
10567 *
10568 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
10569 * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
10570 *
10571 * _.unionWith(objects, others, _.isEqual);
10572 * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
10573 */
10574 var unionWith = rest(function(arrays) {
10575 var comparator = last(arrays);
10576 if (isArrayLikeObject(comparator)) {
10577 comparator = undefined;
10578 }
10579 return baseUniq(baseFlatten(arrays, 1, true), undefined, comparator);
10580 });
10581
10582 /**
10583 * Creates a duplicate-free version of an array, using
10584 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
10585 * for equality comparisons, in which only the first occurrence of each element
10586 * is kept.
10587 *
10588 * @static
10589 * @memberOf _
10590 * @category Array
10591 * @param {Array} array The array to inspect.
10592 * @returns {Array} Returns the new duplicate free array.
10593 * @example
10594 *
10595 * _.uniq([2, 1, 2]);
10596 * // => [2, 1]
10597 */
10598 function uniq(array) {
10599 return (array && array.length)
10600 ? baseUniq(array)
10601 : [];
10602 }
10603
10604 /**
10605 * This method is like `_.uniq` except that it accepts `iteratee` which is
10606 * invoked for each element in `array` to generate the criterion by which
10607 * uniqueness is computed. The iteratee is invoked with one argument: (value).
10608 *
10609 * @static
10610 * @memberOf _
10611 * @category Array
10612 * @param {Array} array The array to inspect.
10613 * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element.
10614 * @returns {Array} Returns the new duplicate free array.
10615 * @example
10616 *
10617 * _.uniqBy([2.1, 1.2, 2.3], Math.floor);
10618 * // => [2.1, 1.2]
10619 *
10620 * // The `_.property` iteratee shorthand.
10621 * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
10622 * // => [{ 'x': 1 }, { 'x': 2 }]
10623 */
10624 function uniqBy(array, iteratee) {
10625 return (array && array.length)
10626 ? baseUniq(array, getIteratee(iteratee))
10627 : [];
10628 }
10629
10630 /**
10631 * This method is like `_.uniq` except that it accepts `comparator` which
10632 * is invoked to compare elements of `array`. The comparator is invoked with
10633 * two arguments: (arrVal, othVal).
10634 *
10635 * @static
10636 * @memberOf _
10637 * @category Array
10638 * @param {Array} array The array to inspect.
10639 * @param {Function} [comparator] The comparator invoked per element.
10640 * @returns {Array} Returns the new duplicate free array.
10641 * @example
10642 *
10643 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
10644 *
10645 * _.uniqWith(objects, _.isEqual);
10646 * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
10647 */
10648 function uniqWith(array, comparator) {
10649 return (array && array.length)
10650 ? baseUniq(array, undefined, comparator)
10651 : [];
10652 }
10653
10654 /**
10655 * This method is like `_.zip` except that it accepts an array of grouped
10656 * elements and creates an array regrouping the elements to their pre-zip
10657 * configuration.
10658 *
10659 * @static
10660 * @memberOf _
10661 * @category Array
10662 * @param {Array} array The array of grouped elements to process.
10663 * @returns {Array} Returns the new array of regrouped elements.
10664 * @example
10665 *
10666 * var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]);
10667 * // => [['fred', 30, true], ['barney', 40, false]]
10668 *
10669 * _.unzip(zipped);
10670 * // => [['fred', 'barney'], [30, 40], [true, false]]
10671 */
10672 function unzip(array) {
10673 if (!(array && array.length)) {
10674 return [];
10675 }
10676 var length = 0;
10677 array = arrayFilter(array, function(group) {
10678 if (isArrayLikeObject(group)) {
10679 length = nativeMax(group.length, length);
10680 return true;
10681 }
10682 });
10683 return baseTimes(length, function(index) {
10684 return arrayMap(array, baseProperty(index));
10685 });
10686 }
10687
10688 /**
10689 * This method is like `_.unzip` except that it accepts `iteratee` to specify
10690 * how regrouped values should be combined. The iteratee is invoked with the
10691 * elements of each group: (...group).
10692 *
10693 * @static
10694 * @memberOf _
10695 * @category Array
10696 * @param {Array} array The array of grouped elements to process.
10697 * @param {Function} [iteratee=_.identity] The function to combine regrouped values.
10698 * @returns {Array} Returns the new array of regrouped elements.
10699 * @example
10700 *
10701 * var zipped = _.zip([1, 2], [10, 20], [100, 200]);
10702 * // => [[1, 10, 100], [2, 20, 200]]
10703 *
10704 * _.unzipWith(zipped, _.add);
10705 * // => [3, 30, 300]
10706 */
10707 function unzipWith(array, iteratee) {
10708 if (!(array && array.length)) {
10709 return [];
10710 }
10711 var result = unzip(array);
10712 if (iteratee == null) {
10713 return result;
10714 }
10715 return arrayMap(result, function(group) {
10716 return apply(iteratee, undefined, group);
10717 });
10718 }
10719
10720 /**
10721 * Creates an array excluding all given values using
10722 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
10723 * for equality comparisons.
10724 *
10725 * @static
10726 * @memberOf _
10727 * @category Array
10728 * @param {Array} array The array to filter.
10729 * @param {...*} [values] The values to exclude.
10730 * @returns {Array} Returns the new array of filtered values.
10731 * @example
10732 *
10733 * _.without([1, 2, 1, 3], 1, 2);
10734 * // => [3]
10735 */
10736 var without = rest(function(array, values) {
10737 return isArrayLikeObject(array)
10738 ? baseDifference(array, values)
10739 : [];
10740 });
10741
10742 /**
10743 * Creates an array of unique values that is the [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)
10744 * of the given arrays. The order of result values is determined by the order
10745 * they occur in the arrays.
10746 *
10747 * @static
10748 * @memberOf _
10749 * @category Array
10750 * @param {...Array} [arrays] The arrays to inspect.
10751 * @returns {Array} Returns the new array of values.
10752 * @example
10753 *
10754 * _.xor([2, 1], [4, 2]);
10755 * // => [1, 4]
10756 */
10757 var xor = rest(function(arrays) {
10758 return baseXor(arrayFilter(arrays, isArrayLikeObject));
10759 });
10760
10761 /**
10762 * This method is like `_.xor` except that it accepts `iteratee` which is
10763 * invoked for each element of each `arrays` to generate the criterion by which
10764 * by which they're compared. The iteratee is invoked with one argument: (value).
10765 *
10766 * @static
10767 * @memberOf _
10768 * @category Array
10769 * @param {...Array} [arrays] The arrays to inspect.
10770 * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element.
10771 * @returns {Array} Returns the new array of values.
10772 * @example
10773 *
10774 * _.xorBy([2.1, 1.2], [4.3, 2.4], Math.floor);
10775 * // => [1.2, 4.3]
10776 *
10777 * // The `_.property` iteratee shorthand.
10778 * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
10779 * // => [{ 'x': 2 }]
10780 */
10781 var xorBy = rest(function(arrays) {
10782 var iteratee = last(arrays);
10783 if (isArrayLikeObject(iteratee)) {
10784 iteratee = undefined;
10785 }
10786 return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee));
10787 });
10788
10789 /**
10790 * This method is like `_.xor` except that it accepts `comparator` which is
10791 * invoked to compare elements of `arrays`. The comparator is invoked with
10792 * two arguments: (arrVal, othVal).
10793 *
10794 * @static
10795 * @memberOf _
10796 * @category Array
10797 * @param {...Array} [arrays] The arrays to inspect.
10798 * @param {Function} [comparator] The comparator invoked per element.
10799 * @returns {Array} Returns the new array of values.
10800 * @example
10801 *
10802 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
10803 * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
10804 *
10805 * _.xorWith(objects, others, _.isEqual);
10806 * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
10807 */
10808 var xorWith = rest(function(arrays) {
10809 var comparator = last(arrays);
10810 if (isArrayLikeObject(comparator)) {
10811 comparator = undefined;
10812 }
10813 return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator);
10814 });
10815
10816 /**
10817 * Creates an array of grouped elements, the first of which contains the first
10818 * elements of the given arrays, the second of which contains the second elements
10819 * of the given arrays, and so on.
10820 *
10821 * @static
10822 * @memberOf _
10823 * @category Array
10824 * @param {...Array} [arrays] The arrays to process.
10825 * @returns {Array} Returns the new array of grouped elements.
10826 * @example
10827 *
10828 * _.zip(['fred', 'barney'], [30, 40], [true, false]);
10829 * // => [['fred', 30, true], ['barney', 40, false]]
10830 */
10831 var zip = rest(unzip);
10832
10833 /**
10834 * This method is like `_.fromPairs` except that it accepts two arrays,
10835 * one of property names and one of corresponding values.
10836 *
10837 * @static
10838 * @memberOf _
10839 * @category Array
10840 * @param {Array} [props=[]] The property names.
10841 * @param {Array} [values=[]] The property values.
10842 * @returns {Object} Returns the new object.
10843 * @example
10844 *
10845 * _.zipObject(['a', 'b'], [1, 2]);
10846 * // => { 'a': 1, 'b': 2 }
10847 */
10848 function zipObject(props, values) {
10849 return baseZipObject(props || [], values || [], assignValue);
10850 }
10851
10852 /**
10853 * This method is like `_.zipObject` except that it supports property paths.
10854 *
10855 * @static
10856 * @memberOf _
10857 * @category Array
10858 * @param {Array} [props=[]] The property names.
10859 * @param {Array} [values=[]] The property values.
10860 * @returns {Object} Returns the new object.
10861 * @example
10862 *
10863 * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);
10864 * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }
10865 */
10866 function zipObjectDeep(props, values) {
10867 return baseZipObject(props || [], values || [], baseSet);
10868 }
10869
10870 /**
10871 * This method is like `_.zip` except that it accepts `iteratee` to specify
10872 * how grouped values should be combined. The iteratee is invoked with the
10873 * elements of each group: (...group).
10874 *
10875 * @static
10876 * @memberOf _
10877 * @category Array
10878 * @param {...Array} [arrays] The arrays to process.
10879 * @param {Function} [iteratee=_.identity] The function to combine grouped values.
10880 * @returns {Array} Returns the new array of grouped elements.
10881 * @example
10882 *
10883 * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) {
10884 * return a + b + c;
10885 * });
10886 * // => [111, 222]
10887 */
10888 var zipWith = rest(function(arrays) {
10889 var length = arrays.length,
10890 iteratee = length > 1 ? arrays[length - 1] : undefined;
10891
10892 iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined;
10893 return unzipWith(arrays, iteratee);
10894 });
10895
10896 /*------------------------------------------------------------------------*/
10897
10898 /**
10899 * Creates a `lodash` object that wraps `value` with explicit method chaining enabled.
10900 * The result of such method chaining must be unwrapped with `_#value`.
10901 *
10902 * @static
10903 * @memberOf _
10904 * @category Seq
10905 * @param {*} value The value to wrap.
10906 * @returns {Object} Returns the new `lodash` wrapper instance.
10907 * @example
10908 *
10909 * var users = [
10910 * { 'user': 'barney', 'age': 36 },
10911 * { 'user': 'fred', 'age': 40 },
10912 * { 'user': 'pebbles', 'age': 1 }
10913 * ];
10914 *
10915 * var youngest = _
10916 * .chain(users)
10917 * .sortBy('age')
10918 * .map(function(o) {
10919 * return o.user + ' is ' + o.age;
10920 * })
10921 * .head()
10922 * .value();
10923 * // => 'pebbles is 1'
10924 */
10925 function chain(value) {
10926 var result = lodash(value);
10927 result.__chain__ = true;
10928 return result;
10929 }
10930
10931 /**
10932 * This method invokes `interceptor` and returns `value`. The interceptor
10933 * is invoked with one argument; (value). The purpose of this method is to
10934 * "tap into" a method chain in order to modify intermediate results.
10935 *
10936 * @static
10937 * @memberOf _
10938 * @category Seq
10939 * @param {*} value The value to provide to `interceptor`.
10940 * @param {Function} interceptor The function to invoke.
10941 * @returns {*} Returns `value`.
10942 * @example
10943 *
10944 * _([1, 2, 3])
10945 * .tap(function(array) {
10946 * // Mutate input array.
10947 * array.pop();
10948 * })
10949 * .reverse()
10950 * .value();
10951 * // => [2, 1]
10952 */
10953 function tap(value, interceptor) {
10954 interceptor(value);
10955 return value;
10956 }
10957
10958 /**
10959 * This method is like `_.tap` except that it returns the result of `interceptor`.
10960 * The purpose of this method is to "pass thru" values replacing intermediate
10961 * results in a method chain.
10962 *
10963 * @static
10964 * @memberOf _
10965 * @category Seq
10966 * @param {*} value The value to provide to `interceptor`.
10967 * @param {Function} interceptor The function to invoke.
10968 * @returns {*} Returns the result of `interceptor`.
10969 * @example
10970 *
10971 * _(' abc ')
10972 * .chain()
10973 * .trim()
10974 * .thru(function(value) {
10975 * return [value];
10976 * })
10977 * .value();
10978 * // => ['abc']
10979 */
10980 function thru(value, interceptor) {
10981 return interceptor(value);
10982 }
10983
10984 /**
10985 * This method is the wrapper version of `_.at`.
10986 *
10987 * @name at
10988 * @memberOf _
10989 * @category Seq
10990 * @param {...(string|string[])} [paths] The property paths of elements to pick,
10991 * specified individually or in arrays.
10992 * @returns {Object} Returns the new `lodash` wrapper instance.
10993 * @example
10994 *
10995 * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
10996 *
10997 * _(object).at(['a[0].b.c', 'a[1]']).value();
10998 * // => [3, 4]
10999 *
11000 * _(['a', 'b', 'c']).at(0, 2).value();
11001 * // => ['a', 'c']
11002 */
11003 var wrapperAt = rest(function(paths) {
11004 paths = baseFlatten(paths, 1);
11005 var length = paths.length,
11006 start = length ? paths[0] : 0,
11007 value = this.__wrapped__,
11008 interceptor = function(object) { return baseAt(object, paths); };
11009
11010 if (length > 1 || this.__actions__.length ||
11011 !(value instanceof LazyWrapper) || !isIndex(start)) {
11012 return this.thru(interceptor);
11013 }
11014 value = value.slice(start, +start + (length ? 1 : 0));
11015 value.__actions__.push({
11016 'func': thru,
11017 'args': [interceptor],
11018 'thisArg': undefined
11019 });
11020 return new LodashWrapper(value, this.__chain__).thru(function(array) {
11021 if (length && !array.length) {
11022 array.push(undefined);
11023 }
11024 return array;
11025 });
11026 });
11027
11028 /**
11029 * Enables explicit method chaining on the wrapper object.
11030 *
11031 * @name chain
11032 * @memberOf _
11033 * @category Seq
11034 * @returns {Object} Returns the new `lodash` wrapper instance.
11035 * @example
11036 *
11037 * var users = [
11038 * { 'user': 'barney', 'age': 36 },
11039 * { 'user': 'fred', 'age': 40 }
11040 * ];
11041 *
11042 * // A sequence without explicit chaining.
11043 * _(users).head();
11044 * // => { 'user': 'barney', 'age': 36 }
11045 *
11046 * // A sequence with explicit chaining.
11047 * _(users)
11048 * .chain()
11049 * .head()
11050 * .pick('user')
11051 * .value();
11052 * // => { 'user': 'barney' }
11053 */
11054 function wrapperChain() {
11055 return chain(this);
11056 }
11057
11058 /**
11059 * Executes the chained sequence and returns the wrapped result.
11060 *
11061 * @name commit
11062 * @memberOf _
11063 * @category Seq
11064 * @returns {Object} Returns the new `lodash` wrapper instance.
11065 * @example
11066 *
11067 * var array = [1, 2];
11068 * var wrapped = _(array).push(3);
11069 *
11070 * console.log(array);
11071 * // => [1, 2]
11072 *
11073 * wrapped = wrapped.commit();
11074 * console.log(array);
11075 * // => [1, 2, 3]
11076 *
11077 * wrapped.last();
11078 * // => 3
11079 *
11080 * console.log(array);
11081 * // => [1, 2, 3]
11082 */
11083 function wrapperCommit() {
11084 return new LodashWrapper(this.value(), this.__chain__);
11085 }
11086
11087 /**
11088 * This method is the wrapper version of `_.flatMap`.
11089 *
11090 * @name flatMap
11091 * @memberOf _
11092 * @category Seq
11093 * @param {Function|Object|string} [iteratee=_.identity] The function invoked per iteration.
11094 * @returns {Object} Returns the new `lodash` wrapper instance.
11095 * @example
11096 *
11097 * function duplicate(n) {
11098 * return [n, n];
11099 * }
11100 *
11101 * _([1, 2]).flatMap(duplicate).value();
11102 * // => [1, 1, 2, 2]
11103 */
11104 function wrapperFlatMap(iteratee) {
11105 return this.map(iteratee).flatten();
11106 }
11107
11108 /**
11109 * Gets the next value on a wrapped object following the
11110 * [iterator protocol](https://mdn.io/iteration_protocols#iterator).
11111 *
11112 * @name next
11113 * @memberOf _
11114 * @category Seq
11115 * @returns {Object} Returns the next iterator value.
11116 * @example
11117 *
11118 * var wrapped = _([1, 2]);
11119 *
11120 * wrapped.next();
11121 * // => { 'done': false, 'value': 1 }
11122 *
11123 * wrapped.next();
11124 * // => { 'done': false, 'value': 2 }
11125 *
11126 * wrapped.next();
11127 * // => { 'done': true, 'value': undefined }
11128 */
11129 function wrapperNext() {
11130 if (this.__values__ === undefined) {
11131 this.__values__ = toArray(this.value());
11132 }
11133 var done = this.__index__ >= this.__values__.length,
11134 value = done ? undefined : this.__values__[this.__index__++];
11135
11136 return { 'done': done, 'value': value };
11137 }
11138
11139 /**
11140 * Enables the wrapper to be iterable.
11141 *
11142 * @name Symbol.iterator
11143 * @memberOf _
11144 * @category Seq
11145 * @returns {Object} Returns the wrapper object.
11146 * @example
11147 *
11148 * var wrapped = _([1, 2]);
11149 *
11150 * wrapped[Symbol.iterator]() === wrapped;
11151 * // => true
11152 *
11153 * Array.from(wrapped);
11154 * // => [1, 2]
11155 */
11156 function wrapperToIterator() {
11157 return this;
11158 }
11159
11160 /**
11161 * Creates a clone of the chained sequence planting `value` as the wrapped value.
11162 *
11163 * @name plant
11164 * @memberOf _
11165 * @category Seq
11166 * @param {*} value The value to plant.
11167 * @returns {Object} Returns the new `lodash` wrapper instance.
11168 * @example
11169 *
11170 * function square(n) {
11171 * return n * n;
11172 * }
11173 *
11174 * var wrapped = _([1, 2]).map(square);
11175 * var other = wrapped.plant([3, 4]);
11176 *
11177 * other.value();
11178 * // => [9, 16]
11179 *
11180 * wrapped.value();
11181 * // => [1, 4]
11182 */
11183 function wrapperPlant(value) {
11184 var result,
11185 parent = this;
11186
11187 while (parent instanceof baseLodash) {
11188 var clone = wrapperClone(parent);
11189 clone.__index__ = 0;
11190 clone.__values__ = undefined;
11191 if (result) {
11192 previous.__wrapped__ = clone;
11193 } else {
11194 result = clone;
11195 }
11196 var previous = clone;
11197 parent = parent.__wrapped__;
11198 }
11199 previous.__wrapped__ = value;
11200 return result;
11201 }
11202
11203 /**
11204 * This method is the wrapper version of `_.reverse`.
11205 *
11206 * **Note:** This method mutates the wrapped array.
11207 *
11208 * @name reverse
11209 * @memberOf _
11210 * @category Seq
11211 * @returns {Object} Returns the new `lodash` wrapper instance.
11212 * @example
11213 *
11214 * var array = [1, 2, 3];
11215 *
11216 * _(array).reverse().value()
11217 * // => [3, 2, 1]
11218 *
11219 * console.log(array);
11220 * // => [3, 2, 1]
11221 */
11222 function wrapperReverse() {
11223 var value = this.__wrapped__;
11224 if (value instanceof LazyWrapper) {
11225 var wrapped = value;
11226 if (this.__actions__.length) {
11227 wrapped = new LazyWrapper(this);
11228 }
11229 wrapped = wrapped.reverse();
11230 wrapped.__actions__.push({
11231 'func': thru,
11232 'args': [reverse],
11233 'thisArg': undefined
11234 });
11235 return new LodashWrapper(wrapped, this.__chain__);
11236 }
11237 return this.thru(reverse);
11238 }
11239
11240 /**
11241 * Executes the chained sequence to extract the unwrapped value.
11242 *
11243 * @name value
11244 * @memberOf _
11245 * @alias toJSON, valueOf
11246 * @category Seq
11247 * @returns {*} Returns the resolved unwrapped value.
11248 * @example
11249 *
11250 * _([1, 2, 3]).value();
11251 * // => [1, 2, 3]
11252 */
11253 function wrapperValue() {
11254 return baseWrapperValue(this.__wrapped__, this.__actions__);
11255 }
11256
11257 /*------------------------------------------------------------------------*/
11258
11259 /**
11260 * Creates an object composed of keys generated from the results of running
11261 * each element of `collection` through `iteratee`. The corresponding value
11262 * of each key is the number of times the key was returned by `iteratee`.
11263 * The iteratee is invoked with one argument: (value).
11264 *
11265 * @static
11266 * @memberOf _
11267 * @category Collection
11268 * @param {Array|Object} collection The collection to iterate over.
11269 * @param {Function|Object|string} [iteratee=_.identity] The iteratee to transform keys.
11270 * @returns {Object} Returns the composed aggregate object.
11271 * @example
11272 *
11273 * _.countBy([6.1, 4.2, 6.3], Math.floor);
11274 * // => { '4': 1, '6': 2 }
11275 *
11276 * _.countBy(['one', 'two', 'three'], 'length');
11277 * // => { '3': 2, '5': 1 }
11278 */
11279 var countBy = createAggregator(function(result, value, key) {
11280 hasOwnProperty.call(result, key) ? ++result[key] : (result[key] = 1);
11281 });
11282
11283 /**
11284 * Checks if `predicate` returns truthy for **all** elements of `collection`.
11285 * Iteration is stopped once `predicate` returns falsey. The predicate is
11286 * invoked with three arguments: (value, index|key, collection).
11287 *
11288 * @static
11289 * @memberOf _
11290 * @category Collection
11291 * @param {Array|Object} collection The collection to iterate over.
11292 * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
11293 * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
11294 * @returns {boolean} Returns `true` if all elements pass the predicate check, else `false`.
11295 * @example
11296 *
11297 * _.every([true, 1, null, 'yes'], Boolean);
11298 * // => false
11299 *
11300 * var users = [
11301 * { 'user': 'barney', 'active': false },
11302 * { 'user': 'fred', 'active': false }
11303 * ];
11304 *
11305 * // The `_.matches` iteratee shorthand.
11306 * _.every(users, { 'user': 'barney', 'active': false });
11307 * // => false
11308 *
11309 * // The `_.matchesProperty` iteratee shorthand.
11310 * _.every(users, ['active', false]);
11311 * // => true
11312 *
11313 * // The `_.property` iteratee shorthand.
11314 * _.every(users, 'active');
11315 * // => false
11316 */
11317 function every(collection, predicate, guard) {
11318 var func = isArray(collection) ? arrayEvery : baseEvery;
11319 if (guard && isIterateeCall(collection, predicate, guard)) {
11320 predicate = undefined;
11321 }
11322 return func(collection, getIteratee(predicate, 3));
11323 }
11324
11325 /**
11326 * Iterates over elements of `collection`, returning an array of all elements
11327 * `predicate` returns truthy for. The predicate is invoked with three arguments:
11328 * (value, index|key, collection).
11329 *
11330 * @static
11331 * @memberOf _
11332 * @category Collection
11333 * @param {Array|Object} collection The collection to iterate over.
11334 * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
11335 * @returns {Array} Returns the new filtered array.
11336 * @example
11337 *
11338 * var users = [
11339 * { 'user': 'barney', 'age': 36, 'active': true },
11340 * { 'user': 'fred', 'age': 40, 'active': false }
11341 * ];
11342 *
11343 * _.filter(users, function(o) { return !o.active; });
11344 * // => objects for ['fred']
11345 *
11346 * // The `_.matches` iteratee shorthand.
11347 * _.filter(users, { 'age': 36, 'active': true });
11348 * // => objects for ['barney']
11349 *
11350 * // The `_.matchesProperty` iteratee shorthand.
11351 * _.filter(users, ['active', false]);
11352 * // => objects for ['fred']
11353 *
11354 * // The `_.property` iteratee shorthand.
11355 * _.filter(users, 'active');
11356 * // => objects for ['barney']
11357 */
11358 function filter(collection, predicate) {
11359 var func = isArray(collection) ? arrayFilter : baseFilter;
11360 return func(collection, getIteratee(predicate, 3));
11361 }
11362
11363 /**
11364 * Iterates over elements of `collection`, returning the first element
11365 * `predicate` returns truthy for. The predicate is invoked with three arguments:
11366 * (value, index|key, collection).
11367 *
11368 * @static
11369 * @memberOf _
11370 * @category Collection
11371 * @param {Array|Object} collection The collection to search.
11372 * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
11373 * @returns {*} Returns the matched element, else `undefined`.
11374 * @example
11375 *
11376 * var users = [
11377 * { 'user': 'barney', 'age': 36, 'active': true },
11378 * { 'user': 'fred', 'age': 40, 'active': false },
11379 * { 'user': 'pebbles', 'age': 1, 'active': true }
11380 * ];
11381 *
11382 * _.find(users, function(o) { return o.age < 40; });
11383 * // => object for 'barney'
11384 *
11385 * // The `_.matches` iteratee shorthand.
11386 * _.find(users, { 'age': 1, 'active': true });
11387 * // => object for 'pebbles'
11388 *
11389 * // The `_.matchesProperty` iteratee shorthand.
11390 * _.find(users, ['active', false]);
11391 * // => object for 'fred'
11392 *
11393 * // The `_.property` iteratee shorthand.
11394 * _.find(users, 'active');
11395 * // => object for 'barney'
11396 */
11397 function find(collection, predicate) {
11398 predicate = getIteratee(predicate, 3);
11399 if (isArray(collection)) {
11400 var index = baseFindIndex(collection, predicate);
11401 return index > -1 ? collection[index] : undefined;
11402 }
11403 return baseFind(collection, predicate, baseEach);
11404 }
11405
11406 /**
11407 * This method is like `_.find` except that it iterates over elements of
11408 * `collection` from right to left.
11409 *
11410 * @static
11411 * @memberOf _
11412 * @category Collection
11413 * @param {Array|Object} collection The collection to search.
11414 * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
11415 * @returns {*} Returns the matched element, else `undefined`.
11416 * @example
11417 *
11418 * _.findLast([1, 2, 3, 4], function(n) {
11419 * return n % 2 == 1;
11420 * });
11421 * // => 3
11422 */
11423 function findLast(collection, predicate) {
11424 predicate = getIteratee(predicate, 3);
11425 if (isArray(collection)) {
11426 var index = baseFindIndex(collection, predicate, true);
11427 return index > -1 ? collection[index] : undefined;
11428 }
11429 return baseFind(collection, predicate, baseEachRight);
11430 }
11431
11432 /**
11433 * Creates an array of flattened values by running each element in `collection`
11434 * through `iteratee` and concating its result to the other mapped values.
11435 * The iteratee is invoked with three arguments: (value, index|key, collection).
11436 *
11437 * @static
11438 * @memberOf _
11439 * @category Collection
11440 * @param {Array|Object} collection The collection to iterate over.
11441 * @param {Function|Object|string} [iteratee=_.identity] The function invoked per iteration.
11442 * @returns {Array} Returns the new flattened array.
11443 * @example
11444 *
11445 * function duplicate(n) {
11446 * return [n, n];
11447 * }
11448 *
11449 * _.flatMap([1, 2], duplicate);
11450 * // => [1, 1, 2, 2]
11451 */
11452 function flatMap(collection, iteratee) {
11453 return baseFlatten(map(collection, iteratee), 1);
11454 }
11455
11456 /**
11457 * Iterates over elements of `collection` invoking `iteratee` for each element.
11458 * The iteratee is invoked with three arguments: (value, index|key, collection).
11459 * Iteratee functions may exit iteration early by explicitly returning `false`.
11460 *
11461 * **Note:** As with other "Collections" methods, objects with a "length" property
11462 * are iterated like arrays. To avoid this behavior use `_.forIn` or `_.forOwn`
11463 * for object iteration.
11464 *
11465 * @static
11466 * @memberOf _
11467 * @alias each
11468 * @category Collection
11469 * @param {Array|Object} collection The collection to iterate over.
11470 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
11471 * @returns {Array|Object} Returns `collection`.
11472 * @example
11473 *
11474 * _([1, 2]).forEach(function(value) {
11475 * console.log(value);
11476 * });
11477 * // => logs `1` then `2`
11478 *
11479 * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
11480 * console.log(key);
11481 * });
11482 * // => logs 'a' then 'b' (iteration order is not guaranteed)
11483 */
11484 function forEach(collection, iteratee) {
11485 return (typeof iteratee == 'function' && isArray(collection))
11486 ? arrayEach(collection, iteratee)
11487 : baseEach(collection, baseCastFunction(iteratee));
11488 }
11489
11490 /**
11491 * This method is like `_.forEach` except that it iterates over elements of
11492 * `collection` from right to left.
11493 *
11494 * @static
11495 * @memberOf _
11496 * @alias eachRight
11497 * @category Collection
11498 * @param {Array|Object} collection The collection to iterate over.
11499 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
11500 * @returns {Array|Object} Returns `collection`.
11501 * @example
11502 *
11503 * _.forEachRight([1, 2], function(value) {
11504 * console.log(value);
11505 * });
11506 * // => logs `2` then `1`
11507 */
11508 function forEachRight(collection, iteratee) {
11509 return (typeof iteratee == 'function' && isArray(collection))
11510 ? arrayEachRight(collection, iteratee)
11511 : baseEachRight(collection, baseCastFunction(iteratee));
11512 }
11513
11514 /**
11515 * Creates an object composed of keys generated from the results of running
11516 * each element of `collection` through `iteratee`. The corresponding value
11517 * of each key is an array of elements responsible for generating the key.
11518 * The iteratee is invoked with one argument: (value).
11519 *
11520 * @static
11521 * @memberOf _
11522 * @category Collection
11523 * @param {Array|Object} collection The collection to iterate over.
11524 * @param {Function|Object|string} [iteratee=_.identity] The iteratee to transform keys.
11525 * @returns {Object} Returns the composed aggregate object.
11526 * @example
11527 *
11528 * _.groupBy([6.1, 4.2, 6.3], Math.floor);
11529 * // => { '4': [4.2], '6': [6.1, 6.3] }
11530 *
11531 * // The `_.property` iteratee shorthand.
11532 * _.groupBy(['one', 'two', 'three'], 'length');
11533 * // => { '3': ['one', 'two'], '5': ['three'] }
11534 */
11535 var groupBy = createAggregator(function(result, value, key) {
11536 if (hasOwnProperty.call(result, key)) {
11537 result[key].push(value);
11538 } else {
11539 result[key] = [value];
11540 }
11541 });
11542
11543 /**
11544 * Checks if `value` is in `collection`. If `collection` is a string it's checked
11545 * for a substring of `value`, otherwise [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
11546 * is used for equality comparisons. If `fromIndex` is negative, it's used as
11547 * the offset from the end of `collection`.
11548 *
11549 * @static
11550 * @memberOf _
11551 * @category Collection
11552 * @param {Array|Object|string} collection The collection to search.
11553 * @param {*} value The value to search for.
11554 * @param {number} [fromIndex=0] The index to search from.
11555 * @param- {Object} [guard] Enables use as an iteratee for functions like `_.reduce`.
11556 * @returns {boolean} Returns `true` if `value` is found, else `false`.
11557 * @example
11558 *
11559 * _.includes([1, 2, 3], 1);
11560 * // => true
11561 *
11562 * _.includes([1, 2, 3], 1, 2);
11563 * // => false
11564 *
11565 * _.includes({ 'user': 'fred', 'age': 40 }, 'fred');
11566 * // => true
11567 *
11568 * _.includes('pebbles', 'eb');
11569 * // => true
11570 */
11571 function includes(collection, value, fromIndex, guard) {
11572 collection = isArrayLike(collection) ? collection : values(collection);
11573 fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;
11574
11575 var length = collection.length;
11576 if (fromIndex < 0) {
11577 fromIndex = nativeMax(length + fromIndex, 0);
11578 }
11579 return isString(collection)
11580 ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)
11581 : (!!length && baseIndexOf(collection, value, fromIndex) > -1);
11582 }
11583
11584 /**
11585 * Invokes the method at `path` of each element in `collection`, returning
11586 * an array of the results of each invoked method. Any additional arguments
11587 * are provided to each invoked method. If `methodName` is a function it's
11588 * invoked for, and `this` bound to, each element in `collection`.
11589 *
11590 * @static
11591 * @memberOf _
11592 * @category Collection
11593 * @param {Array|Object} collection The collection to iterate over.
11594 * @param {Array|Function|string} path The path of the method to invoke or
11595 * the function invoked per iteration.
11596 * @param {...*} [args] The arguments to invoke each method with.
11597 * @returns {Array} Returns the array of results.
11598 * @example
11599 *
11600 * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');
11601 * // => [[1, 5, 7], [1, 2, 3]]
11602 *
11603 * _.invokeMap([123, 456], String.prototype.split, '');
11604 * // => [['1', '2', '3'], ['4', '5', '6']]
11605 */
11606 var invokeMap = rest(function(collection, path, args) {
11607 var index = -1,
11608 isFunc = typeof path == 'function',
11609 isProp = isKey(path),
11610 result = isArrayLike(collection) ? Array(collection.length) : [];
11611
11612 baseEach(collection, function(value) {
11613 var func = isFunc ? path : ((isProp && value != null) ? value[path] : undefined);
11614 result[++index] = func ? apply(func, value, args) : baseInvoke(value, path, args);
11615 });
11616 return result;
11617 });
11618
11619 /**
11620 * Creates an object composed of keys generated from the results of running
11621 * each element of `collection` through `iteratee`. The corresponding value
11622 * of each key is the last element responsible for generating the key. The
11623 * iteratee is invoked with one argument: (value).
11624 *
11625 * @static
11626 * @memberOf _
11627 * @category Collection
11628 * @param {Array|Object} collection The collection to iterate over.
11629 * @param {Function|Object|string} [iteratee=_.identity] The iteratee to transform keys.
11630 * @returns {Object} Returns the composed aggregate object.
11631 * @example
11632 *
11633 * var array = [
11634 * { 'dir': 'left', 'code': 97 },
11635 * { 'dir': 'right', 'code': 100 }
11636 * ];
11637 *
11638 * _.keyBy(array, function(o) {
11639 * return String.fromCharCode(o.code);
11640 * });
11641 * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
11642 *
11643 * _.keyBy(array, 'dir');
11644 * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
11645 */
11646 var keyBy = createAggregator(function(result, value, key) {
11647 result[key] = value;
11648 });
11649
11650 /**
11651 * Creates an array of values by running each element in `collection` through
11652 * `iteratee`. The iteratee is invoked with three arguments:
11653 * (value, index|key, collection).
11654 *
11655 * Many lodash methods are guarded to work as iteratees for methods like
11656 * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
11657 *
11658 * The guarded methods are:
11659 * `ary`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, `fill`,
11660 * `invert`, `parseInt`, `random`, `range`, `rangeRight`, `slice`, `some`,
11661 * `sortBy`, `take`, `takeRight`, `template`, `trim`, `trimEnd`, `trimStart`,
11662 * and `words`
11663 *
11664 * @static
11665 * @memberOf _
11666 * @category Collection
11667 * @param {Array|Object} collection The collection to iterate over.
11668 * @param {Function|Object|string} [iteratee=_.identity] The function invoked per iteration.
11669 * @returns {Array} Returns the new mapped array.
11670 * @example
11671 *
11672 * function square(n) {
11673 * return n * n;
11674 * }
11675 *
11676 * _.map([4, 8], square);
11677 * // => [16, 64]
11678 *
11679 * _.map({ 'a': 4, 'b': 8 }, square);
11680 * // => [16, 64] (iteration order is not guaranteed)
11681 *
11682 * var users = [
11683 * { 'user': 'barney' },
11684 * { 'user': 'fred' }
11685 * ];
11686 *
11687 * // The `_.property` iteratee shorthand.
11688 * _.map(users, 'user');
11689 * // => ['barney', 'fred']
11690 */
11691 function map(collection, iteratee) {
11692 var func = isArray(collection) ? arrayMap : baseMap;
11693 return func(collection, getIteratee(iteratee, 3));
11694 }
11695
11696 /**
11697 * This method is like `_.sortBy` except that it allows specifying the sort
11698 * orders of the iteratees to sort by. If `orders` is unspecified, all values
11699 * are sorted in ascending order. Otherwise, specify an order of "desc" for
11700 * descending or "asc" for ascending sort order of corresponding values.
11701 *
11702 * @static
11703 * @memberOf _
11704 * @category Collection
11705 * @param {Array|Object} collection The collection to iterate over.
11706 * @param {Function[]|Object[]|string[]} [iteratees=[_.identity]] The iteratees to sort by.
11707 * @param {string[]} [orders] The sort orders of `iteratees`.
11708 * @param- {Object} [guard] Enables use as an iteratee for functions like `_.reduce`.
11709 * @returns {Array} Returns the new sorted array.
11710 * @example
11711 *
11712 * var users = [
11713 * { 'user': 'fred', 'age': 48 },
11714 * { 'user': 'barney', 'age': 34 },
11715 * { 'user': 'fred', 'age': 42 },
11716 * { 'user': 'barney', 'age': 36 }
11717 * ];
11718 *
11719 * // Sort by `user` in ascending order and by `age` in descending order.
11720 * _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
11721 * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
11722 */
11723 function orderBy(collection, iteratees, orders, guard) {
11724 if (collection == null) {
11725 return [];
11726 }
11727 if (!isArray(iteratees)) {
11728 iteratees = iteratees == null ? [] : [iteratees];
11729 }
11730 orders = guard ? undefined : orders;
11731 if (!isArray(orders)) {
11732 orders = orders == null ? [] : [orders];
11733 }
11734 return baseOrderBy(collection, iteratees, orders);
11735 }
11736
11737 /**
11738 * Creates an array of elements split into two groups, the first of which
11739 * contains elements `predicate` returns truthy for, the second of which
11740 * contains elements `predicate` returns falsey for. The predicate is
11741 * invoked with one argument: (value).
11742 *
11743 * @static
11744 * @memberOf _
11745 * @category Collection
11746 * @param {Array|Object} collection The collection to iterate over.
11747 * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
11748 * @returns {Array} Returns the array of grouped elements.
11749 * @example
11750 *
11751 * var users = [
11752 * { 'user': 'barney', 'age': 36, 'active': false },
11753 * { 'user': 'fred', 'age': 40, 'active': true },
11754 * { 'user': 'pebbles', 'age': 1, 'active': false }
11755 * ];
11756 *
11757 * _.partition(users, function(o) { return o.active; });
11758 * // => objects for [['fred'], ['barney', 'pebbles']]
11759 *
11760 * // The `_.matches` iteratee shorthand.
11761 * _.partition(users, { 'age': 1, 'active': false });
11762 * // => objects for [['pebbles'], ['barney', 'fred']]
11763 *
11764 * // The `_.matchesProperty` iteratee shorthand.
11765 * _.partition(users, ['active', false]);
11766 * // => objects for [['barney', 'pebbles'], ['fred']]
11767 *
11768 * // The `_.property` iteratee shorthand.
11769 * _.partition(users, 'active');
11770 * // => objects for [['fred'], ['barney', 'pebbles']]
11771 */
11772 var partition = createAggregator(function(result, value, key) {
11773 result[key ? 0 : 1].push(value);
11774 }, function() { return [[], []]; });
11775
11776 /**
11777 * Reduces `collection` to a value which is the accumulated result of running
11778 * each element in `collection` through `iteratee`, where each successive
11779 * invocation is supplied the return value of the previous. If `accumulator`
11780 * is not given the first element of `collection` is used as the initial
11781 * value. The iteratee is invoked with four arguments:
11782 * (accumulator, value, index|key, collection).
11783 *
11784 * Many lodash methods are guarded to work as iteratees for methods like
11785 * `_.reduce`, `_.reduceRight`, and `_.transform`.
11786 *
11787 * The guarded methods are:
11788 * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
11789 * and `sortBy`
11790 *
11791 * @static
11792 * @memberOf _
11793 * @category Collection
11794 * @param {Array|Object} collection The collection to iterate over.
11795 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
11796 * @param {*} [accumulator] The initial value.
11797 * @returns {*} Returns the accumulated value.
11798 * @example
11799 *
11800 * _.reduce([1, 2], function(sum, n) {
11801 * return sum + n;
11802 * }, 0);
11803 * // => 3
11804 *
11805 * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
11806 * (result[value] || (result[value] = [])).push(key);
11807 * return result;
11808 * }, {});
11809 * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
11810 */
11811 function reduce(collection, iteratee, accumulator) {
11812 var func = isArray(collection) ? arrayReduce : baseReduce,
11813 initAccum = arguments.length < 3;
11814
11815 return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach);
11816 }
11817
11818 /**
11819 * This method is like `_.reduce` except that it iterates over elements of
11820 * `collection` from right to left.
11821 *
11822 * @static
11823 * @memberOf _
11824 * @category Collection
11825 * @param {Array|Object} collection The collection to iterate over.
11826 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
11827 * @param {*} [accumulator] The initial value.
11828 * @returns {*} Returns the accumulated value.
11829 * @example
11830 *
11831 * var array = [[0, 1], [2, 3], [4, 5]];
11832 *
11833 * _.reduceRight(array, function(flattened, other) {
11834 * return flattened.concat(other);
11835 * }, []);
11836 * // => [4, 5, 2, 3, 0, 1]
11837 */
11838 function reduceRight(collection, iteratee, accumulator) {
11839 var func = isArray(collection) ? arrayReduceRight : baseReduce,
11840 initAccum = arguments.length < 3;
11841
11842 return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight);
11843 }
11844
11845 /**
11846 * The opposite of `_.filter`; this method returns the elements of `collection`
11847 * that `predicate` does **not** return truthy for.
11848 *
11849 * @static
11850 * @memberOf _
11851 * @category Collection
11852 * @param {Array|Object} collection The collection to iterate over.
11853 * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
11854 * @returns {Array} Returns the new filtered array.
11855 * @example
11856 *
11857 * var users = [
11858 * { 'user': 'barney', 'age': 36, 'active': false },
11859 * { 'user': 'fred', 'age': 40, 'active': true }
11860 * ];
11861 *
11862 * _.reject(users, function(o) { return !o.active; });
11863 * // => objects for ['fred']
11864 *
11865 * // The `_.matches` iteratee shorthand.
11866 * _.reject(users, { 'age': 40, 'active': true });
11867 * // => objects for ['barney']
11868 *
11869 * // The `_.matchesProperty` iteratee shorthand.
11870 * _.reject(users, ['active', false]);
11871 * // => objects for ['fred']
11872 *
11873 * // The `_.property` iteratee shorthand.
11874 * _.reject(users, 'active');
11875 * // => objects for ['barney']
11876 */
11877 function reject(collection, predicate) {
11878 var func = isArray(collection) ? arrayFilter : baseFilter;
11879 predicate = getIteratee(predicate, 3);
11880 return func(collection, function(value, index, collection) {
11881 return !predicate(value, index, collection);
11882 });
11883 }
11884
11885 /**
11886 * Gets a random element from `collection`.
11887 *
11888 * @static
11889 * @memberOf _
11890 * @category Collection
11891 * @param {Array|Object} collection The collection to sample.
11892 * @returns {*} Returns the random element.
11893 * @example
11894 *
11895 * _.sample([1, 2, 3, 4]);
11896 * // => 2
11897 */
11898 function sample(collection) {
11899 var array = isArrayLike(collection) ? collection : values(collection),
11900 length = array.length;
11901
11902 return length > 0 ? array[baseRandom(0, length - 1)] : undefined;
11903 }
11904
11905 /**
11906 * Gets `n` random elements at unique keys from `collection` up to the
11907 * size of `collection`.
11908 *
11909 * @static
11910 * @memberOf _
11911 * @category Collection
11912 * @param {Array|Object} collection The collection to sample.
11913 * @param {number} [n=0] The number of elements to sample.
11914 * @returns {Array} Returns the random elements.
11915 * @example
11916 *
11917 * _.sampleSize([1, 2, 3], 2);
11918 * // => [3, 1]
11919 *
11920 * _.sampleSize([1, 2, 3], 4);
11921 * // => [2, 3, 1]
11922 */
11923 function sampleSize(collection, n) {
11924 var index = -1,
11925 result = toArray(collection),
11926 length = result.length,
11927 lastIndex = length - 1;
11928
11929 n = baseClamp(toInteger(n), 0, length);
11930 while (++index < n) {
11931 var rand = baseRandom(index, lastIndex),
11932 value = result[rand];
11933
11934 result[rand] = result[index];
11935 result[index] = value;
11936 }
11937 result.length = n;
11938 return result;
11939 }
11940
11941 /**
11942 * Creates an array of shuffled values, using a version of the
11943 * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
11944 *
11945 * @static
11946 * @memberOf _
11947 * @category Collection
11948 * @param {Array|Object} collection The collection to shuffle.
11949 * @returns {Array} Returns the new shuffled array.
11950 * @example
11951 *
11952 * _.shuffle([1, 2, 3, 4]);
11953 * // => [4, 1, 3, 2]
11954 */
11955 function shuffle(collection) {
11956 return sampleSize(collection, MAX_ARRAY_LENGTH);
11957 }
11958
11959 /**
11960 * Gets the size of `collection` by returning its length for array-like
11961 * values or the number of own enumerable properties for objects.
11962 *
11963 * @static
11964 * @memberOf _
11965 * @category Collection
11966 * @param {Array|Object} collection The collection to inspect.
11967 * @returns {number} Returns the collection size.
11968 * @example
11969 *
11970 * _.size([1, 2, 3]);
11971 * // => 3
11972 *
11973 * _.size({ 'a': 1, 'b': 2 });
11974 * // => 2
11975 *
11976 * _.size('pebbles');
11977 * // => 7
11978 */
11979 function size(collection) {
11980 if (collection == null) {
11981 return 0;
11982 }
11983 if (isArrayLike(collection)) {
11984 var result = collection.length;
11985 return (result && isString(collection)) ? stringSize(collection) : result;
11986 }
11987 return keys(collection).length;
11988 }
11989
11990 /**
11991 * Checks if `predicate` returns truthy for **any** element of `collection`.
11992 * Iteration is stopped once `predicate` returns truthy. The predicate is
11993 * invoked with three arguments: (value, index|key, collection).
11994 *
11995 * @static
11996 * @memberOf _
11997 * @category Collection
11998 * @param {Array|Object} collection The collection to iterate over.
11999 * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
12000 * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
12001 * @returns {boolean} Returns `true` if any element passes the predicate check, else `false`.
12002 * @example
12003 *
12004 * _.some([null, 0, 'yes', false], Boolean);
12005 * // => true
12006 *
12007 * var users = [
12008 * { 'user': 'barney', 'active': true },
12009 * { 'user': 'fred', 'active': false }
12010 * ];
12011 *
12012 * // The `_.matches` iteratee shorthand.
12013 * _.some(users, { 'user': 'barney', 'active': false });
12014 * // => false
12015 *
12016 * // The `_.matchesProperty` iteratee shorthand.
12017 * _.some(users, ['active', false]);
12018 * // => true
12019 *
12020 * // The `_.property` iteratee shorthand.
12021 * _.some(users, 'active');
12022 * // => true
12023 */
12024 function some(collection, predicate, guard) {
12025 var func = isArray(collection) ? arraySome : baseSome;
12026 if (guard && isIterateeCall(collection, predicate, guard)) {
12027 predicate = undefined;
12028 }
12029 return func(collection, getIteratee(predicate, 3));
12030 }
12031
12032 /**
12033 * Creates an array of elements, sorted in ascending order by the results of
12034 * running each element in a collection through each iteratee. This method
12035 * performs a stable sort, that is, it preserves the original sort order of
12036 * equal elements. The iteratees are invoked with one argument: (value).
12037 *
12038 * @static
12039 * @memberOf _
12040 * @category Collection
12041 * @param {Array|Object} collection The collection to iterate over.
12042 * @param {...(Function|Function[]|Object|Object[]|string|string[])} [iteratees=[_.identity]]
12043 * The iteratees to sort by, specified individually or in arrays.
12044 * @returns {Array} Returns the new sorted array.
12045 * @example
12046 *
12047 * var users = [
12048 * { 'user': 'fred', 'age': 48 },
12049 * { 'user': 'barney', 'age': 36 },
12050 * { 'user': 'fred', 'age': 42 },
12051 * { 'user': 'barney', 'age': 34 }
12052 * ];
12053 *
12054 * _.sortBy(users, function(o) { return o.user; });
12055 * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
12056 *
12057 * _.sortBy(users, ['user', 'age']);
12058 * // => objects for [['barney', 34], ['barney', 36], ['fred', 42], ['fred', 48]]
12059 *
12060 * _.sortBy(users, 'user', function(o) {
12061 * return Math.floor(o.age / 10);
12062 * });
12063 * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
12064 */
12065 var sortBy = rest(function(collection, iteratees) {
12066 if (collection == null) {
12067 return [];
12068 }
12069 var length = iteratees.length;
12070 if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {
12071 iteratees = [];
12072 } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
12073 iteratees.length = 1;
12074 }
12075 return baseOrderBy(collection, baseFlatten(iteratees, 1), []);
12076 });
12077
12078 /*------------------------------------------------------------------------*/
12079
12080 /**
12081 * Gets the timestamp of the number of milliseconds that have elapsed since
12082 * the Unix epoch (1 January 1970 00:00:00 UTC).
12083 *
12084 * @static
12085 * @memberOf _
12086 * @type {Function}
12087 * @category Date
12088 * @returns {number} Returns the timestamp.
12089 * @example
12090 *
12091 * _.defer(function(stamp) {
12092 * console.log(_.now() - stamp);
12093 * }, _.now());
12094 * // => logs the number of milliseconds it took for the deferred function to be invoked
12095 */
12096 var now = Date.now;
12097
12098 /*------------------------------------------------------------------------*/
12099
12100 /**
12101 * The opposite of `_.before`; this method creates a function that invokes
12102 * `func` once it's called `n` or more times.
12103 *
12104 * @static
12105 * @memberOf _
12106 * @category Function
12107 * @param {number} n The number of calls before `func` is invoked.
12108 * @param {Function} func The function to restrict.
12109 * @returns {Function} Returns the new restricted function.
12110 * @example
12111 *
12112 * var saves = ['profile', 'settings'];
12113 *
12114 * var done = _.after(saves.length, function() {
12115 * console.log('done saving!');
12116 * });
12117 *
12118 * _.forEach(saves, function(type) {
12119 * asyncSave({ 'type': type, 'complete': done });
12120 * });
12121 * // => logs 'done saving!' after the two async saves have completed
12122 */
12123 function after(n, func) {
12124 if (typeof func != 'function') {
12125 throw new TypeError(FUNC_ERROR_TEXT);
12126 }
12127 n = toInteger(n);
12128 return function() {
12129 if (--n < 1) {
12130 return func.apply(this, arguments);
12131 }
12132 };
12133 }
12134
12135 /**
12136 * Creates a function that accepts up to `n` arguments, ignoring any
12137 * additional arguments.
12138 *
12139 * @static
12140 * @memberOf _
12141 * @category Function
12142 * @param {Function} func The function to cap arguments for.
12143 * @param {number} [n=func.length] The arity cap.
12144 * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
12145 * @returns {Function} Returns the new function.
12146 * @example
12147 *
12148 * _.map(['6', '8', '10'], _.ary(parseInt, 1));
12149 * // => [6, 8, 10]
12150 */
12151 function ary(func, n, guard) {
12152 n = guard ? undefined : n;
12153 n = (func && n == null) ? func.length : n;
12154 return createWrapper(func, ARY_FLAG, undefined, undefined, undefined, undefined, n);
12155 }
12156
12157 /**
12158 * Creates a function that invokes `func`, with the `this` binding and arguments
12159 * of the created function, while it's called less than `n` times. Subsequent
12160 * calls to the created function return the result of the last `func` invocation.
12161 *
12162 * @static
12163 * @memberOf _
12164 * @category Function
12165 * @param {number} n The number of calls at which `func` is no longer invoked.
12166 * @param {Function} func The function to restrict.
12167 * @returns {Function} Returns the new restricted function.
12168 * @example
12169 *
12170 * jQuery(element).on('click', _.before(5, addContactToList));
12171 * // => allows adding up to 4 contacts to the list
12172 */
12173 function before(n, func) {
12174 var result;
12175 if (typeof func != 'function') {
12176 throw new TypeError(FUNC_ERROR_TEXT);
12177 }
12178 n = toInteger(n);
12179 return function() {
12180 if (--n > 0) {
12181 result = func.apply(this, arguments);
12182 }
12183 if (n <= 1) {
12184 func = undefined;
12185 }
12186 return result;
12187 };
12188 }
12189
12190 /**
12191 * Creates a function that invokes `func` with the `this` binding of `thisArg`
12192 * and prepends any additional `_.bind` arguments to those provided to the
12193 * bound function.
12194 *
12195 * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
12196 * may be used as a placeholder for partially applied arguments.
12197 *
12198 * **Note:** Unlike native `Function#bind` this method doesn't set the "length"
12199 * property of bound functions.
12200 *
12201 * @static
12202 * @memberOf _
12203 * @category Function
12204 * @param {Function} func The function to bind.
12205 * @param {*} thisArg The `this` binding of `func`.
12206 * @param {...*} [partials] The arguments to be partially applied.
12207 * @returns {Function} Returns the new bound function.
12208 * @example
12209 *
12210 * var greet = function(greeting, punctuation) {
12211 * return greeting + ' ' + this.user + punctuation;
12212 * };
12213 *
12214 * var object = { 'user': 'fred' };
12215 *
12216 * var bound = _.bind(greet, object, 'hi');
12217 * bound('!');
12218 * // => 'hi fred!'
12219 *
12220 * // Bound with placeholders.
12221 * var bound = _.bind(greet, object, _, '!');
12222 * bound('hi');
12223 * // => 'hi fred!'
12224 */
12225 var bind = rest(function(func, thisArg, partials) {
12226 var bitmask = BIND_FLAG;
12227 if (partials.length) {
12228 var holders = replaceHolders(partials, getPlaceholder(bind));
12229 bitmask |= PARTIAL_FLAG;
12230 }
12231 return createWrapper(func, bitmask, thisArg, partials, holders);
12232 });
12233
12234 /**
12235 * Creates a function that invokes the method at `object[key]` and prepends
12236 * any additional `_.bindKey` arguments to those provided to the bound function.
12237 *
12238 * This method differs from `_.bind` by allowing bound functions to reference
12239 * methods that may be redefined or don't yet exist.
12240 * See [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)
12241 * for more details.
12242 *
12243 * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic
12244 * builds, may be used as a placeholder for partially applied arguments.
12245 *
12246 * @static
12247 * @memberOf _
12248 * @category Function
12249 * @param {Object} object The object to invoke the method on.
12250 * @param {string} key The key of the method.
12251 * @param {...*} [partials] The arguments to be partially applied.
12252 * @returns {Function} Returns the new bound function.
12253 * @example
12254 *
12255 * var object = {
12256 * 'user': 'fred',
12257 * 'greet': function(greeting, punctuation) {
12258 * return greeting + ' ' + this.user + punctuation;
12259 * }
12260 * };
12261 *
12262 * var bound = _.bindKey(object, 'greet', 'hi');
12263 * bound('!');
12264 * // => 'hi fred!'
12265 *
12266 * object.greet = function(greeting, punctuation) {
12267 * return greeting + 'ya ' + this.user + punctuation;
12268 * };
12269 *
12270 * bound('!');
12271 * // => 'hiya fred!'
12272 *
12273 * // Bound with placeholders.
12274 * var bound = _.bindKey(object, 'greet', _, '!');
12275 * bound('hi');
12276 * // => 'hiya fred!'
12277 */
12278 var bindKey = rest(function(object, key, partials) {
12279 var bitmask = BIND_FLAG | BIND_KEY_FLAG;
12280 if (partials.length) {
12281 var holders = replaceHolders(partials, getPlaceholder(bindKey));
12282 bitmask |= PARTIAL_FLAG;
12283 }
12284 return createWrapper(key, bitmask, object, partials, holders);
12285 });
12286
12287 /**
12288 * Creates a function that accepts arguments of `func` and either invokes
12289 * `func` returning its result, if at least `arity` number of arguments have
12290 * been provided, or returns a function that accepts the remaining `func`
12291 * arguments, and so on. The arity of `func` may be specified if `func.length`
12292 * is not sufficient.
12293 *
12294 * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
12295 * may be used as a placeholder for provided arguments.
12296 *
12297 * **Note:** This method doesn't set the "length" property of curried functions.
12298 *
12299 * @static
12300 * @memberOf _
12301 * @category Function
12302 * @param {Function} func The function to curry.
12303 * @param {number} [arity=func.length] The arity of `func`.
12304 * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
12305 * @returns {Function} Returns the new curried function.
12306 * @example
12307 *
12308 * var abc = function(a, b, c) {
12309 * return [a, b, c];
12310 * };
12311 *
12312 * var curried = _.curry(abc);
12313 *
12314 * curried(1)(2)(3);
12315 * // => [1, 2, 3]
12316 *
12317 * curried(1, 2)(3);
12318 * // => [1, 2, 3]
12319 *
12320 * curried(1, 2, 3);
12321 * // => [1, 2, 3]
12322 *
12323 * // Curried with placeholders.
12324 * curried(1)(_, 3)(2);
12325 * // => [1, 2, 3]
12326 */
12327 function curry(func, arity, guard) {
12328 arity = guard ? undefined : arity;
12329 var result = createWrapper(func, CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
12330 result.placeholder = curry.placeholder;
12331 return result;
12332 }
12333
12334 /**
12335 * This method is like `_.curry` except that arguments are applied to `func`
12336 * in the manner of `_.partialRight` instead of `_.partial`.
12337 *
12338 * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
12339 * builds, may be used as a placeholder for provided arguments.
12340 *
12341 * **Note:** This method doesn't set the "length" property of curried functions.
12342 *
12343 * @static
12344 * @memberOf _
12345 * @category Function
12346 * @param {Function} func The function to curry.
12347 * @param {number} [arity=func.length] The arity of `func`.
12348 * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
12349 * @returns {Function} Returns the new curried function.
12350 * @example
12351 *
12352 * var abc = function(a, b, c) {
12353 * return [a, b, c];
12354 * };
12355 *
12356 * var curried = _.curryRight(abc);
12357 *
12358 * curried(3)(2)(1);
12359 * // => [1, 2, 3]
12360 *
12361 * curried(2, 3)(1);
12362 * // => [1, 2, 3]
12363 *
12364 * curried(1, 2, 3);
12365 * // => [1, 2, 3]
12366 *
12367 * // Curried with placeholders.
12368 * curried(3)(1, _)(2);
12369 * // => [1, 2, 3]
12370 */
12371 function curryRight(func, arity, guard) {
12372 arity = guard ? undefined : arity;
12373 var result = createWrapper(func, CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
12374 result.placeholder = curryRight.placeholder;
12375 return result;
12376 }
12377
12378 /**
12379 * Creates a debounced function that delays invoking `func` until after `wait`
12380 * milliseconds have elapsed since the last time the debounced function was
12381 * invoked. The debounced function comes with a `cancel` method to cancel
12382 * delayed `func` invocations and a `flush` method to immediately invoke them.
12383 * Provide an options object to indicate whether `func` should be invoked on
12384 * the leading and/or trailing edge of the `wait` timeout. The `func` is invoked
12385 * with the last arguments provided to the debounced function. Subsequent calls
12386 * to the debounced function return the result of the last `func` invocation.
12387 *
12388 * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
12389 * on the trailing edge of the timeout only if the debounced function is
12390 * invoked more than once during the `wait` timeout.
12391 *
12392 * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
12393 * for details over the differences between `_.debounce` and `_.throttle`.
12394 *
12395 * @static
12396 * @memberOf _
12397 * @category Function
12398 * @param {Function} func The function to debounce.
12399 * @param {number} [wait=0] The number of milliseconds to delay.
12400 * @param {Object} [options] The options object.
12401 * @param {boolean} [options.leading=false] Specify invoking on the leading
12402 * edge of the timeout.
12403 * @param {number} [options.maxWait] The maximum time `func` is allowed to be
12404 * delayed before it's invoked.
12405 * @param {boolean} [options.trailing=true] Specify invoking on the trailing
12406 * edge of the timeout.
12407 * @returns {Function} Returns the new debounced function.
12408 * @example
12409 *
12410 * // Avoid costly calculations while the window size is in flux.
12411 * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
12412 *
12413 * // Invoke `sendMail` when clicked, debouncing subsequent calls.
12414 * jQuery(element).on('click', _.debounce(sendMail, 300, {
12415 * 'leading': true,
12416 * 'trailing': false
12417 * }));
12418 *
12419 * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
12420 * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
12421 * var source = new EventSource('/stream');
12422 * jQuery(source).on('message', debounced);
12423 *
12424 * // Cancel the trailing debounced invocation.
12425 * jQuery(window).on('popstate', debounced.cancel);
12426 */
12427 function debounce(func, wait, options) {
12428 var args,
12429 maxTimeoutId,
12430 result,
12431 stamp,
12432 thisArg,
12433 timeoutId,
12434 trailingCall,
12435 lastCalled = 0,
12436 leading = false,
12437 maxWait = false,
12438 trailing = true;
12439
12440 if (typeof func != 'function') {
12441 throw new TypeError(FUNC_ERROR_TEXT);
12442 }
12443 wait = toNumber(wait) || 0;
12444 if (isObject(options)) {
12445 leading = !!options.leading;
12446 maxWait = 'maxWait' in options && nativeMax(toNumber(options.maxWait) || 0, wait);
12447 trailing = 'trailing' in options ? !!options.trailing : trailing;
12448 }
12449
12450 function cancel() {
12451 if (timeoutId) {
12452 clearTimeout(timeoutId);
12453 }
12454 if (maxTimeoutId) {
12455 clearTimeout(maxTimeoutId);
12456 }
12457 lastCalled = 0;
12458 args = maxTimeoutId = thisArg = timeoutId = trailingCall = undefined;
12459 }
12460
12461 function complete(isCalled, id) {
12462 if (id) {
12463 clearTimeout(id);
12464 }
12465 maxTimeoutId = timeoutId = trailingCall = undefined;
12466 if (isCalled) {
12467 lastCalled = now();
12468 result = func.apply(thisArg, args);
12469 if (!timeoutId && !maxTimeoutId) {
12470 args = thisArg = undefined;
12471 }
12472 }
12473 }
12474
12475 function delayed() {
12476 var remaining = wait - (now() - stamp);
12477 if (remaining <= 0 || remaining > wait) {
12478 complete(trailingCall, maxTimeoutId);
12479 } else {
12480 timeoutId = setTimeout(delayed, remaining);
12481 }
12482 }
12483
12484 function flush() {
12485 if ((timeoutId && trailingCall) || (maxTimeoutId && trailing)) {
12486 result = func.apply(thisArg, args);
12487 }
12488 cancel();
12489 return result;
12490 }
12491
12492 function maxDelayed() {
12493 complete(trailing, timeoutId);
12494 }
12495
12496 function debounced() {
12497 args = arguments;
12498 stamp = now();
12499 thisArg = this;
12500 trailingCall = trailing && (timeoutId || !leading);
12501
12502 if (maxWait === false) {
12503 var leadingCall = leading && !timeoutId;
12504 } else {
12505 if (!lastCalled && !maxTimeoutId && !leading) {
12506 lastCalled = stamp;
12507 }
12508 var remaining = maxWait - (stamp - lastCalled);
12509
12510 var isCalled = (remaining <= 0 || remaining > maxWait) &&
12511 (leading || maxTimeoutId);
12512
12513 if (isCalled) {
12514 if (maxTimeoutId) {
12515 maxTimeoutId = clearTimeout(maxTimeoutId);
12516 }
12517 lastCalled = stamp;
12518 result = func.apply(thisArg, args);
12519 }
12520 else if (!maxTimeoutId) {
12521 maxTimeoutId = setTimeout(maxDelayed, remaining);
12522 }
12523 }
12524 if (isCalled && timeoutId) {
12525 timeoutId = clearTimeout(timeoutId);
12526 }
12527 else if (!timeoutId && wait !== maxWait) {
12528 timeoutId = setTimeout(delayed, wait);
12529 }
12530 if (leadingCall) {
12531 isCalled = true;
12532 result = func.apply(thisArg, args);
12533 }
12534 if (isCalled && !timeoutId && !maxTimeoutId) {
12535 args = thisArg = undefined;
12536 }
12537 return result;
12538 }
12539 debounced.cancel = cancel;
12540 debounced.flush = flush;
12541 return debounced;
12542 }
12543
12544 /**
12545 * Defers invoking the `func` until the current call stack has cleared. Any
12546 * additional arguments are provided to `func` when it's invoked.
12547 *
12548 * @static
12549 * @memberOf _
12550 * @category Function
12551 * @param {Function} func The function to defer.
12552 * @param {...*} [args] The arguments to invoke `func` with.
12553 * @returns {number} Returns the timer id.
12554 * @example
12555 *
12556 * _.defer(function(text) {
12557 * console.log(text);
12558 * }, 'deferred');
12559 * // => logs 'deferred' after one or more milliseconds
12560 */
12561 var defer = rest(function(func, args) {
12562 return baseDelay(func, 1, args);
12563 });
12564
12565 /**
12566 * Invokes `func` after `wait` milliseconds. Any additional arguments are
12567 * provided to `func` when it's invoked.
12568 *
12569 * @static
12570 * @memberOf _
12571 * @category Function
12572 * @param {Function} func The function to delay.
12573 * @param {number} wait The number of milliseconds to delay invocation.
12574 * @param {...*} [args] The arguments to invoke `func` with.
12575 * @returns {number} Returns the timer id.
12576 * @example
12577 *
12578 * _.delay(function(text) {
12579 * console.log(text);
12580 * }, 1000, 'later');
12581 * // => logs 'later' after one second
12582 */
12583 var delay = rest(function(func, wait, args) {
12584 return baseDelay(func, toNumber(wait) || 0, args);
12585 });
12586
12587 /**
12588 * Creates a function that invokes `func` with arguments reversed.
12589 *
12590 * @static
12591 * @memberOf _
12592 * @category Function
12593 * @param {Function} func The function to flip arguments for.
12594 * @returns {Function} Returns the new function.
12595 * @example
12596 *
12597 * var flipped = _.flip(function() {
12598 * return _.toArray(arguments);
12599 * });
12600 *
12601 * flipped('a', 'b', 'c', 'd');
12602 * // => ['d', 'c', 'b', 'a']
12603 */
12604 function flip(func) {
12605 return createWrapper(func, FLIP_FLAG);
12606 }
12607
12608 /**
12609 * Creates a function that memoizes the result of `func`. If `resolver` is
12610 * provided it determines the cache key for storing the result based on the
12611 * arguments provided to the memoized function. By default, the first argument
12612 * provided to the memoized function is used as the map cache key. The `func`
12613 * is invoked with the `this` binding of the memoized function.
12614 *
12615 * **Note:** The cache is exposed as the `cache` property on the memoized
12616 * function. Its creation may be customized by replacing the `_.memoize.Cache`
12617 * constructor with one whose instances implement the [`Map`](http://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-map-prototype-object)
12618 * method interface of `delete`, `get`, `has`, and `set`.
12619 *
12620 * @static
12621 * @memberOf _
12622 * @category Function
12623 * @param {Function} func The function to have its output memoized.
12624 * @param {Function} [resolver] The function to resolve the cache key.
12625 * @returns {Function} Returns the new memoizing function.
12626 * @example
12627 *
12628 * var object = { 'a': 1, 'b': 2 };
12629 * var other = { 'c': 3, 'd': 4 };
12630 *
12631 * var values = _.memoize(_.values);
12632 * values(object);
12633 * // => [1, 2]
12634 *
12635 * values(other);
12636 * // => [3, 4]
12637 *
12638 * object.a = 2;
12639 * values(object);
12640 * // => [1, 2]
12641 *
12642 * // Modify the result cache.
12643 * values.cache.set(object, ['a', 'b']);
12644 * values(object);
12645 * // => ['a', 'b']
12646 *
12647 * // Replace `_.memoize.Cache`.
12648 * _.memoize.Cache = WeakMap;
12649 */
12650 function memoize(func, resolver) {
12651 if (typeof func != 'function' || (resolver && typeof resolver != 'function')) {
12652 throw new TypeError(FUNC_ERROR_TEXT);
12653 }
12654 var memoized = function() {
12655 var args = arguments,
12656 key = resolver ? resolver.apply(this, args) : args[0],
12657 cache = memoized.cache;
12658
12659 if (cache.has(key)) {
12660 return cache.get(key);
12661 }
12662 var result = func.apply(this, args);
12663 memoized.cache = cache.set(key, result);
12664 return result;
12665 };
12666 memoized.cache = new memoize.Cache;
12667 return memoized;
12668 }
12669
12670 /**
12671 * Creates a function that negates the result of the predicate `func`. The
12672 * `func` predicate is invoked with the `this` binding and arguments of the
12673 * created function.
12674 *
12675 * @static
12676 * @memberOf _
12677 * @category Function
12678 * @param {Function} predicate The predicate to negate.
12679 * @returns {Function} Returns the new function.
12680 * @example
12681 *
12682 * function isEven(n) {
12683 * return n % 2 == 0;
12684 * }
12685 *
12686 * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
12687 * // => [1, 3, 5]
12688 */
12689 function negate(predicate) {
12690 if (typeof predicate != 'function') {
12691 throw new TypeError(FUNC_ERROR_TEXT);
12692 }
12693 return function() {
12694 return !predicate.apply(this, arguments);
12695 };
12696 }
12697
12698 /**
12699 * Creates a function that is restricted to invoking `func` once. Repeat calls
12700 * to the function return the value of the first invocation. The `func` is
12701 * invoked with the `this` binding and arguments of the created function.
12702 *
12703 * @static
12704 * @memberOf _
12705 * @category Function
12706 * @param {Function} func The function to restrict.
12707 * @returns {Function} Returns the new restricted function.
12708 * @example
12709 *
12710 * var initialize = _.once(createApplication);
12711 * initialize();
12712 * initialize();
12713 * // `initialize` invokes `createApplication` once
12714 */
12715 function once(func) {
12716 return before(2, func);
12717 }
12718
12719 /**
12720 * Creates a function that invokes `func` with arguments transformed by
12721 * corresponding `transforms`.
12722 *
12723 * @static
12724 * @memberOf _
12725 * @category Function
12726 * @param {Function} func The function to wrap.
12727 * @param {...(Function|Function[])} [transforms] The functions to transform
12728 * arguments, specified individually or in arrays.
12729 * @returns {Function} Returns the new function.
12730 * @example
12731 *
12732 * function doubled(n) {
12733 * return n * 2;
12734 * }
12735 *
12736 * function square(n) {
12737 * return n * n;
12738 * }
12739 *
12740 * var func = _.overArgs(function(x, y) {
12741 * return [x, y];
12742 * }, square, doubled);
12743 *
12744 * func(9, 3);
12745 * // => [81, 6]
12746 *
12747 * func(10, 5);
12748 * // => [100, 10]
12749 */
12750 var overArgs = rest(function(func, transforms) {
12751 transforms = arrayMap(baseFlatten(transforms, 1), getIteratee());
12752
12753 var funcsLength = transforms.length;
12754 return rest(function(args) {
12755 var index = -1,
12756 length = nativeMin(args.length, funcsLength);
12757
12758 while (++index < length) {
12759 args[index] = transforms[index].call(this, args[index]);
12760 }
12761 return apply(func, this, args);
12762 });
12763 });
12764
12765 /**
12766 * Creates a function that invokes `func` with `partial` arguments prepended
12767 * to those provided to the new function. This method is like `_.bind` except
12768 * it does **not** alter the `this` binding.
12769 *
12770 * The `_.partial.placeholder` value, which defaults to `_` in monolithic
12771 * builds, may be used as a placeholder for partially applied arguments.
12772 *
12773 * **Note:** This method doesn't set the "length" property of partially
12774 * applied functions.
12775 *
12776 * @static
12777 * @memberOf _
12778 * @category Function
12779 * @param {Function} func The function to partially apply arguments to.
12780 * @param {...*} [partials] The arguments to be partially applied.
12781 * @returns {Function} Returns the new partially applied function.
12782 * @example
12783 *
12784 * var greet = function(greeting, name) {
12785 * return greeting + ' ' + name;
12786 * };
12787 *
12788 * var sayHelloTo = _.partial(greet, 'hello');
12789 * sayHelloTo('fred');
12790 * // => 'hello fred'
12791 *
12792 * // Partially applied with placeholders.
12793 * var greetFred = _.partial(greet, _, 'fred');
12794 * greetFred('hi');
12795 * // => 'hi fred'
12796 */
12797 var partial = rest(function(func, partials) {
12798 var holders = replaceHolders(partials, getPlaceholder(partial));
12799 return createWrapper(func, PARTIAL_FLAG, undefined, partials, holders);
12800 });
12801
12802 /**
12803 * This method is like `_.partial` except that partially applied arguments
12804 * are appended to those provided to the new function.
12805 *
12806 * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
12807 * builds, may be used as a placeholder for partially applied arguments.
12808 *
12809 * **Note:** This method doesn't set the "length" property of partially
12810 * applied functions.
12811 *
12812 * @static
12813 * @memberOf _
12814 * @category Function
12815 * @param {Function} func The function to partially apply arguments to.
12816 * @param {...*} [partials] The arguments to be partially applied.
12817 * @returns {Function} Returns the new partially applied function.
12818 * @example
12819 *
12820 * var greet = function(greeting, name) {
12821 * return greeting + ' ' + name;
12822 * };
12823 *
12824 * var greetFred = _.partialRight(greet, 'fred');
12825 * greetFred('hi');
12826 * // => 'hi fred'
12827 *
12828 * // Partially applied with placeholders.
12829 * var sayHelloTo = _.partialRight(greet, 'hello', _);
12830 * sayHelloTo('fred');
12831 * // => 'hello fred'
12832 */
12833 var partialRight = rest(function(func, partials) {
12834 var holders = replaceHolders(partials, getPlaceholder(partialRight));
12835 return createWrapper(func, PARTIAL_RIGHT_FLAG, undefined, partials, holders);
12836 });
12837
12838 /**
12839 * Creates a function that invokes `func` with arguments arranged according
12840 * to the specified indexes where the argument value at the first index is
12841 * provided as the first argument, the argument value at the second index is
12842 * provided as the second argument, and so on.
12843 *
12844 * @static
12845 * @memberOf _
12846 * @category Function
12847 * @param {Function} func The function to rearrange arguments for.
12848 * @param {...(number|number[])} indexes The arranged argument indexes,
12849 * specified individually or in arrays.
12850 * @returns {Function} Returns the new function.
12851 * @example
12852 *
12853 * var rearged = _.rearg(function(a, b, c) {
12854 * return [a, b, c];
12855 * }, 2, 0, 1);
12856 *
12857 * rearged('b', 'c', 'a')
12858 * // => ['a', 'b', 'c']
12859 */
12860 var rearg = rest(function(func, indexes) {
12861 return createWrapper(func, REARG_FLAG, undefined, undefined, undefined, baseFlatten(indexes, 1));
12862 });
12863
12864 /**
12865 * Creates a function that invokes `func` with the `this` binding of the
12866 * created function and arguments from `start` and beyond provided as an array.
12867 *
12868 * **Note:** This method is based on the [rest parameter](https://mdn.io/rest_parameters).
12869 *
12870 * @static
12871 * @memberOf _
12872 * @category Function
12873 * @param {Function} func The function to apply a rest parameter to.
12874 * @param {number} [start=func.length-1] The start position of the rest parameter.
12875 * @returns {Function} Returns the new function.
12876 * @example
12877 *
12878 * var say = _.rest(function(what, names) {
12879 * return what + ' ' + _.initial(names).join(', ') +
12880 * (_.size(names) > 1 ? ', & ' : '') + _.last(names);
12881 * });
12882 *
12883 * say('hello', 'fred', 'barney', 'pebbles');
12884 * // => 'hello fred, barney, & pebbles'
12885 */
12886 function rest(func, start) {
12887 if (typeof func != 'function') {
12888 throw new TypeError(FUNC_ERROR_TEXT);
12889 }
12890 start = nativeMax(start === undefined ? (func.length - 1) : toInteger(start), 0);
12891 return function() {
12892 var args = arguments,
12893 index = -1,
12894 length = nativeMax(args.length - start, 0),
12895 array = Array(length);
12896
12897 while (++index < length) {
12898 array[index] = args[start + index];
12899 }
12900 switch (start) {
12901 case 0: return func.call(this, array);
12902 case 1: return func.call(this, args[0], array);
12903 case 2: return func.call(this, args[0], args[1], array);
12904 }
12905 var otherArgs = Array(start + 1);
12906 index = -1;
12907 while (++index < start) {
12908 otherArgs[index] = args[index];
12909 }
12910 otherArgs[start] = array;
12911 return apply(func, this, otherArgs);
12912 };
12913 }
12914
12915 /**
12916 * Creates a function that invokes `func` with the `this` binding of the created
12917 * function and an array of arguments much like [`Function#apply`](https://es5.github.io/#x15.3.4.3).
12918 *
12919 * **Note:** This method is based on the [spread operator](https://mdn.io/spread_operator).
12920 *
12921 * @static
12922 * @memberOf _
12923 * @category Function
12924 * @param {Function} func The function to spread arguments over.
12925 * @param {number} [start=0] The start position of the spread.
12926 * @returns {Function} Returns the new function.
12927 * @example
12928 *
12929 * var say = _.spread(function(who, what) {
12930 * return who + ' says ' + what;
12931 * });
12932 *
12933 * say(['fred', 'hello']);
12934 * // => 'fred says hello'
12935 *
12936 * var numbers = Promise.all([
12937 * Promise.resolve(40),
12938 * Promise.resolve(36)
12939 * ]);
12940 *
12941 * numbers.then(_.spread(function(x, y) {
12942 * return x + y;
12943 * }));
12944 * // => a Promise of 76
12945 */
12946 function spread(func, start) {
12947 if (typeof func != 'function') {
12948 throw new TypeError(FUNC_ERROR_TEXT);
12949 }
12950 start = start === undefined ? 0 : nativeMax(toInteger(start), 0);
12951 return rest(function(args) {
12952 var array = args[start],
12953 otherArgs = args.slice(0, start);
12954
12955 if (array) {
12956 arrayPush(otherArgs, array);
12957 }
12958 return apply(func, this, otherArgs);
12959 });
12960 }
12961
12962 /**
12963 * Creates a throttled function that only invokes `func` at most once per
12964 * every `wait` milliseconds. The throttled function comes with a `cancel`
12965 * method to cancel delayed `func` invocations and a `flush` method to
12966 * immediately invoke them. Provide an options object to indicate whether
12967 * `func` should be invoked on the leading and/or trailing edge of the `wait`
12968 * timeout. The `func` is invoked with the last arguments provided to the
12969 * throttled function. Subsequent calls to the throttled function return the
12970 * result of the last `func` invocation.
12971 *
12972 * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
12973 * on the trailing edge of the timeout only if the throttled function is
12974 * invoked more than once during the `wait` timeout.
12975 *
12976 * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
12977 * for details over the differences between `_.throttle` and `_.debounce`.
12978 *
12979 * @static
12980 * @memberOf _
12981 * @category Function
12982 * @param {Function} func The function to throttle.
12983 * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
12984 * @param {Object} [options] The options object.
12985 * @param {boolean} [options.leading=true] Specify invoking on the leading
12986 * edge of the timeout.
12987 * @param {boolean} [options.trailing=true] Specify invoking on the trailing
12988 * edge of the timeout.
12989 * @returns {Function} Returns the new throttled function.
12990 * @example
12991 *
12992 * // Avoid excessively updating the position while scrolling.
12993 * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
12994 *
12995 * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
12996 * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
12997 * jQuery(element).on('click', throttled);
12998 *
12999 * // Cancel the trailing throttled invocation.
13000 * jQuery(window).on('popstate', throttled.cancel);
13001 */
13002 function throttle(func, wait, options) {
13003 var leading = true,
13004 trailing = true;
13005
13006 if (typeof func != 'function') {
13007 throw new TypeError(FUNC_ERROR_TEXT);
13008 }
13009 if (isObject(options)) {
13010 leading = 'leading' in options ? !!options.leading : leading;
13011 trailing = 'trailing' in options ? !!options.trailing : trailing;
13012 }
13013 return debounce(func, wait, {
13014 'leading': leading,
13015 'maxWait': wait,
13016 'trailing': trailing
13017 });
13018 }
13019
13020 /**
13021 * Creates a function that accepts up to one argument, ignoring any
13022 * additional arguments.
13023 *
13024 * @static
13025 * @memberOf _
13026 * @category Function
13027 * @param {Function} func The function to cap arguments for.
13028 * @returns {Function} Returns the new function.
13029 * @example
13030 *
13031 * _.map(['6', '8', '10'], _.unary(parseInt));
13032 * // => [6, 8, 10]
13033 */
13034 function unary(func) {
13035 return ary(func, 1);
13036 }
13037
13038 /**
13039 * Creates a function that provides `value` to the wrapper function as its
13040 * first argument. Any additional arguments provided to the function are
13041 * appended to those provided to the wrapper function. The wrapper is invoked
13042 * with the `this` binding of the created function.
13043 *
13044 * @static
13045 * @memberOf _
13046 * @category Function
13047 * @param {*} value The value to wrap.
13048 * @param {Function} [wrapper=identity] The wrapper function.
13049 * @returns {Function} Returns the new function.
13050 * @example
13051 *
13052 * var p = _.wrap(_.escape, function(func, text) {
13053 * return '<p>' + func(text) + '</p>';
13054 * });
13055 *
13056 * p('fred, barney, & pebbles');
13057 * // => '<p>fred, barney, &amp; pebbles</p>'
13058 */
13059 function wrap(value, wrapper) {
13060 wrapper = wrapper == null ? identity : wrapper;
13061 return partial(wrapper, value);
13062 }
13063
13064 /*------------------------------------------------------------------------*/
13065
13066 /**
13067 * Casts `value` as an array if it's not one.
13068 *
13069 * @static
13070 * @memberOf _
13071 * @category Lang
13072 * @param {*} value The value to inspect.
13073 * @returns {Array} Returns the cast array.
13074 * @example
13075 *
13076 * _.castArray(1);
13077 * // => [1]
13078 *
13079 * _.castArray({ 'a': 1 });
13080 * // => [{ 'a': 1 }]
13081 *
13082 * _.castArray('abc');
13083 * // => ['abc']
13084 *
13085 * _.castArray(null);
13086 * // => [null]
13087 *
13088 * _.castArray(undefined);
13089 * // => [undefined]
13090 *
13091 * _.castArray();
13092 * // => []
13093 *
13094 * var array = [1, 2, 3];
13095 * console.log(_.castArray(array) === array);
13096 * // => true
13097 */
13098 function castArray() {
13099 if (!arguments.length) {
13100 return [];
13101 }
13102 var value = arguments[0];
13103 return isArray(value) ? value : [value];
13104 }
13105
13106 /**
13107 * Creates a shallow clone of `value`.
13108 *
13109 * **Note:** This method is loosely based on the
13110 * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
13111 * and supports cloning arrays, array buffers, booleans, date objects, maps,
13112 * numbers, `Object` objects, regexes, sets, strings, symbols, and typed
13113 * arrays. The own enumerable properties of `arguments` objects are cloned
13114 * as plain objects. An empty object is returned for uncloneable values such
13115 * as error objects, functions, DOM nodes, and WeakMaps.
13116 *
13117 * @static
13118 * @memberOf _
13119 * @category Lang
13120 * @param {*} value The value to clone.
13121 * @returns {*} Returns the cloned value.
13122 * @example
13123 *
13124 * var objects = [{ 'a': 1 }, { 'b': 2 }];
13125 *
13126 * var shallow = _.clone(objects);
13127 * console.log(shallow[0] === objects[0]);
13128 * // => true
13129 */
13130 function clone(value) {
13131 return baseClone(value, false, true);
13132 }
13133
13134 /**
13135 * This method is like `_.clone` except that it accepts `customizer` which
13136 * is invoked to produce the cloned value. If `customizer` returns `undefined`
13137 * cloning is handled by the method instead. The `customizer` is invoked with
13138 * up to four arguments; (value [, index|key, object, stack]).
13139 *
13140 * @static
13141 * @memberOf _
13142 * @category Lang
13143 * @param {*} value The value to clone.
13144 * @param {Function} [customizer] The function to customize cloning.
13145 * @returns {*} Returns the cloned value.
13146 * @example
13147 *
13148 * function customizer(value) {
13149 * if (_.isElement(value)) {
13150 * return value.cloneNode(false);
13151 * }
13152 * }
13153 *
13154 * var el = _.cloneWith(document.body, customizer);
13155 *
13156 * console.log(el === document.body);
13157 * // => false
13158 * console.log(el.nodeName);
13159 * // => 'BODY'
13160 * console.log(el.childNodes.length);
13161 * // => 0
13162 */
13163 function cloneWith(value, customizer) {
13164 return baseClone(value, false, true, customizer);
13165 }
13166
13167 /**
13168 * This method is like `_.clone` except that it recursively clones `value`.
13169 *
13170 * @static
13171 * @memberOf _
13172 * @category Lang
13173 * @param {*} value The value to recursively clone.
13174 * @returns {*} Returns the deep cloned value.
13175 * @example
13176 *
13177 * var objects = [{ 'a': 1 }, { 'b': 2 }];
13178 *
13179 * var deep = _.cloneDeep(objects);
13180 * console.log(deep[0] === objects[0]);
13181 * // => false
13182 */
13183 function cloneDeep(value) {
13184 return baseClone(value, true, true);
13185 }
13186
13187 /**
13188 * This method is like `_.cloneWith` except that it recursively clones `value`.
13189 *
13190 * @static
13191 * @memberOf _
13192 * @category Lang
13193 * @param {*} value The value to recursively clone.
13194 * @param {Function} [customizer] The function to customize cloning.
13195 * @returns {*} Returns the deep cloned value.
13196 * @example
13197 *
13198 * function customizer(value) {
13199 * if (_.isElement(value)) {
13200 * return value.cloneNode(true);
13201 * }
13202 * }
13203 *
13204 * var el = _.cloneDeepWith(document.body, customizer);
13205 *
13206 * console.log(el === document.body);
13207 * // => false
13208 * console.log(el.nodeName);
13209 * // => 'BODY'
13210 * console.log(el.childNodes.length);
13211 * // => 20
13212 */
13213 function cloneDeepWith(value, customizer) {
13214 return baseClone(value, true, true, customizer);
13215 }
13216
13217 /**
13218 * Performs a [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
13219 * comparison between two values to determine if they are equivalent.
13220 *
13221 * @static
13222 * @memberOf _
13223 * @category Lang
13224 * @param {*} value The value to compare.
13225 * @param {*} other The other value to compare.
13226 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
13227 * @example
13228 *
13229 * var object = { 'user': 'fred' };
13230 * var other = { 'user': 'fred' };
13231 *
13232 * _.eq(object, object);
13233 * // => true
13234 *
13235 * _.eq(object, other);
13236 * // => false
13237 *
13238 * _.eq('a', 'a');
13239 * // => true
13240 *
13241 * _.eq('a', Object('a'));
13242 * // => false
13243 *
13244 * _.eq(NaN, NaN);
13245 * // => true
13246 */
13247 function eq(value, other) {
13248 return value === other || (value !== value && other !== other);
13249 }
13250
13251 /**
13252 * Checks if `value` is greater than `other`.
13253 *
13254 * @static
13255 * @memberOf _
13256 * @category Lang
13257 * @param {*} value The value to compare.
13258 * @param {*} other The other value to compare.
13259 * @returns {boolean} Returns `true` if `value` is greater than `other`, else `false`.
13260 * @example
13261 *
13262 * _.gt(3, 1);
13263 * // => true
13264 *
13265 * _.gt(3, 3);
13266 * // => false
13267 *
13268 * _.gt(1, 3);
13269 * // => false
13270 */
13271 function gt(value, other) {
13272 return value > other;
13273 }
13274
13275 /**
13276 * Checks if `value` is greater than or equal to `other`.
13277 *
13278 * @static
13279 * @memberOf _
13280 * @category Lang
13281 * @param {*} value The value to compare.
13282 * @param {*} other The other value to compare.
13283 * @returns {boolean} Returns `true` if `value` is greater than or equal to `other`, else `false`.
13284 * @example
13285 *
13286 * _.gte(3, 1);
13287 * // => true
13288 *
13289 * _.gte(3, 3);
13290 * // => true
13291 *
13292 * _.gte(1, 3);
13293 * // => false
13294 */
13295 function gte(value, other) {
13296 return value >= other;
13297 }
13298
13299 /**
13300 * Checks if `value` is likely an `arguments` object.
13301 *
13302 * @static
13303 * @memberOf _
13304 * @category Lang
13305 * @param {*} value The value to check.
13306 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
13307 * @example
13308 *
13309 * _.isArguments(function() { return arguments; }());
13310 * // => true
13311 *
13312 * _.isArguments([1, 2, 3]);
13313 * // => false
13314 */
13315 function isArguments(value) {
13316 // Safari 8.1 incorrectly makes `arguments.callee` enumerable in strict mode.
13317 return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
13318 (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
13319 }
13320
13321 /**
13322 * Checks if `value` is classified as an `Array` object.
13323 *
13324 * @static
13325 * @memberOf _
13326 * @type {Function}
13327 * @category Lang
13328 * @param {*} value The value to check.
13329 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
13330 * @example
13331 *
13332 * _.isArray([1, 2, 3]);
13333 * // => true
13334 *
13335 * _.isArray(document.body.children);
13336 * // => false
13337 *
13338 * _.isArray('abc');
13339 * // => false
13340 *
13341 * _.isArray(_.noop);
13342 * // => false
13343 */
13344 var isArray = Array.isArray;
13345
13346 /**
13347 * Checks if `value` is classified as an `ArrayBuffer` object.
13348 *
13349 * @static
13350 * @memberOf _
13351 * @category Lang
13352 * @param {*} value The value to check.
13353 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
13354 * @example
13355 *
13356 * _.isArrayBuffer(new ArrayBuffer(2));
13357 * // => true
13358 *
13359 * _.isArrayBuffer(new Array(2));
13360 * // => false
13361 */
13362 function isArrayBuffer(value) {
13363 return isObjectLike(value) && objectToString.call(value) == arrayBufferTag;
13364 }
13365
13366 /**
13367 * Checks if `value` is array-like. A value is considered array-like if it's
13368 * not a function and has a `value.length` that's an integer greater than or
13369 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
13370 *
13371 * @static
13372 * @memberOf _
13373 * @category Lang
13374 * @param {*} value The value to check.
13375 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
13376 * @example
13377 *
13378 * _.isArrayLike([1, 2, 3]);
13379 * // => true
13380 *
13381 * _.isArrayLike(document.body.children);
13382 * // => true
13383 *
13384 * _.isArrayLike('abc');
13385 * // => true
13386 *
13387 * _.isArrayLike(_.noop);
13388 * // => false
13389 */
13390 function isArrayLike(value) {
13391 return value != null && isLength(getLength(value)) && !isFunction(value);
13392 }
13393
13394 /**
13395 * This method is like `_.isArrayLike` except that it also checks if `value`
13396 * is an object.
13397 *
13398 * @static
13399 * @memberOf _
13400 * @category Lang
13401 * @param {*} value The value to check.
13402 * @returns {boolean} Returns `true` if `value` is an array-like object, else `false`.
13403 * @example
13404 *
13405 * _.isArrayLikeObject([1, 2, 3]);
13406 * // => true
13407 *
13408 * _.isArrayLikeObject(document.body.children);
13409 * // => true
13410 *
13411 * _.isArrayLikeObject('abc');
13412 * // => false
13413 *
13414 * _.isArrayLikeObject(_.noop);
13415 * // => false
13416 */
13417 function isArrayLikeObject(value) {
13418 return isObjectLike(value) && isArrayLike(value);
13419 }
13420
13421 /**
13422 * Checks if `value` is classified as a boolean primitive or object.
13423 *
13424 * @static
13425 * @memberOf _
13426 * @category Lang
13427 * @param {*} value The value to check.
13428 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
13429 * @example
13430 *
13431 * _.isBoolean(false);
13432 * // => true
13433 *
13434 * _.isBoolean(null);
13435 * // => false
13436 */
13437 function isBoolean(value) {
13438 return value === true || value === false ||
13439 (isObjectLike(value) && objectToString.call(value) == boolTag);
13440 }
13441
13442 /**
13443 * Checks if `value` is a buffer.
13444 *
13445 * @static
13446 * @memberOf _
13447 * @category Lang
13448 * @param {*} value The value to check.
13449 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
13450 * @example
13451 *
13452 * _.isBuffer(new Buffer(2));
13453 * // => true
13454 *
13455 * _.isBuffer(new Uint8Array(2));
13456 * // => false
13457 */
13458 var isBuffer = !Buffer ? constant(false) : function(value) {
13459 return value instanceof Buffer;
13460 };
13461
13462 /**
13463 * Checks if `value` is classified as a `Date` object.
13464 *
13465 * @static
13466 * @memberOf _
13467 * @category Lang
13468 * @param {*} value The value to check.
13469 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
13470 * @example
13471 *
13472 * _.isDate(new Date);
13473 * // => true
13474 *
13475 * _.isDate('Mon April 23 2012');
13476 * // => false
13477 */
13478 function isDate(value) {
13479 return isObjectLike(value) && objectToString.call(value) == dateTag;
13480 }
13481
13482 /**
13483 * Checks if `value` is likely a DOM element.
13484 *
13485 * @static
13486 * @memberOf _
13487 * @category Lang
13488 * @param {*} value The value to check.
13489 * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
13490 * @example
13491 *
13492 * _.isElement(document.body);
13493 * // => true
13494 *
13495 * _.isElement('<body>');
13496 * // => false
13497 */
13498 function isElement(value) {
13499 return !!value && value.nodeType === 1 && isObjectLike(value) && !isPlainObject(value);
13500 }
13501
13502 /**
13503 * Checks if `value` is an empty collection or object. A value is considered
13504 * empty if it's an `arguments` object, array, string, or jQuery-like collection
13505 * with a length of `0` or has no own enumerable properties.
13506 *
13507 * @static
13508 * @memberOf _
13509 * @category Lang
13510 * @param {*} value The value to check.
13511 * @returns {boolean} Returns `true` if `value` is empty, else `false`.
13512 * @example
13513 *
13514 * _.isEmpty(null);
13515 * // => true
13516 *
13517 * _.isEmpty(true);
13518 * // => true
13519 *
13520 * _.isEmpty(1);
13521 * // => true
13522 *
13523 * _.isEmpty([1, 2, 3]);
13524 * // => false
13525 *
13526 * _.isEmpty({ 'a': 1 });
13527 * // => false
13528 */
13529 function isEmpty(value) {
13530 if (isArrayLike(value) &&
13531 (isArray(value) || isString(value) ||
13532 isFunction(value.splice) || isArguments(value))) {
13533 return !value.length;
13534 }
13535 for (var key in value) {
13536 if (hasOwnProperty.call(value, key)) {
13537 return false;
13538 }
13539 }
13540 return true;
13541 }
13542
13543 /**
13544 * Performs a deep comparison between two values to determine if they are
13545 * equivalent.
13546 *
13547 * **Note:** This method supports comparing arrays, array buffers, booleans,
13548 * date objects, error objects, maps, numbers, `Object` objects, regexes,
13549 * sets, strings, symbols, and typed arrays. `Object` objects are compared
13550 * by their own, not inherited, enumerable properties. Functions and DOM
13551 * nodes are **not** supported.
13552 *
13553 * @static
13554 * @memberOf _
13555 * @category Lang
13556 * @param {*} value The value to compare.
13557 * @param {*} other The other value to compare.
13558 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
13559 * @example
13560 *
13561 * var object = { 'user': 'fred' };
13562 * var other = { 'user': 'fred' };
13563 *
13564 * _.isEqual(object, other);
13565 * // => true
13566 *
13567 * object === other;
13568 * // => false
13569 */
13570 function isEqual(value, other) {
13571 return baseIsEqual(value, other);
13572 }
13573
13574 /**
13575 * This method is like `_.isEqual` except that it accepts `customizer` which
13576 * is invoked to compare values. If `customizer` returns `undefined` comparisons
13577 * are handled by the method instead. The `customizer` is invoked with up to
13578 * six arguments: (objValue, othValue [, index|key, object, other, stack]).
13579 *
13580 * @static
13581 * @memberOf _
13582 * @category Lang
13583 * @param {*} value The value to compare.
13584 * @param {*} other The other value to compare.
13585 * @param {Function} [customizer] The function to customize comparisons.
13586 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
13587 * @example
13588 *
13589 * function isGreeting(value) {
13590 * return /^h(?:i|ello)$/.test(value);
13591 * }
13592 *
13593 * function customizer(objValue, othValue) {
13594 * if (isGreeting(objValue) && isGreeting(othValue)) {
13595 * return true;
13596 * }
13597 * }
13598 *
13599 * var array = ['hello', 'goodbye'];
13600 * var other = ['hi', 'goodbye'];
13601 *
13602 * _.isEqualWith(array, other, customizer);
13603 * // => true
13604 */
13605 function isEqualWith(value, other, customizer) {
13606 customizer = typeof customizer == 'function' ? customizer : undefined;
13607 var result = customizer ? customizer(value, other) : undefined;
13608 return result === undefined ? baseIsEqual(value, other, customizer) : !!result;
13609 }
13610
13611 /**
13612 * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
13613 * `SyntaxError`, `TypeError`, or `URIError` object.
13614 *
13615 * @static
13616 * @memberOf _
13617 * @category Lang
13618 * @param {*} value The value to check.
13619 * @returns {boolean} Returns `true` if `value` is an error object, else `false`.
13620 * @example
13621 *
13622 * _.isError(new Error);
13623 * // => true
13624 *
13625 * _.isError(Error);
13626 * // => false
13627 */
13628 function isError(value) {
13629 if (!isObjectLike(value)) {
13630 return false;
13631 }
13632 return (objectToString.call(value) == errorTag) ||
13633 (typeof value.message == 'string' && typeof value.name == 'string');
13634 }
13635
13636 /**
13637 * Checks if `value` is a finite primitive number.
13638 *
13639 * **Note:** This method is based on [`Number.isFinite`](https://mdn.io/Number/isFinite).
13640 *
13641 * @static
13642 * @memberOf _
13643 * @category Lang
13644 * @param {*} value The value to check.
13645 * @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
13646 * @example
13647 *
13648 * _.isFinite(3);
13649 * // => true
13650 *
13651 * _.isFinite(Number.MAX_VALUE);
13652 * // => true
13653 *
13654 * _.isFinite(3.14);
13655 * // => true
13656 *
13657 * _.isFinite(Infinity);
13658 * // => false
13659 */
13660 function isFinite(value) {
13661 return typeof value == 'number' && nativeIsFinite(value);
13662 }
13663
13664 /**
13665 * Checks if `value` is classified as a `Function` object.
13666 *
13667 * @static
13668 * @memberOf _
13669 * @category Lang
13670 * @param {*} value The value to check.
13671 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
13672 * @example
13673 *
13674 * _.isFunction(_);
13675 * // => true
13676 *
13677 * _.isFunction(/abc/);
13678 * // => false
13679 */
13680 function isFunction(value) {
13681 // The use of `Object#toString` avoids issues with the `typeof` operator
13682 // in Safari 8 which returns 'object' for typed array and weak map constructors,
13683 // and PhantomJS 1.9 which returns 'function' for `NodeList` instances.
13684 var tag = isObject(value) ? objectToString.call(value) : '';
13685 return tag == funcTag || tag == genTag;
13686 }
13687
13688 /**
13689 * Checks if `value` is an integer.
13690 *
13691 * **Note:** This method is based on [`Number.isInteger`](https://mdn.io/Number/isInteger).
13692 *
13693 * @static
13694 * @memberOf _
13695 * @category Lang
13696 * @param {*} value The value to check.
13697 * @returns {boolean} Returns `true` if `value` is an integer, else `false`.
13698 * @example
13699 *
13700 * _.isInteger(3);
13701 * // => true
13702 *
13703 * _.isInteger(Number.MIN_VALUE);
13704 * // => false
13705 *
13706 * _.isInteger(Infinity);
13707 * // => false
13708 *
13709 * _.isInteger('3');
13710 * // => false
13711 */
13712 function isInteger(value) {
13713 return typeof value == 'number' && value == toInteger(value);
13714 }
13715
13716 /**
13717 * Checks if `value` is a valid array-like length.
13718 *
13719 * **Note:** This function is loosely based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
13720 *
13721 * @static
13722 * @memberOf _
13723 * @category Lang
13724 * @param {*} value The value to check.
13725 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
13726 * @example
13727 *
13728 * _.isLength(3);
13729 * // => true
13730 *
13731 * _.isLength(Number.MIN_VALUE);
13732 * // => false
13733 *
13734 * _.isLength(Infinity);
13735 * // => false
13736 *
13737 * _.isLength('3');
13738 * // => false
13739 */
13740 function isLength(value) {
13741 return typeof value == 'number' &&
13742 value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
13743 }
13744
13745 /**
13746 * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
13747 * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
13748 *
13749 * @static
13750 * @memberOf _
13751 * @category Lang
13752 * @param {*} value The value to check.
13753 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
13754 * @example
13755 *
13756 * _.isObject({});
13757 * // => true
13758 *
13759 * _.isObject([1, 2, 3]);
13760 * // => true
13761 *
13762 * _.isObject(_.noop);
13763 * // => true
13764 *
13765 * _.isObject(null);
13766 * // => false
13767 */
13768 function isObject(value) {
13769 var type = typeof value;
13770 return !!value && (type == 'object' || type == 'function');
13771 }
13772
13773 /**
13774 * Checks if `value` is object-like. A value is object-like if it's not `null`
13775 * and has a `typeof` result of "object".
13776 *
13777 * @static
13778 * @memberOf _
13779 * @category Lang
13780 * @param {*} value The value to check.
13781 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
13782 * @example
13783 *
13784 * _.isObjectLike({});
13785 * // => true
13786 *
13787 * _.isObjectLike([1, 2, 3]);
13788 * // => true
13789 *
13790 * _.isObjectLike(_.noop);
13791 * // => false
13792 *
13793 * _.isObjectLike(null);
13794 * // => false
13795 */
13796 function isObjectLike(value) {
13797 return !!value && typeof value == 'object';
13798 }
13799
13800 /**
13801 * Checks if `value` is classified as a `Map` object.
13802 *
13803 * @static
13804 * @memberOf _
13805 * @category Lang
13806 * @param {*} value The value to check.
13807 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
13808 * @example
13809 *
13810 * _.isMap(new Map);
13811 * // => true
13812 *
13813 * _.isMap(new WeakMap);
13814 * // => false
13815 */
13816 function isMap(value) {
13817 return isObjectLike(value) && getTag(value) == mapTag;
13818 }
13819
13820 /**
13821 * Performs a partial deep comparison between `object` and `source` to
13822 * determine if `object` contains equivalent property values. This method is
13823 * equivalent to a `_.matches` function when `source` is partially applied.
13824 *
13825 * **Note:** This method supports comparing the same values as `_.isEqual`.
13826 *
13827 * @static
13828 * @memberOf _
13829 * @category Lang
13830 * @param {Object} object The object to inspect.
13831 * @param {Object} source The object of property values to match.
13832 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
13833 * @example
13834 *
13835 * var object = { 'user': 'fred', 'age': 40 };
13836 *
13837 * _.isMatch(object, { 'age': 40 });
13838 * // => true
13839 *
13840 * _.isMatch(object, { 'age': 36 });
13841 * // => false
13842 */
13843 function isMatch(object, source) {
13844 return object === source || baseIsMatch(object, source, getMatchData(source));
13845 }
13846
13847 /**
13848 * This method is like `_.isMatch` except that it accepts `customizer` which
13849 * is invoked to compare values. If `customizer` returns `undefined` comparisons
13850 * are handled by the method instead. The `customizer` is invoked with five
13851 * arguments: (objValue, srcValue, index|key, object, source).
13852 *
13853 * @static
13854 * @memberOf _
13855 * @category Lang
13856 * @param {Object} object The object to inspect.
13857 * @param {Object} source The object of property values to match.
13858 * @param {Function} [customizer] The function to customize comparisons.
13859 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
13860 * @example
13861 *
13862 * function isGreeting(value) {
13863 * return /^h(?:i|ello)$/.test(value);
13864 * }
13865 *
13866 * function customizer(objValue, srcValue) {
13867 * if (isGreeting(objValue) && isGreeting(srcValue)) {
13868 * return true;
13869 * }
13870 * }
13871 *
13872 * var object = { 'greeting': 'hello' };
13873 * var source = { 'greeting': 'hi' };
13874 *
13875 * _.isMatchWith(object, source, customizer);
13876 * // => true
13877 */
13878 function isMatchWith(object, source, customizer) {
13879 customizer = typeof customizer == 'function' ? customizer : undefined;
13880 return baseIsMatch(object, source, getMatchData(source), customizer);
13881 }
13882
13883 /**
13884 * Checks if `value` is `NaN`.
13885 *
13886 * **Note:** This method is not the same as [`isNaN`](https://es5.github.io/#x15.1.2.4)
13887 * which returns `true` for `undefined` and other non-numeric values.
13888 *
13889 * @static
13890 * @memberOf _
13891 * @category Lang
13892 * @param {*} value The value to check.
13893 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
13894 * @example
13895 *
13896 * _.isNaN(NaN);
13897 * // => true
13898 *
13899 * _.isNaN(new Number(NaN));
13900 * // => true
13901 *
13902 * isNaN(undefined);
13903 * // => true
13904 *
13905 * _.isNaN(undefined);
13906 * // => false
13907 */
13908 function isNaN(value) {
13909 // An `NaN` primitive is the only value that is not equal to itself.
13910 // Perform the `toStringTag` check first to avoid errors with some ActiveX objects in IE.
13911 return isNumber(value) && value != +value;
13912 }
13913
13914 /**
13915 * Checks if `value` is a native function.
13916 *
13917 * @static
13918 * @memberOf _
13919 * @category Lang
13920 * @param {*} value The value to check.
13921 * @returns {boolean} Returns `true` if `value` is a native function, else `false`.
13922 * @example
13923 *
13924 * _.isNative(Array.prototype.push);
13925 * // => true
13926 *
13927 * _.isNative(_);
13928 * // => false
13929 */
13930 function isNative(value) {
13931 if (value == null) {
13932 return false;
13933 }
13934 if (isFunction(value)) {
13935 return reIsNative.test(funcToString.call(value));
13936 }
13937 return isObjectLike(value) &&
13938 (isHostObject(value) ? reIsNative : reIsHostCtor).test(value);
13939 }
13940
13941 /**
13942 * Checks if `value` is `null`.
13943 *
13944 * @static
13945 * @memberOf _
13946 * @category Lang
13947 * @param {*} value The value to check.
13948 * @returns {boolean} Returns `true` if `value` is `null`, else `false`.
13949 * @example
13950 *
13951 * _.isNull(null);
13952 * // => true
13953 *
13954 * _.isNull(void 0);
13955 * // => false
13956 */
13957 function isNull(value) {
13958 return value === null;
13959 }
13960
13961 /**
13962 * Checks if `value` is `null` or `undefined`.
13963 *
13964 * @static
13965 * @memberOf _
13966 * @category Lang
13967 * @param {*} value The value to check.
13968 * @returns {boolean} Returns `true` if `value` is nullish, else `false`.
13969 * @example
13970 *
13971 * _.isNil(null);
13972 * // => true
13973 *
13974 * _.isNil(void 0);
13975 * // => true
13976 *
13977 * _.isNil(NaN);
13978 * // => false
13979 */
13980 function isNil(value) {
13981 return value == null;
13982 }
13983
13984 /**
13985 * Checks if `value` is classified as a `Number` primitive or object.
13986 *
13987 * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified
13988 * as numbers, use the `_.isFinite` method.
13989 *
13990 * @static
13991 * @memberOf _
13992 * @category Lang
13993 * @param {*} value The value to check.
13994 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
13995 * @example
13996 *
13997 * _.isNumber(3);
13998 * // => true
13999 *
14000 * _.isNumber(Number.MIN_VALUE);
14001 * // => true
14002 *
14003 * _.isNumber(Infinity);
14004 * // => true
14005 *
14006 * _.isNumber('3');
14007 * // => false
14008 */
14009 function isNumber(value) {
14010 return typeof value == 'number' ||
14011 (isObjectLike(value) && objectToString.call(value) == numberTag);
14012 }
14013
14014 /**
14015 * Checks if `value` is a plain object, that is, an object created by the
14016 * `Object` constructor or one with a `[[Prototype]]` of `null`.
14017 *
14018 * @static
14019 * @memberOf _
14020 * @category Lang
14021 * @param {*} value The value to check.
14022 * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
14023 * @example
14024 *
14025 * function Foo() {
14026 * this.a = 1;
14027 * }
14028 *
14029 * _.isPlainObject(new Foo);
14030 * // => false
14031 *
14032 * _.isPlainObject([1, 2, 3]);
14033 * // => false
14034 *
14035 * _.isPlainObject({ 'x': 0, 'y': 0 });
14036 * // => true
14037 *
14038 * _.isPlainObject(Object.create(null));
14039 * // => true
14040 */
14041 function isPlainObject(value) {
14042 if (!isObjectLike(value) ||
14043 objectToString.call(value) != objectTag || isHostObject(value)) {
14044 return false;
14045 }
14046 var proto = getPrototypeOf(value);
14047 if (proto === null) {
14048 return true;
14049 }
14050 var Ctor = proto.constructor;
14051 return (typeof Ctor == 'function' &&
14052 Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
14053 }
14054
14055 /**
14056 * Checks if `value` is classified as a `RegExp` object.
14057 *
14058 * @static
14059 * @memberOf _
14060 * @category Lang
14061 * @param {*} value The value to check.
14062 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
14063 * @example
14064 *
14065 * _.isRegExp(/abc/);
14066 * // => true
14067 *
14068 * _.isRegExp('/abc/');
14069 * // => false
14070 */
14071 function isRegExp(value) {
14072 return isObject(value) && objectToString.call(value) == regexpTag;
14073 }
14074
14075 /**
14076 * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754
14077 * double precision number which isn't the result of a rounded unsafe integer.
14078 *
14079 * **Note:** This method is based on [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger).
14080 *
14081 * @static
14082 * @memberOf _
14083 * @category Lang
14084 * @param {*} value The value to check.
14085 * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`.
14086 * @example
14087 *
14088 * _.isSafeInteger(3);
14089 * // => true
14090 *
14091 * _.isSafeInteger(Number.MIN_VALUE);
14092 * // => false
14093 *
14094 * _.isSafeInteger(Infinity);
14095 * // => false
14096 *
14097 * _.isSafeInteger('3');
14098 * // => false
14099 */
14100 function isSafeInteger(value) {
14101 return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER;
14102 }
14103
14104 /**
14105 * Checks if `value` is classified as a `Set` object.
14106 *
14107 * @static
14108 * @memberOf _
14109 * @category Lang
14110 * @param {*} value The value to check.
14111 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
14112 * @example
14113 *
14114 * _.isSet(new Set);
14115 * // => true
14116 *
14117 * _.isSet(new WeakSet);
14118 * // => false
14119 */
14120 function isSet(value) {
14121 return isObjectLike(value) && getTag(value) == setTag;
14122 }
14123
14124 /**
14125 * Checks if `value` is classified as a `String` primitive or object.
14126 *
14127 * @static
14128 * @memberOf _
14129 * @category Lang
14130 * @param {*} value The value to check.
14131 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
14132 * @example
14133 *
14134 * _.isString('abc');
14135 * // => true
14136 *
14137 * _.isString(1);
14138 * // => false
14139 */
14140 function isString(value) {
14141 return typeof value == 'string' ||
14142 (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag);
14143 }
14144
14145 /**
14146 * Checks if `value` is classified as a `Symbol` primitive or object.
14147 *
14148 * @static
14149 * @memberOf _
14150 * @category Lang
14151 * @param {*} value The value to check.
14152 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
14153 * @example
14154 *
14155 * _.isSymbol(Symbol.iterator);
14156 * // => true
14157 *
14158 * _.isSymbol('abc');
14159 * // => false
14160 */
14161 function isSymbol(value) {
14162 return typeof value == 'symbol' ||
14163 (isObjectLike(value) && objectToString.call(value) == symbolTag);
14164 }
14165
14166 /**
14167 * Checks if `value` is classified as a typed array.
14168 *
14169 * @static
14170 * @memberOf _
14171 * @category Lang
14172 * @param {*} value The value to check.
14173 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
14174 * @example
14175 *
14176 * _.isTypedArray(new Uint8Array);
14177 * // => true
14178 *
14179 * _.isTypedArray([]);
14180 * // => false
14181 */
14182 function isTypedArray(value) {
14183 return isObjectLike(value) &&
14184 isLength(value.length) && !!typedArrayTags[objectToString.call(value)];
14185 }
14186
14187 /**
14188 * Checks if `value` is `undefined`.
14189 *
14190 * @static
14191 * @memberOf _
14192 * @category Lang
14193 * @param {*} value The value to check.
14194 * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
14195 * @example
14196 *
14197 * _.isUndefined(void 0);
14198 * // => true
14199 *
14200 * _.isUndefined(null);
14201 * // => false
14202 */
14203 function isUndefined(value) {
14204 return value === undefined;
14205 }
14206
14207 /**
14208 * Checks if `value` is classified as a `WeakMap` object.
14209 *
14210 * @static
14211 * @memberOf _
14212 * @category Lang
14213 * @param {*} value The value to check.
14214 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
14215 * @example
14216 *
14217 * _.isWeakMap(new WeakMap);
14218 * // => true
14219 *
14220 * _.isWeakMap(new Map);
14221 * // => false
14222 */
14223 function isWeakMap(value) {
14224 return isObjectLike(value) && getTag(value) == weakMapTag;
14225 }
14226
14227 /**
14228 * Checks if `value` is classified as a `WeakSet` object.
14229 *
14230 * @static
14231 * @memberOf _
14232 * @category Lang
14233 * @param {*} value The value to check.
14234 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
14235 * @example
14236 *
14237 * _.isWeakSet(new WeakSet);
14238 * // => true
14239 *
14240 * _.isWeakSet(new Set);
14241 * // => false
14242 */
14243 function isWeakSet(value) {
14244 return isObjectLike(value) && objectToString.call(value) == weakSetTag;
14245 }
14246
14247 /**
14248 * Checks if `value` is less than `other`.
14249 *
14250 * @static
14251 * @memberOf _
14252 * @category Lang
14253 * @param {*} value The value to compare.
14254 * @param {*} other The other value to compare.
14255 * @returns {boolean} Returns `true` if `value` is less than `other`, else `false`.
14256 * @example
14257 *
14258 * _.lt(1, 3);
14259 * // => true
14260 *
14261 * _.lt(3, 3);
14262 * // => false
14263 *
14264 * _.lt(3, 1);
14265 * // => false
14266 */
14267 function lt(value, other) {
14268 return value < other;
14269 }
14270
14271 /**
14272 * Checks if `value` is less than or equal to `other`.
14273 *
14274 * @static
14275 * @memberOf _
14276 * @category Lang
14277 * @param {*} value The value to compare.
14278 * @param {*} other The other value to compare.
14279 * @returns {boolean} Returns `true` if `value` is less than or equal to `other`, else `false`.
14280 * @example
14281 *
14282 * _.lte(1, 3);
14283 * // => true
14284 *
14285 * _.lte(3, 3);
14286 * // => true
14287 *
14288 * _.lte(3, 1);
14289 * // => false
14290 */
14291 function lte(value, other) {
14292 return value <= other;
14293 }
14294
14295 /**
14296 * Converts `value` to an array.
14297 *
14298 * @static
14299 * @memberOf _
14300 * @category Lang
14301 * @param {*} value The value to convert.
14302 * @returns {Array} Returns the converted array.
14303 * @example
14304 *
14305 * _.toArray({ 'a': 1, 'b': 2 });
14306 * // => [1, 2]
14307 *
14308 * _.toArray('abc');
14309 * // => ['a', 'b', 'c']
14310 *
14311 * _.toArray(1);
14312 * // => []
14313 *
14314 * _.toArray(null);
14315 * // => []
14316 */
14317 function toArray(value) {
14318 if (!value) {
14319 return [];
14320 }
14321 if (isArrayLike(value)) {
14322 return isString(value) ? stringToArray(value) : copyArray(value);
14323 }
14324 if (iteratorSymbol && value[iteratorSymbol]) {
14325 return iteratorToArray(value[iteratorSymbol]());
14326 }
14327 var tag = getTag(value),
14328 func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values);
14329
14330 return func(value);
14331 }
14332
14333 /**
14334 * Converts `value` to an integer.
14335 *
14336 * **Note:** This function is loosely based on [`ToInteger`](http://www.ecma-international.org/ecma-262/6.0/#sec-tointeger).
14337 *
14338 * @static
14339 * @memberOf _
14340 * @category Lang
14341 * @param {*} value The value to convert.
14342 * @returns {number} Returns the converted integer.
14343 * @example
14344 *
14345 * _.toInteger(3);
14346 * // => 3
14347 *
14348 * _.toInteger(Number.MIN_VALUE);
14349 * // => 0
14350 *
14351 * _.toInteger(Infinity);
14352 * // => 1.7976931348623157e+308
14353 *
14354 * _.toInteger('3');
14355 * // => 3
14356 */
14357 function toInteger(value) {
14358 if (!value) {
14359 return value === 0 ? value : 0;
14360 }
14361 value = toNumber(value);
14362 if (value === INFINITY || value === -INFINITY) {
14363 var sign = (value < 0 ? -1 : 1);
14364 return sign * MAX_INTEGER;
14365 }
14366 var remainder = value % 1;
14367 return value === value ? (remainder ? value - remainder : value) : 0;
14368 }
14369
14370 /**
14371 * Converts `value` to an integer suitable for use as the length of an
14372 * array-like object.
14373 *
14374 * **Note:** This method is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
14375 *
14376 * @static
14377 * @memberOf _
14378 * @category Lang
14379 * @param {*} value The value to convert.
14380 * @returns {number} Returns the converted integer.
14381 * @example
14382 *
14383 * _.toLength(3);
14384 * // => 3
14385 *
14386 * _.toLength(Number.MIN_VALUE);
14387 * // => 0
14388 *
14389 * _.toLength(Infinity);
14390 * // => 4294967295
14391 *
14392 * _.toLength('3');
14393 * // => 3
14394 */
14395 function toLength(value) {
14396 return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0;
14397 }
14398
14399 /**
14400 * Converts `value` to a number.
14401 *
14402 * @static
14403 * @memberOf _
14404 * @category Lang
14405 * @param {*} value The value to process.
14406 * @returns {number} Returns the number.
14407 * @example
14408 *
14409 * _.toNumber(3);
14410 * // => 3
14411 *
14412 * _.toNumber(Number.MIN_VALUE);
14413 * // => 5e-324
14414 *
14415 * _.toNumber(Infinity);
14416 * // => Infinity
14417 *
14418 * _.toNumber('3');
14419 * // => 3
14420 */
14421 function toNumber(value) {
14422 if (isObject(value)) {
14423 var other = isFunction(value.valueOf) ? value.valueOf() : value;
14424 value = isObject(other) ? (other + '') : other;
14425 }
14426 if (typeof value != 'string') {
14427 return value === 0 ? value : +value;
14428 }
14429 value = value.replace(reTrim, '');
14430 var isBinary = reIsBinary.test(value);
14431 return (isBinary || reIsOctal.test(value))
14432 ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
14433 : (reIsBadHex.test(value) ? NAN : +value);
14434 }
14435
14436 /**
14437 * Converts `value` to a plain object flattening inherited enumerable
14438 * properties of `value` to own properties of the plain object.
14439 *
14440 * @static
14441 * @memberOf _
14442 * @category Lang
14443 * @param {*} value The value to convert.
14444 * @returns {Object} Returns the converted plain object.
14445 * @example
14446 *
14447 * function Foo() {
14448 * this.b = 2;
14449 * }
14450 *
14451 * Foo.prototype.c = 3;
14452 *
14453 * _.assign({ 'a': 1 }, new Foo);
14454 * // => { 'a': 1, 'b': 2 }
14455 *
14456 * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
14457 * // => { 'a': 1, 'b': 2, 'c': 3 }
14458 */
14459 function toPlainObject(value) {
14460 return copyObject(value, keysIn(value));
14461 }
14462
14463 /**
14464 * Converts `value` to a safe integer. A safe integer can be compared and
14465 * represented correctly.
14466 *
14467 * @static
14468 * @memberOf _
14469 * @category Lang
14470 * @param {*} value The value to convert.
14471 * @returns {number} Returns the converted integer.
14472 * @example
14473 *
14474 * _.toSafeInteger(3);
14475 * // => 3
14476 *
14477 * _.toSafeInteger(Number.MIN_VALUE);
14478 * // => 0
14479 *
14480 * _.toSafeInteger(Infinity);
14481 * // => 9007199254740991
14482 *
14483 * _.toSafeInteger('3');
14484 * // => 3
14485 */
14486 function toSafeInteger(value) {
14487 return baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER);
14488 }
14489
14490 /**
14491 * Converts `value` to a string if it's not one. An empty string is returned
14492 * for `null` and `undefined` values. The sign of `-0` is preserved.
14493 *
14494 * @static
14495 * @memberOf _
14496 * @category Lang
14497 * @param {*} value The value to process.
14498 * @returns {string} Returns the string.
14499 * @example
14500 *
14501 * _.toString(null);
14502 * // => ''
14503 *
14504 * _.toString(-0);
14505 * // => '-0'
14506 *
14507 * _.toString([1, 2, 3]);
14508 * // => '1,2,3'
14509 */
14510 function toString(value) {
14511 // Exit early for strings to avoid a performance hit in some environments.
14512 if (typeof value == 'string') {
14513 return value;
14514 }
14515 if (value == null) {
14516 return '';
14517 }
14518 if (isSymbol(value)) {
14519 return symbolToString ? symbolToString.call(value) : '';
14520 }
14521 var result = (value + '');
14522 return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
14523 }
14524
14525 /*------------------------------------------------------------------------*/
14526
14527 /**
14528 * Assigns own enumerable properties of source objects to the destination
14529 * object. Source objects are applied from left to right. Subsequent sources
14530 * overwrite property assignments of previous sources.
14531 *
14532 * **Note:** This method mutates `object` and is loosely based on
14533 * [`Object.assign`](https://mdn.io/Object/assign).
14534 *
14535 * @static
14536 * @memberOf _
14537 * @category Object
14538 * @param {Object} object The destination object.
14539 * @param {...Object} [sources] The source objects.
14540 * @returns {Object} Returns `object`.
14541 * @example
14542 *
14543 * function Foo() {
14544 * this.c = 3;
14545 * }
14546 *
14547 * function Bar() {
14548 * this.e = 5;
14549 * }
14550 *
14551 * Foo.prototype.d = 4;
14552 * Bar.prototype.f = 6;
14553 *
14554 * _.assign({ 'a': 1 }, new Foo, new Bar);
14555 * // => { 'a': 1, 'c': 3, 'e': 5 }
14556 */
14557 var assign = createAssigner(function(object, source) {
14558 if (nonEnumShadows || isPrototype(source) || isArrayLike(source)) {
14559 copyObject(source, keys(source), object);
14560 return;
14561 }
14562 for (var key in source) {
14563 if (hasOwnProperty.call(source, key)) {
14564 assignValue(object, key, source[key]);
14565 }
14566 }
14567 });
14568
14569 /**
14570 * This method is like `_.assign` except that it iterates over own and
14571 * inherited source properties.
14572 *
14573 * **Note:** This method mutates `object`.
14574 *
14575 * @static
14576 * @memberOf _
14577 * @alias extend
14578 * @category Object
14579 * @param {Object} object The destination object.
14580 * @param {...Object} [sources] The source objects.
14581 * @returns {Object} Returns `object`.
14582 * @example
14583 *
14584 * function Foo() {
14585 * this.b = 2;
14586 * }
14587 *
14588 * function Bar() {
14589 * this.d = 4;
14590 * }
14591 *
14592 * Foo.prototype.c = 3;
14593 * Bar.prototype.e = 5;
14594 *
14595 * _.assignIn({ 'a': 1 }, new Foo, new Bar);
14596 * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5 }
14597 */
14598 var assignIn = createAssigner(function(object, source) {
14599 if (nonEnumShadows || isPrototype(source) || isArrayLike(source)) {
14600 copyObject(source, keysIn(source), object);
14601 return;
14602 }
14603 for (var key in source) {
14604 assignValue(object, key, source[key]);
14605 }
14606 });
14607
14608 /**
14609 * This method is like `_.assignIn` except that it accepts `customizer` which
14610 * is invoked to produce the assigned values. If `customizer` returns `undefined`
14611 * assignment is handled by the method instead. The `customizer` is invoked
14612 * with five arguments: (objValue, srcValue, key, object, source).
14613 *
14614 * **Note:** This method mutates `object`.
14615 *
14616 * @static
14617 * @memberOf _
14618 * @alias extendWith
14619 * @category Object
14620 * @param {Object} object The destination object.
14621 * @param {...Object} sources The source objects.
14622 * @param {Function} [customizer] The function to customize assigned values.
14623 * @returns {Object} Returns `object`.
14624 * @example
14625 *
14626 * function customizer(objValue, srcValue) {
14627 * return _.isUndefined(objValue) ? srcValue : objValue;
14628 * }
14629 *
14630 * var defaults = _.partialRight(_.assignInWith, customizer);
14631 *
14632 * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
14633 * // => { 'a': 1, 'b': 2 }
14634 */
14635 var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {
14636 copyObjectWith(source, keysIn(source), object, customizer);
14637 });
14638
14639 /**
14640 * This method is like `_.assign` except that it accepts `customizer` which
14641 * is invoked to produce the assigned values. If `customizer` returns `undefined`
14642 * assignment is handled by the method instead. The `customizer` is invoked
14643 * with five arguments: (objValue, srcValue, key, object, source).
14644 *
14645 * **Note:** This method mutates `object`.
14646 *
14647 * @static
14648 * @memberOf _
14649 * @category Object
14650 * @param {Object} object The destination object.
14651 * @param {...Object} sources The source objects.
14652 * @param {Function} [customizer] The function to customize assigned values.
14653 * @returns {Object} Returns `object`.
14654 * @example
14655 *
14656 * function customizer(objValue, srcValue) {
14657 * return _.isUndefined(objValue) ? srcValue : objValue;
14658 * }
14659 *
14660 * var defaults = _.partialRight(_.assignWith, customizer);
14661 *
14662 * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
14663 * // => { 'a': 1, 'b': 2 }
14664 */
14665 var assignWith = createAssigner(function(object, source, srcIndex, customizer) {
14666 copyObjectWith(source, keys(source), object, customizer);
14667 });
14668
14669 /**
14670 * Creates an array of values corresponding to `paths` of `object`.
14671 *
14672 * @static
14673 * @memberOf _
14674 * @category Object
14675 * @param {Object} object The object to iterate over.
14676 * @param {...(string|string[])} [paths] The property paths of elements to pick,
14677 * specified individually or in arrays.
14678 * @returns {Array} Returns the new array of picked elements.
14679 * @example
14680 *
14681 * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
14682 *
14683 * _.at(object, ['a[0].b.c', 'a[1]']);
14684 * // => [3, 4]
14685 *
14686 * _.at(['a', 'b', 'c'], 0, 2);
14687 * // => ['a', 'c']
14688 */
14689 var at = rest(function(object, paths) {
14690 return baseAt(object, baseFlatten(paths, 1));
14691 });
14692
14693 /**
14694 * Creates an object that inherits from the `prototype` object. If a `properties`
14695 * object is given its own enumerable properties are assigned to the created object.
14696 *
14697 * @static
14698 * @memberOf _
14699 * @category Object
14700 * @param {Object} prototype The object to inherit from.
14701 * @param {Object} [properties] The properties to assign to the object.
14702 * @returns {Object} Returns the new object.
14703 * @example
14704 *
14705 * function Shape() {
14706 * this.x = 0;
14707 * this.y = 0;
14708 * }
14709 *
14710 * function Circle() {
14711 * Shape.call(this);
14712 * }
14713 *
14714 * Circle.prototype = _.create(Shape.prototype, {
14715 * 'constructor': Circle
14716 * });
14717 *
14718 * var circle = new Circle;
14719 * circle instanceof Circle;
14720 * // => true
14721 *
14722 * circle instanceof Shape;
14723 * // => true
14724 */
14725 function create(prototype, properties) {
14726 var result = baseCreate(prototype);
14727 return properties ? baseAssign(result, properties) : result;
14728 }
14729
14730 /**
14731 * Assigns own and inherited enumerable properties of source objects to the
14732 * destination object for all destination properties that resolve to `undefined`.
14733 * Source objects are applied from left to right. Once a property is set,
14734 * additional values of the same property are ignored.
14735 *
14736 * **Note:** This method mutates `object`.
14737 *
14738 * @static
14739 * @memberOf _
14740 * @category Object
14741 * @param {Object} object The destination object.
14742 * @param {...Object} [sources] The source objects.
14743 * @returns {Object} Returns `object`.
14744 * @example
14745 *
14746 * _.defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
14747 * // => { 'user': 'barney', 'age': 36 }
14748 */
14749 var defaults = rest(function(args) {
14750 args.push(undefined, assignInDefaults);
14751 return apply(assignInWith, undefined, args);
14752 });
14753
14754 /**
14755 * This method is like `_.defaults` except that it recursively assigns
14756 * default properties.
14757 *
14758 * **Note:** This method mutates `object`.
14759 *
14760 * @static
14761 * @memberOf _
14762 * @category Object
14763 * @param {Object} object The destination object.
14764 * @param {...Object} [sources] The source objects.
14765 * @returns {Object} Returns `object`.
14766 * @example
14767 *
14768 * _.defaultsDeep({ 'user': { 'name': 'barney' } }, { 'user': { 'name': 'fred', 'age': 36 } });
14769 * // => { 'user': { 'name': 'barney', 'age': 36 } }
14770 *
14771 */
14772 var defaultsDeep = rest(function(args) {
14773 args.push(undefined, mergeDefaults);
14774 return apply(mergeWith, undefined, args);
14775 });
14776
14777 /**
14778 * This method is like `_.find` except that it returns the key of the first
14779 * element `predicate` returns truthy for instead of the element itself.
14780 *
14781 * @static
14782 * @memberOf _
14783 * @category Object
14784 * @param {Object} object The object to search.
14785 * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
14786 * @returns {string|undefined} Returns the key of the matched element, else `undefined`.
14787 * @example
14788 *
14789 * var users = {
14790 * 'barney': { 'age': 36, 'active': true },
14791 * 'fred': { 'age': 40, 'active': false },
14792 * 'pebbles': { 'age': 1, 'active': true }
14793 * };
14794 *
14795 * _.findKey(users, function(o) { return o.age < 40; });
14796 * // => 'barney' (iteration order is not guaranteed)
14797 *
14798 * // The `_.matches` iteratee shorthand.
14799 * _.findKey(users, { 'age': 1, 'active': true });
14800 * // => 'pebbles'
14801 *
14802 * // The `_.matchesProperty` iteratee shorthand.
14803 * _.findKey(users, ['active', false]);
14804 * // => 'fred'
14805 *
14806 * // The `_.property` iteratee shorthand.
14807 * _.findKey(users, 'active');
14808 * // => 'barney'
14809 */
14810 function findKey(object, predicate) {
14811 return baseFind(object, getIteratee(predicate, 3), baseForOwn, true);
14812 }
14813
14814 /**
14815 * This method is like `_.findKey` except that it iterates over elements of
14816 * a collection in the opposite order.
14817 *
14818 * @static
14819 * @memberOf _
14820 * @category Object
14821 * @param {Object} object The object to search.
14822 * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration.
14823 * @returns {string|undefined} Returns the key of the matched element, else `undefined`.
14824 * @example
14825 *
14826 * var users = {
14827 * 'barney': { 'age': 36, 'active': true },
14828 * 'fred': { 'age': 40, 'active': false },
14829 * 'pebbles': { 'age': 1, 'active': true }
14830 * };
14831 *
14832 * _.findLastKey(users, function(o) { return o.age < 40; });
14833 * // => returns 'pebbles' assuming `_.findKey` returns 'barney'
14834 *
14835 * // The `_.matches` iteratee shorthand.
14836 * _.findLastKey(users, { 'age': 36, 'active': true });
14837 * // => 'barney'
14838 *
14839 * // The `_.matchesProperty` iteratee shorthand.
14840 * _.findLastKey(users, ['active', false]);
14841 * // => 'fred'
14842 *
14843 * // The `_.property` iteratee shorthand.
14844 * _.findLastKey(users, 'active');
14845 * // => 'pebbles'
14846 */
14847 function findLastKey(object, predicate) {
14848 return baseFind(object, getIteratee(predicate, 3), baseForOwnRight, true);
14849 }
14850
14851 /**
14852 * Iterates over own and inherited enumerable properties of an object invoking
14853 * `iteratee` for each property. The iteratee is invoked with three arguments:
14854 * (value, key, object). Iteratee functions may exit iteration early by explicitly
14855 * returning `false`.
14856 *
14857 * @static
14858 * @memberOf _
14859 * @category Object
14860 * @param {Object} object The object to iterate over.
14861 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
14862 * @returns {Object} Returns `object`.
14863 * @example
14864 *
14865 * function Foo() {
14866 * this.a = 1;
14867 * this.b = 2;
14868 * }
14869 *
14870 * Foo.prototype.c = 3;
14871 *
14872 * _.forIn(new Foo, function(value, key) {
14873 * console.log(key);
14874 * });
14875 * // => logs 'a', 'b', then 'c' (iteration order is not guaranteed)
14876 */
14877 function forIn(object, iteratee) {
14878 return object == null
14879 ? object
14880 : baseFor(object, baseCastFunction(iteratee), keysIn);
14881 }
14882
14883 /**
14884 * This method is like `_.forIn` except that it iterates over properties of
14885 * `object` in the opposite order.
14886 *
14887 * @static
14888 * @memberOf _
14889 * @category Object
14890 * @param {Object} object The object to iterate over.
14891 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
14892 * @returns {Object} Returns `object`.
14893 * @example
14894 *
14895 * function Foo() {
14896 * this.a = 1;
14897 * this.b = 2;
14898 * }
14899 *
14900 * Foo.prototype.c = 3;
14901 *
14902 * _.forInRight(new Foo, function(value, key) {
14903 * console.log(key);
14904 * });
14905 * // => logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'
14906 */
14907 function forInRight(object, iteratee) {
14908 return object == null
14909 ? object
14910 : baseForRight(object, baseCastFunction(iteratee), keysIn);
14911 }
14912
14913 /**
14914 * Iterates over own enumerable properties of an object invoking `iteratee`
14915 * for each property. The iteratee is invoked with three arguments:
14916 * (value, key, object). Iteratee functions may exit iteration early by
14917 * explicitly returning `false`.
14918 *
14919 * @static
14920 * @memberOf _
14921 * @category Object
14922 * @param {Object} object The object to iterate over.
14923 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
14924 * @returns {Object} Returns `object`.
14925 * @example
14926 *
14927 * function Foo() {
14928 * this.a = 1;
14929 * this.b = 2;
14930 * }
14931 *
14932 * Foo.prototype.c = 3;
14933 *
14934 * _.forOwn(new Foo, function(value, key) {
14935 * console.log(key);
14936 * });
14937 * // => logs 'a' then 'b' (iteration order is not guaranteed)
14938 */
14939 function forOwn(object, iteratee) {
14940 return object && baseForOwn(object, baseCastFunction(iteratee));
14941 }
14942
14943 /**
14944 * This method is like `_.forOwn` except that it iterates over properties of
14945 * `object` in the opposite order.
14946 *
14947 * @static
14948 * @memberOf _
14949 * @category Object
14950 * @param {Object} object The object to iterate over.
14951 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
14952 * @returns {Object} Returns `object`.
14953 * @example
14954 *
14955 * function Foo() {
14956 * this.a = 1;
14957 * this.b = 2;
14958 * }
14959 *
14960 * Foo.prototype.c = 3;
14961 *
14962 * _.forOwnRight(new Foo, function(value, key) {
14963 * console.log(key);
14964 * });
14965 * // => logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'
14966 */
14967 function forOwnRight(object, iteratee) {
14968 return object && baseForOwnRight(object, baseCastFunction(iteratee));
14969 }
14970
14971 /**
14972 * Creates an array of function property names from own enumerable properties
14973 * of `object`.
14974 *
14975 * @static
14976 * @memberOf _
14977 * @category Object
14978 * @param {Object} object The object to inspect.
14979 * @returns {Array} Returns the new array of property names.
14980 * @example
14981 *
14982 * function Foo() {
14983 * this.a = _.constant('a');
14984 * this.b = _.constant('b');
14985 * }
14986 *
14987 * Foo.prototype.c = _.constant('c');
14988 *
14989 * _.functions(new Foo);
14990 * // => ['a', 'b']
14991 */
14992 function functions(object) {
14993 return object == null ? [] : baseFunctions(object, keys(object));
14994 }
14995
14996 /**
14997 * Creates an array of function property names from own and inherited
14998 * enumerable properties of `object`.
14999 *
15000 * @static
15001 * @memberOf _
15002 * @category Object
15003 * @param {Object} object The object to inspect.
15004 * @returns {Array} Returns the new array of property names.
15005 * @example
15006 *
15007 * function Foo() {
15008 * this.a = _.constant('a');
15009 * this.b = _.constant('b');
15010 * }
15011 *
15012 * Foo.prototype.c = _.constant('c');
15013 *
15014 * _.functionsIn(new Foo);
15015 * // => ['a', 'b', 'c']
15016 */
15017 function functionsIn(object) {
15018 return object == null ? [] : baseFunctions(object, keysIn(object));
15019 }
15020
15021 /**
15022 * Gets the value at `path` of `object`. If the resolved value is
15023 * `undefined` the `defaultValue` is used in its place.
15024 *
15025 * @static
15026 * @memberOf _
15027 * @category Object
15028 * @param {Object} object The object to query.
15029 * @param {Array|string} path The path of the property to get.
15030 * @param {*} [defaultValue] The value returned if the resolved value is `undefined`.
15031 * @returns {*} Returns the resolved value.
15032 * @example
15033 *
15034 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
15035 *
15036 * _.get(object, 'a[0].b.c');
15037 * // => 3
15038 *
15039 * _.get(object, ['a', '0', 'b', 'c']);
15040 * // => 3
15041 *
15042 * _.get(object, 'a.b.c', 'default');
15043 * // => 'default'
15044 */
15045 function get(object, path, defaultValue) {
15046 var result = object == null ? undefined : baseGet(object, path);
15047 return result === undefined ? defaultValue : result;
15048 }
15049
15050 /**
15051 * Checks if `path` is a direct property of `object`.
15052 *
15053 * @static
15054 * @memberOf _
15055 * @category Object
15056 * @param {Object} object The object to query.
15057 * @param {Array|string} path The path to check.
15058 * @returns {boolean} Returns `true` if `path` exists, else `false`.
15059 * @example
15060 *
15061 * var object = { 'a': { 'b': { 'c': 3 } } };
15062 * var other = _.create({ 'a': _.create({ 'b': _.create({ 'c': 3 }) }) });
15063 *
15064 * _.has(object, 'a');
15065 * // => true
15066 *
15067 * _.has(object, 'a.b.c');
15068 * // => true
15069 *
15070 * _.has(object, ['a', 'b', 'c']);
15071 * // => true
15072 *
15073 * _.has(other, 'a');
15074 * // => false
15075 */
15076 function has(object, path) {
15077 return hasPath(object, path, baseHas);
15078 }
15079
15080 /**
15081 * Checks if `path` is a direct or inherited property of `object`.
15082 *
15083 * @static
15084 * @memberOf _
15085 * @category Object
15086 * @param {Object} object The object to query.
15087 * @param {Array|string} path The path to check.
15088 * @returns {boolean} Returns `true` if `path` exists, else `false`.
15089 * @example
15090 *
15091 * var object = _.create({ 'a': _.create({ 'b': _.create({ 'c': 3 }) }) });
15092 *
15093 * _.hasIn(object, 'a');
15094 * // => true
15095 *
15096 * _.hasIn(object, 'a.b.c');
15097 * // => true
15098 *
15099 * _.hasIn(object, ['a', 'b', 'c']);
15100 * // => true
15101 *
15102 * _.hasIn(object, 'b');
15103 * // => false
15104 */
15105 function hasIn(object, path) {
15106 return hasPath(object, path, baseHasIn);
15107 }
15108
15109 /**
15110 * Creates an object composed of the inverted keys and values of `object`.
15111 * If `object` contains duplicate values, subsequent values overwrite property
15112 * assignments of previous values.
15113 *
15114 * @static
15115 * @memberOf _
15116 * @category Object
15117 * @param {Object} object The object to invert.
15118 * @returns {Object} Returns the new inverted object.
15119 * @example
15120 *
15121 * var object = { 'a': 1, 'b': 2, 'c': 1 };
15122 *
15123 * _.invert(object);
15124 * // => { '1': 'c', '2': 'b' }
15125 */
15126 var invert = createInverter(function(result, value, key) {
15127 result[value] = key;
15128 }, constant(identity));
15129
15130 /**
15131 * This method is like `_.invert` except that the inverted object is generated
15132 * from the results of running each element of `object` through `iteratee`.
15133 * The corresponding inverted value of each inverted key is an array of keys
15134 * responsible for generating the inverted value. The iteratee is invoked
15135 * with one argument: (value).
15136 *
15137 * @static
15138 * @memberOf _
15139 * @category Object
15140 * @param {Object} object The object to invert.
15141 * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element.
15142 * @returns {Object} Returns the new inverted object.
15143 * @example
15144 *
15145 * var object = { 'a': 1, 'b': 2, 'c': 1 };
15146 *
15147 * _.invertBy(object);
15148 * // => { '1': ['a', 'c'], '2': ['b'] }
15149 *
15150 * _.invertBy(object, function(value) {
15151 * return 'group' + value;
15152 * });
15153 * // => { 'group1': ['a', 'c'], 'group2': ['b'] }
15154 */
15155 var invertBy = createInverter(function(result, value, key) {
15156 if (hasOwnProperty.call(result, value)) {
15157 result[value].push(key);
15158 } else {
15159 result[value] = [key];
15160 }
15161 }, getIteratee);
15162
15163 /**
15164 * Invokes the method at `path` of `object`.
15165 *
15166 * @static
15167 * @memberOf _
15168 * @category Object
15169 * @param {Object} object The object to query.
15170 * @param {Array|string} path The path of the method to invoke.
15171 * @param {...*} [args] The arguments to invoke the method with.
15172 * @returns {*} Returns the result of the invoked method.
15173 * @example
15174 *
15175 * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };
15176 *
15177 * _.invoke(object, 'a[0].b.c.slice', 1, 3);
15178 * // => [2, 3]
15179 */
15180 var invoke = rest(baseInvoke);
15181
15182 /**
15183 * Creates an array of the own enumerable property names of `object`.
15184 *
15185 * **Note:** Non-object values are coerced to objects. See the
15186 * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys)
15187 * for more details.
15188 *
15189 * @static
15190 * @memberOf _
15191 * @category Object
15192 * @param {Object} object The object to query.
15193 * @returns {Array} Returns the array of property names.
15194 * @example
15195 *
15196 * function Foo() {
15197 * this.a = 1;
15198 * this.b = 2;
15199 * }
15200 *
15201 * Foo.prototype.c = 3;
15202 *
15203 * _.keys(new Foo);
15204 * // => ['a', 'b'] (iteration order is not guaranteed)
15205 *
15206 * _.keys('hi');
15207 * // => ['0', '1']
15208 */
15209 function keys(object) {
15210 var isProto = isPrototype(object);
15211 if (!(isProto || isArrayLike(object))) {
15212 return baseKeys(object);
15213 }
15214 var indexes = indexKeys(object),
15215 skipIndexes = !!indexes,
15216 result = indexes || [],
15217 length = result.length;
15218
15219 for (var key in object) {
15220 if (baseHas(object, key) &&
15221 !(skipIndexes && (key == 'length' || isIndex(key, length))) &&
15222 !(isProto && key == 'constructor')) {
15223 result.push(key);
15224 }
15225 }
15226 return result;
15227 }
15228
15229 /**
15230 * Creates an array of the own and inherited enumerable property names of `object`.
15231 *
15232 * **Note:** Non-object values are coerced to objects.
15233 *
15234 * @static
15235 * @memberOf _
15236 * @category Object
15237 * @param {Object} object The object to query.
15238 * @returns {Array} Returns the array of property names.
15239 * @example
15240 *
15241 * function Foo() {
15242 * this.a = 1;
15243 * this.b = 2;
15244 * }
15245 *
15246 * Foo.prototype.c = 3;
15247 *
15248 * _.keysIn(new Foo);
15249 * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
15250 */
15251 function keysIn(object) {
15252 var index = -1,
15253 isProto = isPrototype(object),
15254 props = baseKeysIn(object),
15255 propsLength = props.length,
15256 indexes = indexKeys(object),
15257 skipIndexes = !!indexes,
15258 result = indexes || [],
15259 length = result.length;
15260
15261 while (++index < propsLength) {
15262 var key = props[index];
15263 if (!(skipIndexes && (key == 'length' || isIndex(key, length))) &&
15264 !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
15265 result.push(key);
15266 }
15267 }
15268 return result;
15269 }
15270
15271 /**
15272 * The opposite of `_.mapValues`; this method creates an object with the
15273 * same values as `object` and keys generated by running each own enumerable
15274 * property of `object` through `iteratee`. The iteratee is invoked with
15275 * three arguments: (value, key, object).
15276 *
15277 * @static
15278 * @memberOf _
15279 * @category Object
15280 * @param {Object} object The object to iterate over.
15281 * @param {Function|Object|string} [iteratee=_.identity] The function invoked per iteration.
15282 * @returns {Object} Returns the new mapped object.
15283 * @example
15284 *
15285 * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
15286 * return key + value;
15287 * });
15288 * // => { 'a1': 1, 'b2': 2 }
15289 */
15290 function mapKeys(object, iteratee) {
15291 var result = {};
15292 iteratee = getIteratee(iteratee, 3);
15293
15294 baseForOwn(object, function(value, key, object) {
15295 result[iteratee(value, key, object)] = value;
15296 });
15297 return result;
15298 }
15299
15300 /**
15301 * Creates an object with the same keys as `object` and values generated by
15302 * running each own enumerable property of `object` through `iteratee`. The
15303 * iteratee is invoked with three arguments: (value, key, object).
15304 *
15305 * @static
15306 * @memberOf _
15307 * @category Object
15308 * @param {Object} object The object to iterate over.
15309 * @param {Function|Object|string} [iteratee=_.identity] The function invoked per iteration.
15310 * @returns {Object} Returns the new mapped object.
15311 * @example
15312 *
15313 * var users = {
15314 * 'fred': { 'user': 'fred', 'age': 40 },
15315 * 'pebbles': { 'user': 'pebbles', 'age': 1 }
15316 * };
15317 *
15318 * _.mapValues(users, function(o) { return o.age; });
15319 * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
15320 *
15321 * // The `_.property` iteratee shorthand.
15322 * _.mapValues(users, 'age');
15323 * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
15324 */
15325 function mapValues(object, iteratee) {
15326 var result = {};
15327 iteratee = getIteratee(iteratee, 3);
15328
15329 baseForOwn(object, function(value, key, object) {
15330 result[key] = iteratee(value, key, object);
15331 });
15332 return result;
15333 }
15334
15335 /**
15336 * This method is like `_.assign` except that it recursively merges own and
15337 * inherited enumerable properties of source objects into the destination
15338 * object. Source properties that resolve to `undefined` are skipped if a
15339 * destination value exists. Array and plain object properties are merged
15340 * recursively.Other objects and value types are overridden by assignment.
15341 * Source objects are applied from left to right. Subsequent sources
15342 * overwrite property assignments of previous sources.
15343 *
15344 * **Note:** This method mutates `object`.
15345 *
15346 * @static
15347 * @memberOf _
15348 * @category Object
15349 * @param {Object} object The destination object.
15350 * @param {...Object} [sources] The source objects.
15351 * @returns {Object} Returns `object`.
15352 * @example
15353 *
15354 * var users = {
15355 * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }]
15356 * };
15357 *
15358 * var ages = {
15359 * 'data': [{ 'age': 36 }, { 'age': 40 }]
15360 * };
15361 *
15362 * _.merge(users, ages);
15363 * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }
15364 */
15365 var merge = createAssigner(function(object, source, srcIndex) {
15366 baseMerge(object, source, srcIndex);
15367 });
15368
15369 /**
15370 * This method is like `_.merge` except that it accepts `customizer` which
15371 * is invoked to produce the merged values of the destination and source
15372 * properties. If `customizer` returns `undefined` merging is handled by the
15373 * method instead. The `customizer` is invoked with seven arguments:
15374 * (objValue, srcValue, key, object, source, stack).
15375 *
15376 * **Note:** This method mutates `object`.
15377 *
15378 * @static
15379 * @memberOf _
15380 * @category Object
15381 * @param {Object} object The destination object.
15382 * @param {...Object} sources The source objects.
15383 * @param {Function} customizer The function to customize assigned values.
15384 * @returns {Object} Returns `object`.
15385 * @example
15386 *
15387 * function customizer(objValue, srcValue) {
15388 * if (_.isArray(objValue)) {
15389 * return objValue.concat(srcValue);
15390 * }
15391 * }
15392 *
15393 * var object = {
15394 * 'fruits': ['apple'],
15395 * 'vegetables': ['beet']
15396 * };
15397 *
15398 * var other = {
15399 * 'fruits': ['banana'],
15400 * 'vegetables': ['carrot']
15401 * };
15402 *
15403 * _.mergeWith(object, other, customizer);
15404 * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }
15405 */
15406 var mergeWith = createAssigner(function(object, source, srcIndex, customizer) {
15407 baseMerge(object, source, srcIndex, customizer);
15408 });
15409
15410 /**
15411 * The opposite of `_.pick`; this method creates an object composed of the
15412 * own and inherited enumerable properties of `object` that are not omitted.
15413 *
15414 * @static
15415 * @memberOf _
15416 * @category Object
15417 * @param {Object} object The source object.
15418 * @param {...(string|string[])} [props] The property names to omit, specified
15419 * individually or in arrays.
15420 * @returns {Object} Returns the new object.
15421 * @example
15422 *
15423 * var object = { 'a': 1, 'b': '2', 'c': 3 };
15424 *
15425 * _.omit(object, ['a', 'c']);
15426 * // => { 'b': '2' }
15427 */
15428 var omit = rest(function(object, props) {
15429 if (object == null) {
15430 return {};
15431 }
15432 props = arrayMap(baseFlatten(props, 1), String);
15433 return basePick(object, baseDifference(keysIn(object), props));
15434 });
15435
15436 /**
15437 * The opposite of `_.pickBy`; this method creates an object composed of
15438 * the own and inherited enumerable properties of `object` that `predicate`
15439 * doesn't return truthy for. The predicate is invoked with two arguments:
15440 * (value, key).
15441 *
15442 * @static
15443 * @memberOf _
15444 * @category Object
15445 * @param {Object} object The source object.
15446 * @param {Function|Object|string} [predicate=_.identity] The function invoked per property.
15447 * @returns {Object} Returns the new object.
15448 * @example
15449 *
15450 * var object = { 'a': 1, 'b': '2', 'c': 3 };
15451 *
15452 * _.omitBy(object, _.isNumber);
15453 * // => { 'b': '2' }
15454 */
15455 function omitBy(object, predicate) {
15456 predicate = getIteratee(predicate);
15457 return basePickBy(object, function(value, key) {
15458 return !predicate(value, key);
15459 });
15460 }
15461
15462 /**
15463 * Creates an object composed of the picked `object` properties.
15464 *
15465 * @static
15466 * @memberOf _
15467 * @category Object
15468 * @param {Object} object The source object.
15469 * @param {...(string|string[])} [props] The property names to pick, specified
15470 * individually or in arrays.
15471 * @returns {Object} Returns the new object.
15472 * @example
15473 *
15474 * var object = { 'a': 1, 'b': '2', 'c': 3 };
15475 *
15476 * _.pick(object, ['a', 'c']);
15477 * // => { 'a': 1, 'c': 3 }
15478 */
15479 var pick = rest(function(object, props) {
15480 return object == null ? {} : basePick(object, baseFlatten(props, 1));
15481 });
15482
15483 /**
15484 * Creates an object composed of the `object` properties `predicate` returns
15485 * truthy for. The predicate is invoked with two arguments: (value, key).
15486 *
15487 * @static
15488 * @memberOf _
15489 * @category Object
15490 * @param {Object} object The source object.
15491 * @param {Function|Object|string} [predicate=_.identity] The function invoked per property.
15492 * @returns {Object} Returns the new object.
15493 * @example
15494 *
15495 * var object = { 'a': 1, 'b': '2', 'c': 3 };
15496 *
15497 * _.pickBy(object, _.isNumber);
15498 * // => { 'a': 1, 'c': 3 }
15499 */
15500 function pickBy(object, predicate) {
15501 return object == null ? {} : basePickBy(object, getIteratee(predicate));
15502 }
15503
15504 /**
15505 * This method is like `_.get` except that if the resolved value is a function
15506 * it's invoked with the `this` binding of its parent object and its result
15507 * is returned.
15508 *
15509 * @static
15510 * @memberOf _
15511 * @category Object
15512 * @param {Object} object The object to query.
15513 * @param {Array|string} path The path of the property to resolve.
15514 * @param {*} [defaultValue] The value returned if the resolved value is `undefined`.
15515 * @returns {*} Returns the resolved value.
15516 * @example
15517 *
15518 * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
15519 *
15520 * _.result(object, 'a[0].b.c1');
15521 * // => 3
15522 *
15523 * _.result(object, 'a[0].b.c2');
15524 * // => 4
15525 *
15526 * _.result(object, 'a[0].b.c3', 'default');
15527 * // => 'default'
15528 *
15529 * _.result(object, 'a[0].b.c3', _.constant('default'));
15530 * // => 'default'
15531 */
15532 function result(object, path, defaultValue) {
15533 if (!isKey(path, object)) {
15534 path = baseCastPath(path);
15535 var result = get(object, path);
15536 object = parent(object, path);
15537 } else {
15538 result = object == null ? undefined : object[path];
15539 }
15540 if (result === undefined) {
15541 result = defaultValue;
15542 }
15543 return isFunction(result) ? result.call(object) : result;
15544 }
15545
15546 /**
15547 * Sets the value at `path` of `object`. If a portion of `path` doesn't exist
15548 * it's created. Arrays are created for missing index properties while objects
15549 * are created for all other missing properties. Use `_.setWith` to customize
15550 * `path` creation.
15551 *
15552 * **Note:** This method mutates `object`.
15553 *
15554 * @static
15555 * @memberOf _
15556 * @category Object
15557 * @param {Object} object The object to modify.
15558 * @param {Array|string} path The path of the property to set.
15559 * @param {*} value The value to set.
15560 * @returns {Object} Returns `object`.
15561 * @example
15562 *
15563 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
15564 *
15565 * _.set(object, 'a[0].b.c', 4);
15566 * console.log(object.a[0].b.c);
15567 * // => 4
15568 *
15569 * _.set(object, 'x[0].y.z', 5);
15570 * console.log(object.x[0].y.z);
15571 * // => 5
15572 */
15573 function set(object, path, value) {
15574 return object == null ? object : baseSet(object, path, value);
15575 }
15576
15577 /**
15578 * This method is like `_.set` except that it accepts `customizer` which is
15579 * invoked to produce the objects of `path`. If `customizer` returns `undefined`
15580 * path creation is handled by the method instead. The `customizer` is invoked
15581 * with three arguments: (nsValue, key, nsObject).
15582 *
15583 * **Note:** This method mutates `object`.
15584 *
15585 * @static
15586 * @memberOf _
15587 * @category Object
15588 * @param {Object} object The object to modify.
15589 * @param {Array|string} path The path of the property to set.
15590 * @param {*} value The value to set.
15591 * @param {Function} [customizer] The function to customize assigned values.
15592 * @returns {Object} Returns `object`.
15593 * @example
15594 *
15595 * var object = {};
15596 *
15597 * _.setWith(object, '[0][1]', 'a', Object);
15598 * // => { '0': { '1': 'a' } }
15599 */
15600 function setWith(object, path, value, customizer) {
15601 customizer = typeof customizer == 'function' ? customizer : undefined;
15602 return object == null ? object : baseSet(object, path, value, customizer);
15603 }
15604
15605 /**
15606 * Creates an array of own enumerable key-value pairs for `object` which
15607 * can be consumed by `_.fromPairs`.
15608 *
15609 * @static
15610 * @memberOf _
15611 * @category Object
15612 * @param {Object} object The object to query.
15613 * @returns {Array} Returns the new array of key-value pairs.
15614 * @example
15615 *
15616 * function Foo() {
15617 * this.a = 1;
15618 * this.b = 2;
15619 * }
15620 *
15621 * Foo.prototype.c = 3;
15622 *
15623 * _.toPairs(new Foo);
15624 * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)
15625 */
15626 function toPairs(object) {
15627 return baseToPairs(object, keys(object));
15628 }
15629
15630 /**
15631 * Creates an array of own and inherited enumerable key-value pairs for
15632 * `object` which can be consumed by `_.fromPairs`.
15633 *
15634 * @static
15635 * @memberOf _
15636 * @category Object
15637 * @param {Object} object The object to query.
15638 * @returns {Array} Returns the new array of key-value pairs.
15639 * @example
15640 *
15641 * function Foo() {
15642 * this.a = 1;
15643 * this.b = 2;
15644 * }
15645 *
15646 * Foo.prototype.c = 3;
15647 *
15648 * _.toPairsIn(new Foo);
15649 * // => [['a', 1], ['b', 2], ['c', 1]] (iteration order is not guaranteed)
15650 */
15651 function toPairsIn(object) {
15652 return baseToPairs(object, keysIn(object));
15653 }
15654
15655 /**
15656 * An alternative to `_.reduce`; this method transforms `object` to a new
15657 * `accumulator` object which is the result of running each of its own enumerable
15658 * properties through `iteratee`, with each invocation potentially mutating
15659 * the `accumulator` object. The iteratee is invoked with four arguments:
15660 * (accumulator, value, key, object). Iteratee functions may exit iteration
15661 * early by explicitly returning `false`.
15662 *
15663 * @static
15664 * @memberOf _
15665 * @category Object
15666 * @param {Array|Object} object The object to iterate over.
15667 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
15668 * @param {*} [accumulator] The custom accumulator value.
15669 * @returns {*} Returns the accumulated value.
15670 * @example
15671 *
15672 * _.transform([2, 3, 4], function(result, n) {
15673 * result.push(n *= n);
15674 * return n % 2 == 0;
15675 * }, []);
15676 * // => [4, 9]
15677 *
15678 * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
15679 * (result[value] || (result[value] = [])).push(key);
15680 * }, {});
15681 * // => { '1': ['a', 'c'], '2': ['b'] }
15682 */
15683 function transform(object, iteratee, accumulator) {
15684 var isArr = isArray(object) || isTypedArray(object);
15685 iteratee = getIteratee(iteratee, 4);
15686
15687 if (accumulator == null) {
15688 if (isArr || isObject(object)) {
15689 var Ctor = object.constructor;
15690 if (isArr) {
15691 accumulator = isArray(object) ? new Ctor : [];
15692 } else {
15693 accumulator = isFunction(Ctor) ? baseCreate(getPrototypeOf(object)) : {};
15694 }
15695 } else {
15696 accumulator = {};
15697 }
15698 }
15699 (isArr ? arrayEach : baseForOwn)(object, function(value, index, object) {
15700 return iteratee(accumulator, value, index, object);
15701 });
15702 return accumulator;
15703 }
15704
15705 /**
15706 * Removes the property at `path` of `object`.
15707 *
15708 * **Note:** This method mutates `object`.
15709 *
15710 * @static
15711 * @memberOf _
15712 * @category Object
15713 * @param {Object} object The object to modify.
15714 * @param {Array|string} path The path of the property to unset.
15715 * @returns {boolean} Returns `true` if the property is deleted, else `false`.
15716 * @example
15717 *
15718 * var object = { 'a': [{ 'b': { 'c': 7 } }] };
15719 * _.unset(object, 'a[0].b.c');
15720 * // => true
15721 *
15722 * console.log(object);
15723 * // => { 'a': [{ 'b': {} }] };
15724 *
15725 * _.unset(object, 'a[0].b.c');
15726 * // => true
15727 *
15728 * console.log(object);
15729 * // => { 'a': [{ 'b': {} }] };
15730 */
15731 function unset(object, path) {
15732 return object == null ? true : baseUnset(object, path);
15733 }
15734
15735 /**
15736 * This method is like `_.set` except that accepts `updater` to produce the
15737 * value to set. Use `_.updateWith` to customize `path` creation. The `updater`
15738 * is invoked with one argument: (value).
15739 *
15740 * **Note:** This method mutates `object`.
15741 *
15742 * @static
15743 * @memberOf _
15744 * @category Object
15745 * @param {Object} object The object to modify.
15746 * @param {Array|string} path The path of the property to set.
15747 * @param {Function} updater The function to produce the updated value.
15748 * @returns {Object} Returns `object`.
15749 * @example
15750 *
15751 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
15752 *
15753 * _.update(object, 'a[0].b.c', function(n) { return n * n; });
15754 * console.log(object.a[0].b.c);
15755 * // => 9
15756 *
15757 * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });
15758 * console.log(object.x[0].y.z);
15759 * // => 0
15760 */
15761 function update(object, path, updater) {
15762 return object == null ? object : baseUpdate(object, path, baseCastFunction(updater));
15763 }
15764
15765 /**
15766 * This method is like `_.update` except that it accepts `customizer` which is
15767 * invoked to produce the objects of `path`. If `customizer` returns `undefined`
15768 * path creation is handled by the method instead. The `customizer` is invoked
15769 * with three arguments: (nsValue, key, nsObject).
15770 *
15771 * **Note:** This method mutates `object`.
15772 *
15773 * @static
15774 * @memberOf _
15775 * @category Object
15776 * @param {Object} object The object to modify.
15777 * @param {Array|string} path The path of the property to set.
15778 * @param {Function} updater The function to produce the updated value.
15779 * @param {Function} [customizer] The function to customize assigned values.
15780 * @returns {Object} Returns `object`.
15781 * @example
15782 *
15783 * var object = {};
15784 *
15785 * _.updateWith(object, '[0][1]', _.constant('a'), Object);
15786 * // => { '0': { '1': 'a' } }
15787 */
15788 function updateWith(object, path, updater, customizer) {
15789 customizer = typeof customizer == 'function' ? customizer : undefined;
15790 return object == null ? object : baseUpdate(object, path, baseCastFunction(updater), customizer);
15791 }
15792
15793 /**
15794 * Creates an array of the own enumerable property values of `object`.
15795 *
15796 * **Note:** Non-object values are coerced to objects.
15797 *
15798 * @static
15799 * @memberOf _
15800 * @category Object
15801 * @param {Object} object The object to query.
15802 * @returns {Array} Returns the array of property values.
15803 * @example
15804 *
15805 * function Foo() {
15806 * this.a = 1;
15807 * this.b = 2;
15808 * }
15809 *
15810 * Foo.prototype.c = 3;
15811 *
15812 * _.values(new Foo);
15813 * // => [1, 2] (iteration order is not guaranteed)
15814 *
15815 * _.values('hi');
15816 * // => ['h', 'i']
15817 */
15818 function values(object) {
15819 return object ? baseValues(object, keys(object)) : [];
15820 }
15821
15822 /**
15823 * Creates an array of the own and inherited enumerable property values of `object`.
15824 *
15825 * **Note:** Non-object values are coerced to objects.
15826 *
15827 * @static
15828 * @memberOf _
15829 * @category Object
15830 * @param {Object} object The object to query.
15831 * @returns {Array} Returns the array of property values.
15832 * @example
15833 *
15834 * function Foo() {
15835 * this.a = 1;
15836 * this.b = 2;
15837 * }
15838 *
15839 * Foo.prototype.c = 3;
15840 *
15841 * _.valuesIn(new Foo);
15842 * // => [1, 2, 3] (iteration order is not guaranteed)
15843 */
15844 function valuesIn(object) {
15845 return object == null ? [] : baseValues(object, keysIn(object));
15846 }
15847
15848 /*------------------------------------------------------------------------*/
15849
15850 /**
15851 * Clamps `number` within the inclusive `lower` and `upper` bounds.
15852 *
15853 * @static
15854 * @memberOf _
15855 * @category Number
15856 * @param {number} number The number to clamp.
15857 * @param {number} [lower] The lower bound.
15858 * @param {number} upper The upper bound.
15859 * @returns {number} Returns the clamped number.
15860 * @example
15861 *
15862 * _.clamp(-10, -5, 5);
15863 * // => -5
15864 *
15865 * _.clamp(10, -5, 5);
15866 * // => 5
15867 */
15868 function clamp(number, lower, upper) {
15869 if (upper === undefined) {
15870 upper = lower;
15871 lower = undefined;
15872 }
15873 if (upper !== undefined) {
15874 upper = toNumber(upper);
15875 upper = upper === upper ? upper : 0;
15876 }
15877 if (lower !== undefined) {
15878 lower = toNumber(lower);
15879 lower = lower === lower ? lower : 0;
15880 }
15881 return baseClamp(toNumber(number), lower, upper);
15882 }
15883
15884 /**
15885 * Checks if `n` is between `start` and up to but not including, `end`. If
15886 * `end` is not specified it's set to `start` with `start` then set to `0`.
15887 * If `start` is greater than `end` the params are swapped to support
15888 * negative ranges.
15889 *
15890 * @static
15891 * @memberOf _
15892 * @category Number
15893 * @param {number} number The number to check.
15894 * @param {number} [start=0] The start of the range.
15895 * @param {number} end The end of the range.
15896 * @returns {boolean} Returns `true` if `number` is in the range, else `false`.
15897 * @example
15898 *
15899 * _.inRange(3, 2, 4);
15900 * // => true
15901 *
15902 * _.inRange(4, 8);
15903 * // => true
15904 *
15905 * _.inRange(4, 2);
15906 * // => false
15907 *
15908 * _.inRange(2, 2);
15909 * // => false
15910 *
15911 * _.inRange(1.2, 2);
15912 * // => true
15913 *
15914 * _.inRange(5.2, 4);
15915 * // => false
15916 *
15917 * _.inRange(-3, -2, -6);
15918 * // => true
15919 */
15920 function inRange(number, start, end) {
15921 start = toNumber(start) || 0;
15922 if (end === undefined) {
15923 end = start;
15924 start = 0;
15925 } else {
15926 end = toNumber(end) || 0;
15927 }
15928 number = toNumber(number);
15929 return baseInRange(number, start, end);
15930 }
15931
15932 /**
15933 * Produces a random number between the inclusive `lower` and `upper` bounds.
15934 * If only one argument is provided a number between `0` and the given number
15935 * is returned. If `floating` is `true`, or either `lower` or `upper` are floats,
15936 * a floating-point number is returned instead of an integer.
15937 *
15938 * **Note:** JavaScript follows the IEEE-754 standard for resolving
15939 * floating-point values which can produce unexpected results.
15940 *
15941 * @static
15942 * @memberOf _
15943 * @category Number
15944 * @param {number} [lower=0] The lower bound.
15945 * @param {number} [upper=1] The upper bound.
15946 * @param {boolean} [floating] Specify returning a floating-point number.
15947 * @returns {number} Returns the random number.
15948 * @example
15949 *
15950 * _.random(0, 5);
15951 * // => an integer between 0 and 5
15952 *
15953 * _.random(5);
15954 * // => also an integer between 0 and 5
15955 *
15956 * _.random(5, true);
15957 * // => a floating-point number between 0 and 5
15958 *
15959 * _.random(1.2, 5.2);
15960 * // => a floating-point number between 1.2 and 5.2
15961 */
15962 function random(lower, upper, floating) {
15963 if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) {
15964 upper = floating = undefined;
15965 }
15966 if (floating === undefined) {
15967 if (typeof upper == 'boolean') {
15968 floating = upper;
15969 upper = undefined;
15970 }
15971 else if (typeof lower == 'boolean') {
15972 floating = lower;
15973 lower = undefined;
15974 }
15975 }
15976 if (lower === undefined && upper === undefined) {
15977 lower = 0;
15978 upper = 1;
15979 }
15980 else {
15981 lower = toNumber(lower) || 0;
15982 if (upper === undefined) {
15983 upper = lower;
15984 lower = 0;
15985 } else {
15986 upper = toNumber(upper) || 0;
15987 }
15988 }
15989 if (lower > upper) {
15990 var temp = lower;
15991 lower = upper;
15992 upper = temp;
15993 }
15994 if (floating || lower % 1 || upper % 1) {
15995 var rand = nativeRandom();
15996 return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper);
15997 }
15998 return baseRandom(lower, upper);
15999 }
16000
16001 /*------------------------------------------------------------------------*/
16002
16003 /**
16004 * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
16005 *
16006 * @static
16007 * @memberOf _
16008 * @category String
16009 * @param {string} [string=''] The string to convert.
16010 * @returns {string} Returns the camel cased string.
16011 * @example
16012 *
16013 * _.camelCase('Foo Bar');
16014 * // => 'fooBar'
16015 *
16016 * _.camelCase('--foo-bar');
16017 * // => 'fooBar'
16018 *
16019 * _.camelCase('__foo_bar__');
16020 * // => 'fooBar'
16021 */
16022 var camelCase = createCompounder(function(result, word, index) {
16023 word = word.toLowerCase();
16024 return result + (index ? capitalize(word) : word);
16025 });
16026
16027 /**
16028 * Converts the first character of `string` to upper case and the remaining
16029 * to lower case.
16030 *
16031 * @static
16032 * @memberOf _
16033 * @category String
16034 * @param {string} [string=''] The string to capitalize.
16035 * @returns {string} Returns the capitalized string.
16036 * @example
16037 *
16038 * _.capitalize('FRED');
16039 * // => 'Fred'
16040 */
16041 function capitalize(string) {
16042 return upperFirst(toString(string).toLowerCase());
16043 }
16044
16045 /**
16046 * Deburrs `string` by converting [latin-1 supplementary letters](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
16047 * to basic latin letters and removing [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
16048 *
16049 * @static
16050 * @memberOf _
16051 * @category String
16052 * @param {string} [string=''] The string to deburr.
16053 * @returns {string} Returns the deburred string.
16054 * @example
16055 *
16056 * _.deburr('déjà vu');
16057 * // => 'deja vu'
16058 */
16059 function deburr(string) {
16060 string = toString(string);
16061 return string && string.replace(reLatin1, deburrLetter).replace(reComboMark, '');
16062 }
16063
16064 /**
16065 * Checks if `string` ends with the given target string.
16066 *
16067 * @static
16068 * @memberOf _
16069 * @category String
16070 * @param {string} [string=''] The string to search.
16071 * @param {string} [target] The string to search for.
16072 * @param {number} [position=string.length] The position to search from.
16073 * @returns {boolean} Returns `true` if `string` ends with `target`, else `false`.
16074 * @example
16075 *
16076 * _.endsWith('abc', 'c');
16077 * // => true
16078 *
16079 * _.endsWith('abc', 'b');
16080 * // => false
16081 *
16082 * _.endsWith('abc', 'b', 2);
16083 * // => true
16084 */
16085 function endsWith(string, target, position) {
16086 string = toString(string);
16087 target = typeof target == 'string' ? target : (target + '');
16088
16089 var length = string.length;
16090 position = position === undefined
16091 ? length
16092 : baseClamp(toInteger(position), 0, length);
16093
16094 position -= target.length;
16095 return position >= 0 && string.indexOf(target, position) == position;
16096 }
16097
16098 /**
16099 * Converts the characters "&", "<", ">", '"', "'", and "\`" in `string` to
16100 * their corresponding HTML entities.
16101 *
16102 * **Note:** No other characters are escaped. To escape additional
16103 * characters use a third-party library like [_he_](https://mths.be/he).
16104 *
16105 * Though the ">" character is escaped for symmetry, characters like
16106 * ">" and "/" don't need escaping in HTML and have no special meaning
16107 * unless they're part of a tag or unquoted attribute value.
16108 * See [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
16109 * (under "semi-related fun fact") for more details.
16110 *
16111 * Backticks are escaped because in IE < 9, they can break out of
16112 * attribute values or HTML comments. See [#59](https://html5sec.org/#59),
16113 * [#102](https://html5sec.org/#102), [#108](https://html5sec.org/#108), and
16114 * [#133](https://html5sec.org/#133) of the [HTML5 Security Cheatsheet](https://html5sec.org/)
16115 * for more details.
16116 *
16117 * When working with HTML you should always [quote attribute values](http://wonko.com/post/html-escaping)
16118 * to reduce XSS vectors.
16119 *
16120 * @static
16121 * @memberOf _
16122 * @category String
16123 * @param {string} [string=''] The string to escape.
16124 * @returns {string} Returns the escaped string.
16125 * @example
16126 *
16127 * _.escape('fred, barney, & pebbles');
16128 * // => 'fred, barney, &amp; pebbles'
16129 */
16130 function escape(string) {
16131 string = toString(string);
16132 return (string && reHasUnescapedHtml.test(string))
16133 ? string.replace(reUnescapedHtml, escapeHtmlChar)
16134 : string;
16135 }
16136
16137 /**
16138 * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+",
16139 * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`.
16140 *
16141 * @static
16142 * @memberOf _
16143 * @category String
16144 * @param {string} [string=''] The string to escape.
16145 * @returns {string} Returns the escaped string.
16146 * @example
16147 *
16148 * _.escapeRegExp('[lodash](https://lodash.com/)');
16149 * // => '\[lodash\]\(https://lodash\.com/\)'
16150 */
16151 function escapeRegExp(string) {
16152 string = toString(string);
16153 return (string && reHasRegExpChar.test(string))
16154 ? string.replace(reRegExpChar, '\\$&')
16155 : string;
16156 }
16157
16158 /**
16159 * Converts `string` to [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
16160 *
16161 * @static
16162 * @memberOf _
16163 * @category String
16164 * @param {string} [string=''] The string to convert.
16165 * @returns {string} Returns the kebab cased string.
16166 * @example
16167 *
16168 * _.kebabCase('Foo Bar');
16169 * // => 'foo-bar'
16170 *
16171 * _.kebabCase('fooBar');
16172 * // => 'foo-bar'
16173 *
16174 * _.kebabCase('__foo_bar__');
16175 * // => 'foo-bar'
16176 */
16177 var kebabCase = createCompounder(function(result, word, index) {
16178 return result + (index ? '-' : '') + word.toLowerCase();
16179 });
16180
16181 /**
16182 * Converts `string`, as space separated words, to lower case.
16183 *
16184 * @static
16185 * @memberOf _
16186 * @category String
16187 * @param {string} [string=''] The string to convert.
16188 * @returns {string} Returns the lower cased string.
16189 * @example
16190 *
16191 * _.lowerCase('--Foo-Bar');
16192 * // => 'foo bar'
16193 *
16194 * _.lowerCase('fooBar');
16195 * // => 'foo bar'
16196 *
16197 * _.lowerCase('__FOO_BAR__');
16198 * // => 'foo bar'
16199 */
16200 var lowerCase = createCompounder(function(result, word, index) {
16201 return result + (index ? ' ' : '') + word.toLowerCase();
16202 });
16203
16204 /**
16205 * Converts the first character of `string` to lower case.
16206 *
16207 * @static
16208 * @memberOf _
16209 * @category String
16210 * @param {string} [string=''] The string to convert.
16211 * @returns {string} Returns the converted string.
16212 * @example
16213 *
16214 * _.lowerFirst('Fred');
16215 * // => 'fred'
16216 *
16217 * _.lowerFirst('FRED');
16218 * // => 'fRED'
16219 */
16220 var lowerFirst = createCaseFirst('toLowerCase');
16221
16222 /**
16223 * Converts the first character of `string` to upper case.
16224 *
16225 * @static
16226 * @memberOf _
16227 * @category String
16228 * @param {string} [string=''] The string to convert.
16229 * @returns {string} Returns the converted string.
16230 * @example
16231 *
16232 * _.upperFirst('fred');
16233 * // => 'Fred'
16234 *
16235 * _.upperFirst('FRED');
16236 * // => 'FRED'
16237 */
16238 var upperFirst = createCaseFirst('toUpperCase');
16239
16240 /**
16241 * Pads `string` on the left and right sides if it's shorter than `length`.
16242 * Padding characters are truncated if they can't be evenly divided by `length`.
16243 *
16244 * @static
16245 * @memberOf _
16246 * @category String
16247 * @param {string} [string=''] The string to pad.
16248 * @param {number} [length=0] The padding length.
16249 * @param {string} [chars=' '] The string used as padding.
16250 * @returns {string} Returns the padded string.
16251 * @example
16252 *
16253 * _.pad('abc', 8);
16254 * // => ' abc '
16255 *
16256 * _.pad('abc', 8, '_-');
16257 * // => '_-abc_-_'
16258 *
16259 * _.pad('abc', 3);
16260 * // => 'abc'
16261 */
16262 function pad(string, length, chars) {
16263 string = toString(string);
16264 length = toInteger(length);
16265
16266 var strLength = stringSize(string);
16267 if (!length || strLength >= length) {
16268 return string;
16269 }
16270 var mid = (length - strLength) / 2,
16271 leftLength = nativeFloor(mid),
16272 rightLength = nativeCeil(mid);
16273
16274 return createPadding('', leftLength, chars) + string + createPadding('', rightLength, chars);
16275 }
16276
16277 /**
16278 * Pads `string` on the right side if it's shorter than `length`. Padding
16279 * characters are truncated if they exceed `length`.
16280 *
16281 * @static
16282 * @memberOf _
16283 * @category String
16284 * @param {string} [string=''] The string to pad.
16285 * @param {number} [length=0] The padding length.
16286 * @param {string} [chars=' '] The string used as padding.
16287 * @returns {string} Returns the padded string.
16288 * @example
16289 *
16290 * _.padEnd('abc', 6);
16291 * // => 'abc '
16292 *
16293 * _.padEnd('abc', 6, '_-');
16294 * // => 'abc_-_'
16295 *
16296 * _.padEnd('abc', 3);
16297 * // => 'abc'
16298 */
16299 function padEnd(string, length, chars) {
16300 string = toString(string);
16301 return string + createPadding(string, length, chars);
16302 }
16303
16304 /**
16305 * Pads `string` on the left side if it's shorter than `length`. Padding
16306 * characters are truncated if they exceed `length`.
16307 *
16308 * @static
16309 * @memberOf _
16310 * @category String
16311 * @param {string} [string=''] The string to pad.
16312 * @param {number} [length=0] The padding length.
16313 * @param {string} [chars=' '] The string used as padding.
16314 * @returns {string} Returns the padded string.
16315 * @example
16316 *
16317 * _.padStart('abc', 6);
16318 * // => ' abc'
16319 *
16320 * _.padStart('abc', 6, '_-');
16321 * // => '_-_abc'
16322 *
16323 * _.padStart('abc', 3);
16324 * // => 'abc'
16325 */
16326 function padStart(string, length, chars) {
16327 string = toString(string);
16328 return createPadding(string, length, chars) + string;
16329 }
16330
16331 /**
16332 * Converts `string` to an integer of the specified radix. If `radix` is
16333 * `undefined` or `0`, a `radix` of `10` is used unless `value` is a hexadecimal,
16334 * in which case a `radix` of `16` is used.
16335 *
16336 * **Note:** This method aligns with the [ES5 implementation](https://es5.github.io/#x15.1.2.2)
16337 * of `parseInt`.
16338 *
16339 * @static
16340 * @memberOf _
16341 * @category String
16342 * @param {string} string The string to convert.
16343 * @param {number} [radix=10] The radix to interpret `value` by.
16344 * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
16345 * @returns {number} Returns the converted integer.
16346 * @example
16347 *
16348 * _.parseInt('08');
16349 * // => 8
16350 *
16351 * _.map(['6', '08', '10'], _.parseInt);
16352 * // => [6, 8, 10]
16353 */
16354 function parseInt(string, radix, guard) {
16355 // Chrome fails to trim leading <BOM> whitespace characters.
16356 // See https://code.google.com/p/v8/issues/detail?id=3109 for more details.
16357 if (guard || radix == null) {
16358 radix = 0;
16359 } else if (radix) {
16360 radix = +radix;
16361 }
16362 string = toString(string).replace(reTrim, '');
16363 return nativeParseInt(string, radix || (reHasHexPrefix.test(string) ? 16 : 10));
16364 }
16365
16366 /**
16367 * Repeats the given string `n` times.
16368 *
16369 * @static
16370 * @memberOf _
16371 * @category String
16372 * @param {string} [string=''] The string to repeat.
16373 * @param {number} [n=0] The number of times to repeat the string.
16374 * @returns {string} Returns the repeated string.
16375 * @example
16376 *
16377 * _.repeat('*', 3);
16378 * // => '***'
16379 *
16380 * _.repeat('abc', 2);
16381 * // => 'abcabc'
16382 *
16383 * _.repeat('abc', 0);
16384 * // => ''
16385 */
16386 function repeat(string, n) {
16387 string = toString(string);
16388 n = toInteger(n);
16389
16390 var result = '';
16391 if (!string || n < 1 || n > MAX_SAFE_INTEGER) {
16392 return result;
16393 }
16394 // Leverage the exponentiation by squaring algorithm for a faster repeat.
16395 // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
16396 do {
16397 if (n % 2) {
16398 result += string;
16399 }
16400 n = nativeFloor(n / 2);
16401 string += string;
16402 } while (n);
16403
16404 return result;
16405 }
16406
16407 /**
16408 * Replaces matches for `pattern` in `string` with `replacement`.
16409 *
16410 * **Note:** This method is based on [`String#replace`](https://mdn.io/String/replace).
16411 *
16412 * @static
16413 * @memberOf _
16414 * @category String
16415 * @param {string} [string=''] The string to modify.
16416 * @param {RegExp|string} pattern The pattern to replace.
16417 * @param {Function|string} replacement The match replacement.
16418 * @returns {string} Returns the modified string.
16419 * @example
16420 *
16421 * _.replace('Hi Fred', 'Fred', 'Barney');
16422 * // => 'Hi Barney'
16423 */
16424 function replace() {
16425 var args = arguments,
16426 string = toString(args[0]);
16427
16428 return args.length < 3 ? string : string.replace(args[1], args[2]);
16429 }
16430
16431 /**
16432 * Converts `string` to [snake case](https://en.wikipedia.org/wiki/Snake_case).
16433 *
16434 * @static
16435 * @memberOf _
16436 * @category String
16437 * @param {string} [string=''] The string to convert.
16438 * @returns {string} Returns the snake cased string.
16439 * @example
16440 *
16441 * _.snakeCase('Foo Bar');
16442 * // => 'foo_bar'
16443 *
16444 * _.snakeCase('fooBar');
16445 * // => 'foo_bar'
16446 *
16447 * _.snakeCase('--foo-bar');
16448 * // => 'foo_bar'
16449 */
16450 var snakeCase = createCompounder(function(result, word, index) {
16451 return result + (index ? '_' : '') + word.toLowerCase();
16452 });
16453
16454 /**
16455 * Splits `string` by `separator`.
16456 *
16457 * **Note:** This method is based on [`String#split`](https://mdn.io/String/split).
16458 *
16459 * @static
16460 * @memberOf _
16461 * @category String
16462 * @param {string} [string=''] The string to split.
16463 * @param {RegExp|string} separator The separator pattern to split by.
16464 * @param {number} [limit] The length to truncate results to.
16465 * @returns {Array} Returns the new array of string segments.
16466 * @example
16467 *
16468 * _.split('a-b-c', '-', 2);
16469 * // => ['a', 'b']
16470 */
16471 function split(string, separator, limit) {
16472 return toString(string).split(separator, limit);
16473 }
16474
16475 /**
16476 * Converts `string` to [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
16477 *
16478 * @static
16479 * @memberOf _
16480 * @category String
16481 * @param {string} [string=''] The string to convert.
16482 * @returns {string} Returns the start cased string.
16483 * @example
16484 *
16485 * _.startCase('--foo-bar');
16486 * // => 'Foo Bar'
16487 *
16488 * _.startCase('fooBar');
16489 * // => 'Foo Bar'
16490 *
16491 * _.startCase('__foo_bar__');
16492 * // => 'Foo Bar'
16493 */
16494 var startCase = createCompounder(function(result, word, index) {
16495 return result + (index ? ' ' : '') + capitalize(word);
16496 });
16497
16498 /**
16499 * Checks if `string` starts with the given target string.
16500 *
16501 * @static
16502 * @memberOf _
16503 * @category String
16504 * @param {string} [string=''] The string to search.
16505 * @param {string} [target] The string to search for.
16506 * @param {number} [position=0] The position to search from.
16507 * @returns {boolean} Returns `true` if `string` starts with `target`, else `false`.
16508 * @example
16509 *
16510 * _.startsWith('abc', 'a');
16511 * // => true
16512 *
16513 * _.startsWith('abc', 'b');
16514 * // => false
16515 *
16516 * _.startsWith('abc', 'b', 1);
16517 * // => true
16518 */
16519 function startsWith(string, target, position) {
16520 string = toString(string);
16521 position = baseClamp(toInteger(position), 0, string.length);
16522 return string.lastIndexOf(target, position) == position;
16523 }
16524
16525 /**
16526 * Creates a compiled template function that can interpolate data properties
16527 * in "interpolate" delimiters, HTML-escape interpolated data properties in
16528 * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
16529 * properties may be accessed as free variables in the template. If a setting
16530 * object is given it takes precedence over `_.templateSettings` values.
16531 *
16532 * **Note:** In the development build `_.template` utilizes
16533 * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
16534 * for easier debugging.
16535 *
16536 * For more information on precompiling templates see
16537 * [lodash's custom builds documentation](https://lodash.com/custom-builds).
16538 *
16539 * For more information on Chrome extension sandboxes see
16540 * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
16541 *
16542 * @static
16543 * @memberOf _
16544 * @category String
16545 * @param {string} [string=''] The template string.
16546 * @param {Object} [options] The options object.
16547 * @param {RegExp} [options.escape] The HTML "escape" delimiter.
16548 * @param {RegExp} [options.evaluate] The "evaluate" delimiter.
16549 * @param {Object} [options.imports] An object to import into the template as free variables.
16550 * @param {RegExp} [options.interpolate] The "interpolate" delimiter.
16551 * @param {string} [options.sourceURL] The sourceURL of the template's compiled source.
16552 * @param {string} [options.variable] The data object variable name.
16553 * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
16554 * @returns {Function} Returns the compiled template function.
16555 * @example
16556 *
16557 * // Use the "interpolate" delimiter to create a compiled template.
16558 * var compiled = _.template('hello <%= user %>!');
16559 * compiled({ 'user': 'fred' });
16560 * // => 'hello fred!'
16561 *
16562 * // Use the HTML "escape" delimiter to escape data property values.
16563 * var compiled = _.template('<b><%- value %></b>');
16564 * compiled({ 'value': '<script>' });
16565 * // => '<b>&lt;script&gt;</b>'
16566 *
16567 * // Use the "evaluate" delimiter to execute JavaScript and generate HTML.
16568 * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
16569 * compiled({ 'users': ['fred', 'barney'] });
16570 * // => '<li>fred</li><li>barney</li>'
16571 *
16572 * // Use the internal `print` function in "evaluate" delimiters.
16573 * var compiled = _.template('<% print("hello " + user); %>!');
16574 * compiled({ 'user': 'barney' });
16575 * // => 'hello barney!'
16576 *
16577 * // Use the ES delimiter as an alternative to the default "interpolate" delimiter.
16578 * var compiled = _.template('hello ${ user }!');
16579 * compiled({ 'user': 'pebbles' });
16580 * // => 'hello pebbles!'
16581 *
16582 * // Use custom template delimiters.
16583 * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
16584 * var compiled = _.template('hello {{ user }}!');
16585 * compiled({ 'user': 'mustache' });
16586 * // => 'hello mustache!'
16587 *
16588 * // Use backslashes to treat delimiters as plain text.
16589 * var compiled = _.template('<%= "\\<%- value %\\>" %>');
16590 * compiled({ 'value': 'ignored' });
16591 * // => '<%- value %>'
16592 *
16593 * // Use the `imports` option to import `jQuery` as `jq`.
16594 * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
16595 * var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
16596 * compiled({ 'users': ['fred', 'barney'] });
16597 * // => '<li>fred</li><li>barney</li>'
16598 *
16599 * // Use the `sourceURL` option to specify a custom sourceURL for the template.
16600 * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
16601 * compiled(data);
16602 * // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
16603 *
16604 * // Use the `variable` option to ensure a with-statement isn't used in the compiled template.
16605 * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
16606 * compiled.source;
16607 * // => function(data) {
16608 * // var __t, __p = '';
16609 * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
16610 * // return __p;
16611 * // }
16612 *
16613 * // Use the `source` property to inline compiled templates for meaningful
16614 * // line numbers in error messages and stack traces.
16615 * fs.writeFileSync(path.join(cwd, 'jst.js'), '\
16616 * var JST = {\
16617 * "main": ' + _.template(mainText).source + '\
16618 * };\
16619 * ');
16620 */
16621 function template(string, options, guard) {
16622 // Based on John Resig's `tmpl` implementation (http://ejohn.org/blog/javascript-micro-templating/)
16623 // and Laura Doktorova's doT.js (https://github.com/olado/doT).
16624 var settings = lodash.templateSettings;
16625
16626 if (guard && isIterateeCall(string, options, guard)) {
16627 options = undefined;
16628 }
16629 string = toString(string);
16630 options = assignInWith({}, options, settings, assignInDefaults);
16631
16632 var imports = assignInWith({}, options.imports, settings.imports, assignInDefaults),
16633 importsKeys = keys(imports),
16634 importsValues = baseValues(imports, importsKeys);
16635
16636 var isEscaping,
16637 isEvaluating,
16638 index = 0,
16639 interpolate = options.interpolate || reNoMatch,
16640 source = "__p += '";
16641
16642 // Compile the regexp to match each delimiter.
16643 var reDelimiters = RegExp(
16644 (options.escape || reNoMatch).source + '|' +
16645 interpolate.source + '|' +
16646 (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
16647 (options.evaluate || reNoMatch).source + '|$'
16648 , 'g');
16649
16650 // Use a sourceURL for easier debugging.
16651 var sourceURL = '//# sourceURL=' +
16652 ('sourceURL' in options
16653 ? options.sourceURL
16654 : ('lodash.templateSources[' + (++templateCounter) + ']')
16655 ) + '\n';
16656
16657 string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
16658 interpolateValue || (interpolateValue = esTemplateValue);
16659
16660 // Escape characters that can't be included in string literals.
16661 source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
16662
16663 // Replace delimiters with snippets.
16664 if (escapeValue) {
16665 isEscaping = true;
16666 source += "' +\n__e(" + escapeValue + ") +\n'";
16667 }
16668 if (evaluateValue) {
16669 isEvaluating = true;
16670 source += "';\n" + evaluateValue + ";\n__p += '";
16671 }
16672 if (interpolateValue) {
16673 source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
16674 }
16675 index = offset + match.length;
16676
16677 // The JS engine embedded in Adobe products needs `match` returned in
16678 // order to produce the correct `offset` value.
16679 return match;
16680 });
16681
16682 source += "';\n";
16683
16684 // If `variable` is not specified wrap a with-statement around the generated
16685 // code to add the data object to the top of the scope chain.
16686 var variable = options.variable;
16687 if (!variable) {
16688 source = 'with (obj) {\n' + source + '\n}\n';
16689 }
16690 // Cleanup code by stripping empty strings.
16691 source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
16692 .replace(reEmptyStringMiddle, '$1')
16693 .replace(reEmptyStringTrailing, '$1;');
16694
16695 // Frame code as the function body.
16696 source = 'function(' + (variable || 'obj') + ') {\n' +
16697 (variable
16698 ? ''
16699 : 'obj || (obj = {});\n'
16700 ) +
16701 "var __t, __p = ''" +
16702 (isEscaping
16703 ? ', __e = _.escape'
16704 : ''
16705 ) +
16706 (isEvaluating
16707 ? ', __j = Array.prototype.join;\n' +
16708 "function print() { __p += __j.call(arguments, '') }\n"
16709 : ';\n'
16710 ) +
16711 source +
16712 'return __p\n}';
16713
16714 var result = attempt(function() {
16715 return Function(importsKeys, sourceURL + 'return ' + source)
16716 .apply(undefined, importsValues);
16717 });
16718
16719 // Provide the compiled function's source by its `toString` method or
16720 // the `source` property as a convenience for inlining compiled templates.
16721 result.source = source;
16722 if (isError(result)) {
16723 throw result;
16724 }
16725 return result;
16726 }
16727
16728 /**
16729 * Converts `string`, as a whole, to lower case just like
16730 * [String#toLowerCase](https://mdn.io/toLowerCase).
16731 *
16732 * @static
16733 * @memberOf _
16734 * @category String
16735 * @param {string} [string=''] The string to convert.
16736 * @returns {string} Returns the lower cased string.
16737 * @example
16738 *
16739 * _.toLower('--Foo-Bar');
16740 * // => '--foo-bar'
16741 *
16742 * _.toLower('fooBar');
16743 * // => 'foobar'
16744 *
16745 * _.toLower('__FOO_BAR__');
16746 * // => '__foo_bar__'
16747 */
16748 function toLower(value) {
16749 return toString(value).toLowerCase();
16750 }
16751
16752 /**
16753 * Converts `string`, as a whole, to upper case just like
16754 * [String#toUpperCase](https://mdn.io/toUpperCase).
16755 *
16756 * @static
16757 * @memberOf _
16758 * @category String
16759 * @param {string} [string=''] The string to convert.
16760 * @returns {string} Returns the upper cased string.
16761 * @example
16762 *
16763 * _.toUpper('--foo-bar');
16764 * // => '--FOO-BAR'
16765 *
16766 * _.toUpper('fooBar');
16767 * // => 'FOOBAR'
16768 *
16769 * _.toUpper('__foo_bar__');
16770 * // => '__FOO_BAR__'
16771 */
16772 function toUpper(value) {
16773 return toString(value).toUpperCase();
16774 }
16775
16776 /**
16777 * Removes leading and trailing whitespace or specified characters from `string`.
16778 *
16779 * @static
16780 * @memberOf _
16781 * @category String
16782 * @param {string} [string=''] The string to trim.
16783 * @param {string} [chars=whitespace] The characters to trim.
16784 * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
16785 * @returns {string} Returns the trimmed string.
16786 * @example
16787 *
16788 * _.trim(' abc ');
16789 * // => 'abc'
16790 *
16791 * _.trim('-_-abc-_-', '_-');
16792 * // => 'abc'
16793 *
16794 * _.map([' foo ', ' bar '], _.trim);
16795 * // => ['foo', 'bar']
16796 */
16797 function trim(string, chars, guard) {
16798 string = toString(string);
16799 if (!string) {
16800 return string;
16801 }
16802 if (guard || chars === undefined) {
16803 return string.replace(reTrim, '');
16804 }
16805 chars = (chars + '');
16806 if (!chars) {
16807 return string;
16808 }
16809 var strSymbols = stringToArray(string),
16810 chrSymbols = stringToArray(chars);
16811
16812 return strSymbols
16813 .slice(charsStartIndex(strSymbols, chrSymbols), charsEndIndex(strSymbols, chrSymbols) + 1)
16814 .join('');
16815 }
16816
16817 /**
16818 * Removes trailing whitespace or specified characters from `string`.
16819 *
16820 * @static
16821 * @memberOf _
16822 * @category String
16823 * @param {string} [string=''] The string to trim.
16824 * @param {string} [chars=whitespace] The characters to trim.
16825 * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
16826 * @returns {string} Returns the trimmed string.
16827 * @example
16828 *
16829 * _.trimEnd(' abc ');
16830 * // => ' abc'
16831 *
16832 * _.trimEnd('-_-abc-_-', '_-');
16833 * // => '-_-abc'
16834 */
16835 function trimEnd(string, chars, guard) {
16836 string = toString(string);
16837 if (!string) {
16838 return string;
16839 }
16840 if (guard || chars === undefined) {
16841 return string.replace(reTrimEnd, '');
16842 }
16843 chars = (chars + '');
16844 if (!chars) {
16845 return string;
16846 }
16847 var strSymbols = stringToArray(string);
16848 return strSymbols
16849 .slice(0, charsEndIndex(strSymbols, stringToArray(chars)) + 1)
16850 .join('');
16851 }
16852
16853 /**
16854 * Removes leading whitespace or specified characters from `string`.
16855 *
16856 * @static
16857 * @memberOf _
16858 * @category String
16859 * @param {string} [string=''] The string to trim.
16860 * @param {string} [chars=whitespace] The characters to trim.
16861 * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
16862 * @returns {string} Returns the trimmed string.
16863 * @example
16864 *
16865 * _.trimStart(' abc ');
16866 * // => 'abc '
16867 *
16868 * _.trimStart('-_-abc-_-', '_-');
16869 * // => 'abc-_-'
16870 */
16871 function trimStart(string, chars, guard) {
16872 string = toString(string);
16873 if (!string) {
16874 return string;
16875 }
16876 if (guard || chars === undefined) {
16877 return string.replace(reTrimStart, '');
16878 }
16879 chars = (chars + '');
16880 if (!chars) {
16881 return string;
16882 }
16883 var strSymbols = stringToArray(string);
16884 return strSymbols
16885 .slice(charsStartIndex(strSymbols, stringToArray(chars)))
16886 .join('');
16887 }
16888
16889 /**
16890 * Truncates `string` if it's longer than the given maximum string length.
16891 * The last characters of the truncated string are replaced with the omission
16892 * string which defaults to "...".
16893 *
16894 * @static
16895 * @memberOf _
16896 * @category String
16897 * @param {string} [string=''] The string to truncate.
16898 * @param {Object} [options=({})] The options object.
16899 * @param {number} [options.length=30] The maximum string length.
16900 * @param {string} [options.omission='...'] The string to indicate text is omitted.
16901 * @param {RegExp|string} [options.separator] The separator pattern to truncate to.
16902 * @returns {string} Returns the truncated string.
16903 * @example
16904 *
16905 * _.truncate('hi-diddly-ho there, neighborino');
16906 * // => 'hi-diddly-ho there, neighbo...'
16907 *
16908 * _.truncate('hi-diddly-ho there, neighborino', {
16909 * 'length': 24,
16910 * 'separator': ' '
16911 * });
16912 * // => 'hi-diddly-ho there,...'
16913 *
16914 * _.truncate('hi-diddly-ho there, neighborino', {
16915 * 'length': 24,
16916 * 'separator': /,? +/
16917 * });
16918 * // => 'hi-diddly-ho there...'
16919 *
16920 * _.truncate('hi-diddly-ho there, neighborino', {
16921 * 'omission': ' [...]'
16922 * });
16923 * // => 'hi-diddly-ho there, neig [...]'
16924 */
16925 function truncate(string, options) {
16926 var length = DEFAULT_TRUNC_LENGTH,
16927 omission = DEFAULT_TRUNC_OMISSION;
16928
16929 if (isObject(options)) {
16930 var separator = 'separator' in options ? options.separator : separator;
16931 length = 'length' in options ? toInteger(options.length) : length;
16932 omission = 'omission' in options ? toString(options.omission) : omission;
16933 }
16934 string = toString(string);
16935
16936 var strLength = string.length;
16937 if (reHasComplexSymbol.test(string)) {
16938 var strSymbols = stringToArray(string);
16939 strLength = strSymbols.length;
16940 }
16941 if (length >= strLength) {
16942 return string;
16943 }
16944 var end = length - stringSize(omission);
16945 if (end < 1) {
16946 return omission;
16947 }
16948 var result = strSymbols
16949 ? strSymbols.slice(0, end).join('')
16950 : string.slice(0, end);
16951
16952 if (separator === undefined) {
16953 return result + omission;
16954 }
16955 if (strSymbols) {
16956 end += (result.length - end);
16957 }
16958 if (isRegExp(separator)) {
16959 if (string.slice(end).search(separator)) {
16960 var match,
16961 substring = result;
16962
16963 if (!separator.global) {
16964 separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g');
16965 }
16966 separator.lastIndex = 0;
16967 while ((match = separator.exec(substring))) {
16968 var newEnd = match.index;
16969 }
16970 result = result.slice(0, newEnd === undefined ? end : newEnd);
16971 }
16972 } else if (string.indexOf(separator, end) != end) {
16973 var index = result.lastIndexOf(separator);
16974 if (index > -1) {
16975 result = result.slice(0, index);
16976 }
16977 }
16978 return result + omission;
16979 }
16980
16981 /**
16982 * The inverse of `_.escape`; this method converts the HTML entities
16983 * `&amp;`, `&lt;`, `&gt;`, `&quot;`, `&#39;`, and `&#96;` in `string` to their
16984 * corresponding characters.
16985 *
16986 * **Note:** No other HTML entities are unescaped. To unescape additional HTML
16987 * entities use a third-party library like [_he_](https://mths.be/he).
16988 *
16989 * @static
16990 * @memberOf _
16991 * @category String
16992 * @param {string} [string=''] The string to unescape.
16993 * @returns {string} Returns the unescaped string.
16994 * @example
16995 *
16996 * _.unescape('fred, barney, &amp; pebbles');
16997 * // => 'fred, barney, & pebbles'
16998 */
16999 function unescape(string) {
17000 string = toString(string);
17001 return (string && reHasEscapedHtml.test(string))
17002 ? string.replace(reEscapedHtml, unescapeHtmlChar)
17003 : string;
17004 }
17005
17006 /**
17007 * Converts `string`, as space separated words, to upper case.
17008 *
17009 * @static
17010 * @memberOf _
17011 * @category String
17012 * @param {string} [string=''] The string to convert.
17013 * @returns {string} Returns the upper cased string.
17014 * @example
17015 *
17016 * _.upperCase('--foo-bar');
17017 * // => 'FOO BAR'
17018 *
17019 * _.upperCase('fooBar');
17020 * // => 'FOO BAR'
17021 *
17022 * _.upperCase('__foo_bar__');
17023 * // => 'FOO BAR'
17024 */
17025 var upperCase = createCompounder(function(result, word, index) {
17026 return result + (index ? ' ' : '') + word.toUpperCase();
17027 });
17028
17029 /**
17030 * Splits `string` into an array of its words.
17031 *
17032 * @static
17033 * @memberOf _
17034 * @category String
17035 * @param {string} [string=''] The string to inspect.
17036 * @param {RegExp|string} [pattern] The pattern to match words.
17037 * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
17038 * @returns {Array} Returns the words of `string`.
17039 * @example
17040 *
17041 * _.words('fred, barney, & pebbles');
17042 * // => ['fred', 'barney', 'pebbles']
17043 *
17044 * _.words('fred, barney, & pebbles', /[^, ]+/g);
17045 * // => ['fred', 'barney', '&', 'pebbles']
17046 */
17047 function words(string, pattern, guard) {
17048 string = toString(string);
17049 pattern = guard ? undefined : pattern;
17050
17051 if (pattern === undefined) {
17052 pattern = reHasComplexWord.test(string) ? reComplexWord : reBasicWord;
17053 }
17054 return string.match(pattern) || [];
17055 }
17056
17057 /*------------------------------------------------------------------------*/
17058
17059 /**
17060 * Attempts to invoke `func`, returning either the result or the caught error
17061 * object. Any additional arguments are provided to `func` when it's invoked.
17062 *
17063 * @static
17064 * @memberOf _
17065 * @category Util
17066 * @param {Function} func The function to attempt.
17067 * @returns {*} Returns the `func` result or error object.
17068 * @example
17069 *
17070 * // Avoid throwing errors for invalid selectors.
17071 * var elements = _.attempt(function(selector) {
17072 * return document.querySelectorAll(selector);
17073 * }, '>_>');
17074 *
17075 * if (_.isError(elements)) {
17076 * elements = [];
17077 * }
17078 */
17079 var attempt = rest(function(func, args) {
17080 try {
17081 return apply(func, undefined, args);
17082 } catch (e) {
17083 return isError(e) ? e : new Error(e);
17084 }
17085 });
17086
17087 /**
17088 * Binds methods of an object to the object itself, overwriting the existing
17089 * method.
17090 *
17091 * **Note:** This method doesn't set the "length" property of bound functions.
17092 *
17093 * @static
17094 * @memberOf _
17095 * @category Util
17096 * @param {Object} object The object to bind and assign the bound methods to.
17097 * @param {...(string|string[])} methodNames The object method names to bind,
17098 * specified individually or in arrays.
17099 * @returns {Object} Returns `object`.
17100 * @example
17101 *
17102 * var view = {
17103 * 'label': 'docs',
17104 * 'onClick': function() {
17105 * console.log('clicked ' + this.label);
17106 * }
17107 * };
17108 *
17109 * _.bindAll(view, 'onClick');
17110 * jQuery(element).on('click', view.onClick);
17111 * // => logs 'clicked docs' when clicked
17112 */
17113 var bindAll = rest(function(object, methodNames) {
17114 arrayEach(baseFlatten(methodNames, 1), function(key) {
17115 object[key] = bind(object[key], object);
17116 });
17117 return object;
17118 });
17119
17120 /**
17121 * Creates a function that iterates over `pairs` invoking the corresponding
17122 * function of the first predicate to return truthy. The predicate-function
17123 * pairs are invoked with the `this` binding and arguments of the created
17124 * function.
17125 *
17126 * @static
17127 * @memberOf _
17128 * @category Util
17129 * @param {Array} pairs The predicate-function pairs.
17130 * @returns {Function} Returns the new function.
17131 * @example
17132 *
17133 * var func = _.cond([
17134 * [_.matches({ 'a': 1 }), _.constant('matches A')],
17135 * [_.conforms({ 'b': _.isNumber }), _.constant('matches B')],
17136 * [_.constant(true), _.constant('no match')]
17137 * ]);
17138 *
17139 * func({ 'a': 1, 'b': 2 });
17140 * // => 'matches A'
17141 *
17142 * func({ 'a': 0, 'b': 1 });
17143 * // => 'matches B'
17144 *
17145 * func({ 'a': '1', 'b': '2' });
17146 * // => 'no match'
17147 */
17148 function cond(pairs) {
17149 var length = pairs ? pairs.length : 0,
17150 toIteratee = getIteratee();
17151
17152 pairs = !length ? [] : arrayMap(pairs, function(pair) {
17153 if (typeof pair[1] != 'function') {
17154 throw new TypeError(FUNC_ERROR_TEXT);
17155 }
17156 return [toIteratee(pair[0]), pair[1]];
17157 });
17158
17159 return rest(function(args) {
17160 var index = -1;
17161 while (++index < length) {
17162 var pair = pairs[index];
17163 if (apply(pair[0], this, args)) {
17164 return apply(pair[1], this, args);
17165 }
17166 }
17167 });
17168 }
17169
17170 /**
17171 * Creates a function that invokes the predicate properties of `source` with
17172 * the corresponding property values of a given object, returning `true` if
17173 * all predicates return truthy, else `false`.
17174 *
17175 * @static
17176 * @memberOf _
17177 * @category Util
17178 * @param {Object} source The object of property predicates to conform to.
17179 * @returns {Function} Returns the new function.
17180 * @example
17181 *
17182 * var users = [
17183 * { 'user': 'barney', 'age': 36 },
17184 * { 'user': 'fred', 'age': 40 }
17185 * ];
17186 *
17187 * _.filter(users, _.conforms({ 'age': _.partial(_.gt, _, 38) }));
17188 * // => [{ 'user': 'fred', 'age': 40 }]
17189 */
17190 function conforms(source) {
17191 return baseConforms(baseClone(source, true));
17192 }
17193
17194 /**
17195 * Creates a function that returns `value`.
17196 *
17197 * @static
17198 * @memberOf _
17199 * @category Util
17200 * @param {*} value The value to return from the new function.
17201 * @returns {Function} Returns the new function.
17202 * @example
17203 *
17204 * var object = { 'user': 'fred' };
17205 * var getter = _.constant(object);
17206 *
17207 * getter() === object;
17208 * // => true
17209 */
17210 function constant(value) {
17211 return function() {
17212 return value;
17213 };
17214 }
17215
17216 /**
17217 * Creates a function that returns the result of invoking the given functions
17218 * with the `this` binding of the created function, where each successive
17219 * invocation is supplied the return value of the previous.
17220 *
17221 * @static
17222 * @memberOf _
17223 * @category Util
17224 * @param {...(Function|Function[])} [funcs] Functions to invoke.
17225 * @returns {Function} Returns the new function.
17226 * @example
17227 *
17228 * function square(n) {
17229 * return n * n;
17230 * }
17231 *
17232 * var addSquare = _.flow(_.add, square);
17233 * addSquare(1, 2);
17234 * // => 9
17235 */
17236 var flow = createFlow();
17237
17238 /**
17239 * This method is like `_.flow` except that it creates a function that
17240 * invokes the given functions from right to left.
17241 *
17242 * @static
17243 * @memberOf _
17244 * @category Util
17245 * @param {...(Function|Function[])} [funcs] Functions to invoke.
17246 * @returns {Function} Returns the new function.
17247 * @example
17248 *
17249 * function square(n) {
17250 * return n * n;
17251 * }
17252 *
17253 * var addSquare = _.flowRight(square, _.add);
17254 * addSquare(1, 2);
17255 * // => 9
17256 */
17257 var flowRight = createFlow(true);
17258
17259 /**
17260 * This method returns the first argument given to it.
17261 *
17262 * @static
17263 * @memberOf _
17264 * @category Util
17265 * @param {*} value Any value.
17266 * @returns {*} Returns `value`.
17267 * @example
17268 *
17269 * var object = { 'user': 'fred' };
17270 *
17271 * _.identity(object) === object;
17272 * // => true
17273 */
17274 function identity(value) {
17275 return value;
17276 }
17277
17278 /**
17279 * Creates a function that invokes `func` with the arguments of the created
17280 * function. If `func` is a property name the created callback returns the
17281 * property value for a given element. If `func` is an object the created
17282 * callback returns `true` for elements that contain the equivalent object
17283 * properties, otherwise it returns `false`.
17284 *
17285 * @static
17286 * @memberOf _
17287 * @category Util
17288 * @param {*} [func=_.identity] The value to convert to a callback.
17289 * @returns {Function} Returns the callback.
17290 * @example
17291 *
17292 * var users = [
17293 * { 'user': 'barney', 'age': 36 },
17294 * { 'user': 'fred', 'age': 40 }
17295 * ];
17296 *
17297 * // Create custom iteratee shorthands.
17298 * _.iteratee = _.wrap(_.iteratee, function(callback, func) {
17299 * var p = /^(\S+)\s*([<>])\s*(\S+)$/.exec(func);
17300 * return !p ? callback(func) : function(object) {
17301 * return (p[2] == '>' ? object[p[1]] > p[3] : object[p[1]] < p[3]);
17302 * };
17303 * });
17304 *
17305 * _.filter(users, 'age > 36');
17306 * // => [{ 'user': 'fred', 'age': 40 }]
17307 */
17308 function iteratee(func) {
17309 return baseIteratee(typeof func == 'function' ? func : baseClone(func, true));
17310 }
17311
17312 /**
17313 * Creates a function that performs a partial deep comparison between a given
17314 * object and `source`, returning `true` if the given object has equivalent
17315 * property values, else `false`. The created function is equivalent to
17316 * `_.isMatch` with a `source` partially applied.
17317 *
17318 * **Note:** This method supports comparing the same values as `_.isEqual`.
17319 *
17320 * @static
17321 * @memberOf _
17322 * @category Util
17323 * @param {Object} source The object of property values to match.
17324 * @returns {Function} Returns the new function.
17325 * @example
17326 *
17327 * var users = [
17328 * { 'user': 'barney', 'age': 36, 'active': true },
17329 * { 'user': 'fred', 'age': 40, 'active': false }
17330 * ];
17331 *
17332 * _.filter(users, _.matches({ 'age': 40, 'active': false }));
17333 * // => [{ 'user': 'fred', 'age': 40, 'active': false }]
17334 */
17335 function matches(source) {
17336 return baseMatches(baseClone(source, true));
17337 }
17338
17339 /**
17340 * Creates a function that performs a partial deep comparison between the
17341 * value at `path` of a given object to `srcValue`, returning `true` if the
17342 * object value is equivalent, else `false`.
17343 *
17344 * **Note:** This method supports comparing the same values as `_.isEqual`.
17345 *
17346 * @static
17347 * @memberOf _
17348 * @category Util
17349 * @param {Array|string} path The path of the property to get.
17350 * @param {*} srcValue The value to match.
17351 * @returns {Function} Returns the new function.
17352 * @example
17353 *
17354 * var users = [
17355 * { 'user': 'barney' },
17356 * { 'user': 'fred' }
17357 * ];
17358 *
17359 * _.find(users, _.matchesProperty('user', 'fred'));
17360 * // => { 'user': 'fred' }
17361 */
17362 function matchesProperty(path, srcValue) {
17363 return baseMatchesProperty(path, baseClone(srcValue, true));
17364 }
17365
17366 /**
17367 * Creates a function that invokes the method at `path` of a given object.
17368 * Any additional arguments are provided to the invoked method.
17369 *
17370 * @static
17371 * @memberOf _
17372 * @category Util
17373 * @param {Array|string} path The path of the method to invoke.
17374 * @param {...*} [args] The arguments to invoke the method with.
17375 * @returns {Function} Returns the new function.
17376 * @example
17377 *
17378 * var objects = [
17379 * { 'a': { 'b': { 'c': _.constant(2) } } },
17380 * { 'a': { 'b': { 'c': _.constant(1) } } }
17381 * ];
17382 *
17383 * _.map(objects, _.method('a.b.c'));
17384 * // => [2, 1]
17385 *
17386 * _.invokeMap(_.sortBy(objects, _.method(['a', 'b', 'c'])), 'a.b.c');
17387 * // => [1, 2]
17388 */
17389 var method = rest(function(path, args) {
17390 return function(object) {
17391 return baseInvoke(object, path, args);
17392 };
17393 });
17394
17395 /**
17396 * The opposite of `_.method`; this method creates a function that invokes
17397 * the method at a given path of `object`. Any additional arguments are
17398 * provided to the invoked method.
17399 *
17400 * @static
17401 * @memberOf _
17402 * @category Util
17403 * @param {Object} object The object to query.
17404 * @param {...*} [args] The arguments to invoke the method with.
17405 * @returns {Function} Returns the new function.
17406 * @example
17407 *
17408 * var array = _.times(3, _.constant),
17409 * object = { 'a': array, 'b': array, 'c': array };
17410 *
17411 * _.map(['a[2]', 'c[0]'], _.methodOf(object));
17412 * // => [2, 0]
17413 *
17414 * _.map([['a', '2'], ['c', '0']], _.methodOf(object));
17415 * // => [2, 0]
17416 */
17417 var methodOf = rest(function(object, args) {
17418 return function(path) {
17419 return baseInvoke(object, path, args);
17420 };
17421 });
17422
17423 /**
17424 * Adds all own enumerable function properties of a source object to the
17425 * destination object. If `object` is a function then methods are added to
17426 * its prototype as well.
17427 *
17428 * **Note:** Use `_.runInContext` to create a pristine `lodash` function to
17429 * avoid conflicts caused by modifying the original.
17430 *
17431 * @static
17432 * @memberOf _
17433 * @category Util
17434 * @param {Function|Object} [object=lodash] The destination object.
17435 * @param {Object} source The object of functions to add.
17436 * @param {Object} [options] The options object.
17437 * @param {boolean} [options.chain=true] Specify whether the functions added
17438 * are chainable.
17439 * @returns {Function|Object} Returns `object`.
17440 * @example
17441 *
17442 * function vowels(string) {
17443 * return _.filter(string, function(v) {
17444 * return /[aeiou]/i.test(v);
17445 * });
17446 * }
17447 *
17448 * _.mixin({ 'vowels': vowels });
17449 * _.vowels('fred');
17450 * // => ['e']
17451 *
17452 * _('fred').vowels().value();
17453 * // => ['e']
17454 *
17455 * _.mixin({ 'vowels': vowels }, { 'chain': false });
17456 * _('fred').vowels();
17457 * // => ['e']
17458 */
17459 function mixin(object, source, options) {
17460 var props = keys(source),
17461 methodNames = baseFunctions(source, props);
17462
17463 if (options == null &&
17464 !(isObject(source) && (methodNames.length || !props.length))) {
17465 options = source;
17466 source = object;
17467 object = this;
17468 methodNames = baseFunctions(source, keys(source));
17469 }
17470 var chain = (isObject(options) && 'chain' in options) ? options.chain : true,
17471 isFunc = isFunction(object);
17472
17473 arrayEach(methodNames, function(methodName) {
17474 var func = source[methodName];
17475 object[methodName] = func;
17476 if (isFunc) {
17477 object.prototype[methodName] = function() {
17478 var chainAll = this.__chain__;
17479 if (chain || chainAll) {
17480 var result = object(this.__wrapped__),
17481 actions = result.__actions__ = copyArray(this.__actions__);
17482
17483 actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
17484 result.__chain__ = chainAll;
17485 return result;
17486 }
17487 return func.apply(object, arrayPush([this.value()], arguments));
17488 };
17489 }
17490 });
17491
17492 return object;
17493 }
17494
17495 /**
17496 * Reverts the `_` variable to its previous value and returns a reference to
17497 * the `lodash` function.
17498 *
17499 * @static
17500 * @memberOf _
17501 * @category Util
17502 * @returns {Function} Returns the `lodash` function.
17503 * @example
17504 *
17505 * var lodash = _.noConflict();
17506 */
17507 function noConflict() {
17508 if (root._ === this) {
17509 root._ = oldDash;
17510 }
17511 return this;
17512 }
17513
17514 /**
17515 * A no-operation function that returns `undefined` regardless of the
17516 * arguments it receives.
17517 *
17518 * @static
17519 * @memberOf _
17520 * @category Util
17521 * @example
17522 *
17523 * var object = { 'user': 'fred' };
17524 *
17525 * _.noop(object) === undefined;
17526 * // => true
17527 */
17528 function noop() {
17529 // No operation performed.
17530 }
17531
17532 /**
17533 * Creates a function that returns its nth argument.
17534 *
17535 * @static
17536 * @memberOf _
17537 * @category Util
17538 * @param {number} [n=0] The index of the argument to return.
17539 * @returns {Function} Returns the new function.
17540 * @example
17541 *
17542 * var func = _.nthArg(1);
17543 *
17544 * func('a', 'b', 'c');
17545 * // => 'b'
17546 */
17547 function nthArg(n) {
17548 n = toInteger(n);
17549 return function() {
17550 return arguments[n];
17551 };
17552 }
17553
17554 /**
17555 * Creates a function that invokes `iteratees` with the arguments provided
17556 * to the created function and returns their results.
17557 *
17558 * @static
17559 * @memberOf _
17560 * @category Util
17561 * @param {...(Function|Function[])} iteratees The iteratees to invoke.
17562 * @returns {Function} Returns the new function.
17563 * @example
17564 *
17565 * var func = _.over(Math.max, Math.min);
17566 *
17567 * func(1, 2, 3, 4);
17568 * // => [4, 1]
17569 */
17570 var over = createOver(arrayMap);
17571
17572 /**
17573 * Creates a function that checks if **all** of the `predicates` return
17574 * truthy when invoked with the arguments provided to the created function.
17575 *
17576 * @static
17577 * @memberOf _
17578 * @category Util
17579 * @param {...(Function|Function[])} predicates The predicates to check.
17580 * @returns {Function} Returns the new function.
17581 * @example
17582 *
17583 * var func = _.overEvery(Boolean, isFinite);
17584 *
17585 * func('1');
17586 * // => true
17587 *
17588 * func(null);
17589 * // => false
17590 *
17591 * func(NaN);
17592 * // => false
17593 */
17594 var overEvery = createOver(arrayEvery);
17595
17596 /**
17597 * Creates a function that checks if **any** of the `predicates` return
17598 * truthy when invoked with the arguments provided to the created function.
17599 *
17600 * @static
17601 * @memberOf _
17602 * @category Util
17603 * @param {...(Function|Function[])} predicates The predicates to check.
17604 * @returns {Function} Returns the new function.
17605 * @example
17606 *
17607 * var func = _.overSome(Boolean, isFinite);
17608 *
17609 * func('1');
17610 * // => true
17611 *
17612 * func(null);
17613 * // => true
17614 *
17615 * func(NaN);
17616 * // => false
17617 */
17618 var overSome = createOver(arraySome);
17619
17620 /**
17621 * Creates a function that returns the value at `path` of a given object.
17622 *
17623 * @static
17624 * @memberOf _
17625 * @category Util
17626 * @param {Array|string} path The path of the property to get.
17627 * @returns {Function} Returns the new function.
17628 * @example
17629 *
17630 * var objects = [
17631 * { 'a': { 'b': { 'c': 2 } } },
17632 * { 'a': { 'b': { 'c': 1 } } }
17633 * ];
17634 *
17635 * _.map(objects, _.property('a.b.c'));
17636 * // => [2, 1]
17637 *
17638 * _.map(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c');
17639 * // => [1, 2]
17640 */
17641 function property(path) {
17642 return isKey(path) ? baseProperty(path) : basePropertyDeep(path);
17643 }
17644
17645 /**
17646 * The opposite of `_.property`; this method creates a function that returns
17647 * the value at a given path of `object`.
17648 *
17649 * @static
17650 * @memberOf _
17651 * @category Util
17652 * @param {Object} object The object to query.
17653 * @returns {Function} Returns the new function.
17654 * @example
17655 *
17656 * var array = [0, 1, 2],
17657 * object = { 'a': array, 'b': array, 'c': array };
17658 *
17659 * _.map(['a[2]', 'c[0]'], _.propertyOf(object));
17660 * // => [2, 0]
17661 *
17662 * _.map([['a', '2'], ['c', '0']], _.propertyOf(object));
17663 * // => [2, 0]
17664 */
17665 function propertyOf(object) {
17666 return function(path) {
17667 return object == null ? undefined : baseGet(object, path);
17668 };
17669 }
17670
17671 /**
17672 * Creates an array of numbers (positive and/or negative) progressing from
17673 * `start` up to, but not including, `end`. A step of `-1` is used if a negative
17674 * `start` is specified without an `end` or `step`. If `end` is not specified
17675 * it's set to `start` with `start` then set to `0`.
17676 *
17677 * **Note:** JavaScript follows the IEEE-754 standard for resolving
17678 * floating-point values which can produce unexpected results.
17679 *
17680 * @static
17681 * @memberOf _
17682 * @category Util
17683 * @param {number} [start=0] The start of the range.
17684 * @param {number} end The end of the range.
17685 * @param {number} [step=1] The value to increment or decrement by.
17686 * @returns {Array} Returns the new array of numbers.
17687 * @example
17688 *
17689 * _.range(4);
17690 * // => [0, 1, 2, 3]
17691 *
17692 * _.range(-4);
17693 * // => [0, -1, -2, -3]
17694 *
17695 * _.range(1, 5);
17696 * // => [1, 2, 3, 4]
17697 *
17698 * _.range(0, 20, 5);
17699 * // => [0, 5, 10, 15]
17700 *
17701 * _.range(0, -4, -1);
17702 * // => [0, -1, -2, -3]
17703 *
17704 * _.range(1, 4, 0);
17705 * // => [1, 1, 1]
17706 *
17707 * _.range(0);
17708 * // => []
17709 */
17710 var range = createRange();
17711
17712 /**
17713 * This method is like `_.range` except that it populates values in
17714 * descending order.
17715 *
17716 * @static
17717 * @memberOf _
17718 * @category Util
17719 * @param {number} [start=0] The start of the range.
17720 * @param {number} end The end of the range.
17721 * @param {number} [step=1] The value to increment or decrement by.
17722 * @returns {Array} Returns the new array of numbers.
17723 * @example
17724 *
17725 * _.rangeRight(4);
17726 * // => [3, 2, 1, 0]
17727 *
17728 * _.rangeRight(-4);
17729 * // => [-3, -2, -1, 0]
17730 *
17731 * _.rangeRight(1, 5);
17732 * // => [4, 3, 2, 1]
17733 *
17734 * _.rangeRight(0, 20, 5);
17735 * // => [15, 10, 5, 0]
17736 *
17737 * _.rangeRight(0, -4, -1);
17738 * // => [-3, -2, -1, 0]
17739 *
17740 * _.rangeRight(1, 4, 0);
17741 * // => [1, 1, 1]
17742 *
17743 * _.rangeRight(0);
17744 * // => []
17745 */
17746 var rangeRight = createRange(true);
17747
17748 /**
17749 * Invokes the iteratee `n` times, returning an array of the results of
17750 * each invocation. The iteratee is invoked with one argument; (index).
17751 *
17752 * @static
17753 * @memberOf _
17754 * @category Util
17755 * @param {number} n The number of times to invoke `iteratee`.
17756 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
17757 * @returns {Array} Returns the array of results.
17758 * @example
17759 *
17760 * _.times(3, String);
17761 * // => ['0', '1', '2']
17762 *
17763 * _.times(4, _.constant(true));
17764 * // => [true, true, true, true]
17765 */
17766 function times(n, iteratee) {
17767 n = toInteger(n);
17768 if (n < 1 || n > MAX_SAFE_INTEGER) {
17769 return [];
17770 }
17771 var index = MAX_ARRAY_LENGTH,
17772 length = nativeMin(n, MAX_ARRAY_LENGTH);
17773
17774 iteratee = baseCastFunction(iteratee);
17775 n -= MAX_ARRAY_LENGTH;
17776
17777 var result = baseTimes(length, iteratee);
17778 while (++index < n) {
17779 iteratee(index);
17780 }
17781 return result;
17782 }
17783
17784 /**
17785 * Converts `value` to a property path array.
17786 *
17787 * @static
17788 * @memberOf _
17789 * @category Util
17790 * @param {*} value The value to convert.
17791 * @returns {Array} Returns the new property path array.
17792 * @example
17793 *
17794 * _.toPath('a.b.c');
17795 * // => ['a', 'b', 'c']
17796 *
17797 * _.toPath('a[0].b.c');
17798 * // => ['a', '0', 'b', 'c']
17799 *
17800 * var path = ['a', 'b', 'c'],
17801 * newPath = _.toPath(path);
17802 *
17803 * console.log(newPath);
17804 * // => ['a', 'b', 'c']
17805 *
17806 * console.log(path === newPath);
17807 * // => false
17808 */
17809 function toPath(value) {
17810 return isArray(value) ? arrayMap(value, String) : stringToPath(value);
17811 }
17812
17813 /**
17814 * Generates a unique ID. If `prefix` is given the ID is appended to it.
17815 *
17816 * @static
17817 * @memberOf _
17818 * @category Util
17819 * @param {string} [prefix=''] The value to prefix the ID with.
17820 * @returns {string} Returns the unique ID.
17821 * @example
17822 *
17823 * _.uniqueId('contact_');
17824 * // => 'contact_104'
17825 *
17826 * _.uniqueId();
17827 * // => '105'
17828 */
17829 function uniqueId(prefix) {
17830 var id = ++idCounter;
17831 return toString(prefix) + id;
17832 }
17833
17834 /*------------------------------------------------------------------------*/
17835
17836 /**
17837 * Adds two numbers.
17838 *
17839 * @static
17840 * @memberOf _
17841 * @category Math
17842 * @param {number} augend The first number in an addition.
17843 * @param {number} addend The second number in an addition.
17844 * @returns {number} Returns the total.
17845 * @example
17846 *
17847 * _.add(6, 4);
17848 * // => 10
17849 */
17850 function add(augend, addend) {
17851 var result;
17852 if (augend === undefined && addend === undefined) {
17853 return 0;
17854 }
17855 if (augend !== undefined) {
17856 result = augend;
17857 }
17858 if (addend !== undefined) {
17859 result = result === undefined ? addend : (result + addend);
17860 }
17861 return result;
17862 }
17863
17864 /**
17865 * Computes `number` rounded up to `precision`.
17866 *
17867 * @static
17868 * @memberOf _
17869 * @category Math
17870 * @param {number} number The number to round up.
17871 * @param {number} [precision=0] The precision to round up to.
17872 * @returns {number} Returns the rounded up number.
17873 * @example
17874 *
17875 * _.ceil(4.006);
17876 * // => 5
17877 *
17878 * _.ceil(6.004, 2);
17879 * // => 6.01
17880 *
17881 * _.ceil(6040, -2);
17882 * // => 6100
17883 */
17884 var ceil = createRound('ceil');
17885
17886 /**
17887 * Computes `number` rounded down to `precision`.
17888 *
17889 * @static
17890 * @memberOf _
17891 * @category Math
17892 * @param {number} number The number to round down.
17893 * @param {number} [precision=0] The precision to round down to.
17894 * @returns {number} Returns the rounded down number.
17895 * @example
17896 *
17897 * _.floor(4.006);
17898 * // => 4
17899 *
17900 * _.floor(0.046, 2);
17901 * // => 0.04
17902 *
17903 * _.floor(4060, -2);
17904 * // => 4000
17905 */
17906 var floor = createRound('floor');
17907
17908 /**
17909 * Computes the maximum value of `array`. If `array` is empty or falsey
17910 * `undefined` is returned.
17911 *
17912 * @static
17913 * @memberOf _
17914 * @category Math
17915 * @param {Array} array The array to iterate over.
17916 * @returns {*} Returns the maximum value.
17917 * @example
17918 *
17919 * _.max([4, 2, 8, 6]);
17920 * // => 8
17921 *
17922 * _.max([]);
17923 * // => undefined
17924 */
17925 function max(array) {
17926 return (array && array.length)
17927 ? baseExtremum(array, identity, gt)
17928 : undefined;
17929 }
17930
17931 /**
17932 * This method is like `_.max` except that it accepts `iteratee` which is
17933 * invoked for each element in `array` to generate the criterion by which
17934 * the value is ranked. The iteratee is invoked with one argument: (value).
17935 *
17936 * @static
17937 * @memberOf _
17938 * @category Math
17939 * @param {Array} array The array to iterate over.
17940 * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element.
17941 * @returns {*} Returns the maximum value.
17942 * @example
17943 *
17944 * var objects = [{ 'n': 1 }, { 'n': 2 }];
17945 *
17946 * _.maxBy(objects, function(o) { return o.n; });
17947 * // => { 'n': 2 }
17948 *
17949 * // The `_.property` iteratee shorthand.
17950 * _.maxBy(objects, 'n');
17951 * // => { 'n': 2 }
17952 */
17953 function maxBy(array, iteratee) {
17954 return (array && array.length)
17955 ? baseExtremum(array, getIteratee(iteratee), gt)
17956 : undefined;
17957 }
17958
17959 /**
17960 * Computes the mean of the values in `array`.
17961 *
17962 * @static
17963 * @memberOf _
17964 * @category Math
17965 * @param {Array} array The array to iterate over.
17966 * @returns {number} Returns the mean.
17967 * @example
17968 *
17969 * _.mean([4, 2, 8, 6]);
17970 * // => 5
17971 */
17972 function mean(array) {
17973 return sum(array) / (array ? array.length : 0);
17974 }
17975
17976 /**
17977 * Computes the minimum value of `array`. If `array` is empty or falsey
17978 * `undefined` is returned.
17979 *
17980 * @static
17981 * @memberOf _
17982 * @category Math
17983 * @param {Array} array The array to iterate over.
17984 * @returns {*} Returns the minimum value.
17985 * @example
17986 *
17987 * _.min([4, 2, 8, 6]);
17988 * // => 2
17989 *
17990 * _.min([]);
17991 * // => undefined
17992 */
17993 function min(array) {
17994 return (array && array.length)
17995 ? baseExtremum(array, identity, lt)
17996 : undefined;
17997 }
17998
17999 /**
18000 * This method is like `_.min` except that it accepts `iteratee` which is
18001 * invoked for each element in `array` to generate the criterion by which
18002 * the value is ranked. The iteratee is invoked with one argument: (value).
18003 *
18004 * @static
18005 * @memberOf _
18006 * @category Math
18007 * @param {Array} array The array to iterate over.
18008 * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element.
18009 * @returns {*} Returns the minimum value.
18010 * @example
18011 *
18012 * var objects = [{ 'n': 1 }, { 'n': 2 }];
18013 *
18014 * _.minBy(objects, function(o) { return o.n; });
18015 * // => { 'n': 1 }
18016 *
18017 * // The `_.property` iteratee shorthand.
18018 * _.minBy(objects, 'n');
18019 * // => { 'n': 1 }
18020 */
18021 function minBy(array, iteratee) {
18022 return (array && array.length)
18023 ? baseExtremum(array, getIteratee(iteratee), lt)
18024 : undefined;
18025 }
18026
18027 /**
18028 * Computes `number` rounded to `precision`.
18029 *
18030 * @static
18031 * @memberOf _
18032 * @category Math
18033 * @param {number} number The number to round.
18034 * @param {number} [precision=0] The precision to round to.
18035 * @returns {number} Returns the rounded number.
18036 * @example
18037 *
18038 * _.round(4.006);
18039 * // => 4
18040 *
18041 * _.round(4.006, 2);
18042 * // => 4.01
18043 *
18044 * _.round(4060, -2);
18045 * // => 4100
18046 */
18047 var round = createRound('round');
18048
18049 /**
18050 * Subtract two numbers.
18051 *
18052 * @static
18053 * @memberOf _
18054 * @category Math
18055 * @param {number} minuend The first number in a subtraction.
18056 * @param {number} subtrahend The second number in a subtraction.
18057 * @returns {number} Returns the difference.
18058 * @example
18059 *
18060 * _.subtract(6, 4);
18061 * // => 2
18062 */
18063 function subtract(minuend, subtrahend) {
18064 var result;
18065 if (minuend === undefined && subtrahend === undefined) {
18066 return 0;
18067 }
18068 if (minuend !== undefined) {
18069 result = minuend;
18070 }
18071 if (subtrahend !== undefined) {
18072 result = result === undefined ? subtrahend : (result - subtrahend);
18073 }
18074 return result;
18075 }
18076
18077 /**
18078 * Computes the sum of the values in `array`.
18079 *
18080 * @static
18081 * @memberOf _
18082 * @category Math
18083 * @param {Array} array The array to iterate over.
18084 * @returns {number} Returns the sum.
18085 * @example
18086 *
18087 * _.sum([4, 2, 8, 6]);
18088 * // => 20
18089 */
18090 function sum(array) {
18091 return (array && array.length)
18092 ? baseSum(array, identity)
18093 : 0;
18094 }
18095
18096 /**
18097 * This method is like `_.sum` except that it accepts `iteratee` which is
18098 * invoked for each element in `array` to generate the value to be summed.
18099 * The iteratee is invoked with one argument: (value).
18100 *
18101 * @static
18102 * @memberOf _
18103 * @category Math
18104 * @param {Array} array The array to iterate over.
18105 * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element.
18106 * @returns {number} Returns the sum.
18107 * @example
18108 *
18109 * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
18110 *
18111 * _.sumBy(objects, function(o) { return o.n; });
18112 * // => 20
18113 *
18114 * // The `_.property` iteratee shorthand.
18115 * _.sumBy(objects, 'n');
18116 * // => 20
18117 */
18118 function sumBy(array, iteratee) {
18119 return (array && array.length)
18120 ? baseSum(array, getIteratee(iteratee))
18121 : 0;
18122 }
18123
18124 /*------------------------------------------------------------------------*/
18125
18126 // Ensure wrappers are instances of `baseLodash`.
18127 lodash.prototype = baseLodash.prototype;
18128 lodash.prototype.constructor = lodash;
18129
18130 LodashWrapper.prototype = baseCreate(baseLodash.prototype);
18131 LodashWrapper.prototype.constructor = LodashWrapper;
18132
18133 LazyWrapper.prototype = baseCreate(baseLodash.prototype);
18134 LazyWrapper.prototype.constructor = LazyWrapper;
18135
18136 // Avoid inheriting from `Object.prototype` when possible.
18137 Hash.prototype = nativeCreate ? nativeCreate(null) : objectProto;
18138
18139 // Add functions to the `MapCache`.
18140 MapCache.prototype.clear = mapClear;
18141 MapCache.prototype['delete'] = mapDelete;
18142 MapCache.prototype.get = mapGet;
18143 MapCache.prototype.has = mapHas;
18144 MapCache.prototype.set = mapSet;
18145
18146 // Add functions to the `SetCache`.
18147 SetCache.prototype.push = cachePush;
18148
18149 // Add functions to the `Stack` cache.
18150 Stack.prototype.clear = stackClear;
18151 Stack.prototype['delete'] = stackDelete;
18152 Stack.prototype.get = stackGet;
18153 Stack.prototype.has = stackHas;
18154 Stack.prototype.set = stackSet;
18155
18156 // Assign cache to `_.memoize`.
18157 memoize.Cache = MapCache;
18158
18159 // Add functions that return wrapped values when chaining.
18160 lodash.after = after;
18161 lodash.ary = ary;
18162 lodash.assign = assign;
18163 lodash.assignIn = assignIn;
18164 lodash.assignInWith = assignInWith;
18165 lodash.assignWith = assignWith;
18166 lodash.at = at;
18167 lodash.before = before;
18168 lodash.bind = bind;
18169 lodash.bindAll = bindAll;
18170 lodash.bindKey = bindKey;
18171 lodash.castArray = castArray;
18172 lodash.chain = chain;
18173 lodash.chunk = chunk;
18174 lodash.compact = compact;
18175 lodash.concat = concat;
18176 lodash.cond = cond;
18177 lodash.conforms = conforms;
18178 lodash.constant = constant;
18179 lodash.countBy = countBy;
18180 lodash.create = create;
18181 lodash.curry = curry;
18182 lodash.curryRight = curryRight;
18183 lodash.debounce = debounce;
18184 lodash.defaults = defaults;
18185 lodash.defaultsDeep = defaultsDeep;
18186 lodash.defer = defer;
18187 lodash.delay = delay;
18188 lodash.difference = difference;
18189 lodash.differenceBy = differenceBy;
18190 lodash.differenceWith = differenceWith;
18191 lodash.drop = drop;
18192 lodash.dropRight = dropRight;
18193 lodash.dropRightWhile = dropRightWhile;
18194 lodash.dropWhile = dropWhile;
18195 lodash.fill = fill;
18196 lodash.filter = filter;
18197 lodash.flatMap = flatMap;
18198 lodash.flatten = flatten;
18199 lodash.flattenDeep = flattenDeep;
18200 lodash.flattenDepth = flattenDepth;
18201 lodash.flip = flip;
18202 lodash.flow = flow;
18203 lodash.flowRight = flowRight;
18204 lodash.fromPairs = fromPairs;
18205 lodash.functions = functions;
18206 lodash.functionsIn = functionsIn;
18207 lodash.groupBy = groupBy;
18208 lodash.initial = initial;
18209 lodash.intersection = intersection;
18210 lodash.intersectionBy = intersectionBy;
18211 lodash.intersectionWith = intersectionWith;
18212 lodash.invert = invert;
18213 lodash.invertBy = invertBy;
18214 lodash.invokeMap = invokeMap;
18215 lodash.iteratee = iteratee;
18216 lodash.keyBy = keyBy;
18217 lodash.keys = keys;
18218 lodash.keysIn = keysIn;
18219 lodash.map = map;
18220 lodash.mapKeys = mapKeys;
18221 lodash.mapValues = mapValues;
18222 lodash.matches = matches;
18223 lodash.matchesProperty = matchesProperty;
18224 lodash.memoize = memoize;
18225 lodash.merge = merge;
18226 lodash.mergeWith = mergeWith;
18227 lodash.method = method;
18228 lodash.methodOf = methodOf;
18229 lodash.mixin = mixin;
18230 lodash.negate = negate;
18231 lodash.nthArg = nthArg;
18232 lodash.omit = omit;
18233 lodash.omitBy = omitBy;
18234 lodash.once = once;
18235 lodash.orderBy = orderBy;
18236 lodash.over = over;
18237 lodash.overArgs = overArgs;
18238 lodash.overEvery = overEvery;
18239 lodash.overSome = overSome;
18240 lodash.partial = partial;
18241 lodash.partialRight = partialRight;
18242 lodash.partition = partition;
18243 lodash.pick = pick;
18244 lodash.pickBy = pickBy;
18245 lodash.property = property;
18246 lodash.propertyOf = propertyOf;
18247 lodash.pull = pull;
18248 lodash.pullAll = pullAll;
18249 lodash.pullAllBy = pullAllBy;
18250 lodash.pullAllWith = pullAllWith;
18251 lodash.pullAt = pullAt;
18252 lodash.range = range;
18253 lodash.rangeRight = rangeRight;
18254 lodash.rearg = rearg;
18255 lodash.reject = reject;
18256 lodash.remove = remove;
18257 lodash.rest = rest;
18258 lodash.reverse = reverse;
18259 lodash.sampleSize = sampleSize;
18260 lodash.set = set;
18261 lodash.setWith = setWith;
18262 lodash.shuffle = shuffle;
18263 lodash.slice = slice;
18264 lodash.sortBy = sortBy;
18265 lodash.sortedUniq = sortedUniq;
18266 lodash.sortedUniqBy = sortedUniqBy;
18267 lodash.split = split;
18268 lodash.spread = spread;
18269 lodash.tail = tail;
18270 lodash.take = take;
18271 lodash.takeRight = takeRight;
18272 lodash.takeRightWhile = takeRightWhile;
18273 lodash.takeWhile = takeWhile;
18274 lodash.tap = tap;
18275 lodash.throttle = throttle;
18276 lodash.thru = thru;
18277 lodash.toArray = toArray;
18278 lodash.toPairs = toPairs;
18279 lodash.toPairsIn = toPairsIn;
18280 lodash.toPath = toPath;
18281 lodash.toPlainObject = toPlainObject;
18282 lodash.transform = transform;
18283 lodash.unary = unary;
18284 lodash.union = union;
18285 lodash.unionBy = unionBy;
18286 lodash.unionWith = unionWith;
18287 lodash.uniq = uniq;
18288 lodash.uniqBy = uniqBy;
18289 lodash.uniqWith = uniqWith;
18290 lodash.unset = unset;
18291 lodash.unzip = unzip;
18292 lodash.unzipWith = unzipWith;
18293 lodash.update = update;
18294 lodash.updateWith = updateWith;
18295 lodash.values = values;
18296 lodash.valuesIn = valuesIn;
18297 lodash.without = without;
18298 lodash.words = words;
18299 lodash.wrap = wrap;
18300 lodash.xor = xor;
18301 lodash.xorBy = xorBy;
18302 lodash.xorWith = xorWith;
18303 lodash.zip = zip;
18304 lodash.zipObject = zipObject;
18305 lodash.zipObjectDeep = zipObjectDeep;
18306 lodash.zipWith = zipWith;
18307
18308 // Add aliases.
18309 lodash.extend = assignIn;
18310 lodash.extendWith = assignInWith;
18311
18312 // Add functions to `lodash.prototype`.
18313 mixin(lodash, lodash);
18314
18315 /*------------------------------------------------------------------------*/
18316
18317 // Add functions that return unwrapped values when chaining.
18318 lodash.add = add;
18319 lodash.attempt = attempt;
18320 lodash.camelCase = camelCase;
18321 lodash.capitalize = capitalize;
18322 lodash.ceil = ceil;
18323 lodash.clamp = clamp;
18324 lodash.clone = clone;
18325 lodash.cloneDeep = cloneDeep;
18326 lodash.cloneDeepWith = cloneDeepWith;
18327 lodash.cloneWith = cloneWith;
18328 lodash.deburr = deburr;
18329 lodash.endsWith = endsWith;
18330 lodash.eq = eq;
18331 lodash.escape = escape;
18332 lodash.escapeRegExp = escapeRegExp;
18333 lodash.every = every;
18334 lodash.find = find;
18335 lodash.findIndex = findIndex;
18336 lodash.findKey = findKey;
18337 lodash.findLast = findLast;
18338 lodash.findLastIndex = findLastIndex;
18339 lodash.findLastKey = findLastKey;
18340 lodash.floor = floor;
18341 lodash.forEach = forEach;
18342 lodash.forEachRight = forEachRight;
18343 lodash.forIn = forIn;
18344 lodash.forInRight = forInRight;
18345 lodash.forOwn = forOwn;
18346 lodash.forOwnRight = forOwnRight;
18347 lodash.get = get;
18348 lodash.gt = gt;
18349 lodash.gte = gte;
18350 lodash.has = has;
18351 lodash.hasIn = hasIn;
18352 lodash.head = head;
18353 lodash.identity = identity;
18354 lodash.includes = includes;
18355 lodash.indexOf = indexOf;
18356 lodash.inRange = inRange;
18357 lodash.invoke = invoke;
18358 lodash.isArguments = isArguments;
18359 lodash.isArray = isArray;
18360 lodash.isArrayBuffer = isArrayBuffer;
18361 lodash.isArrayLike = isArrayLike;
18362 lodash.isArrayLikeObject = isArrayLikeObject;
18363 lodash.isBoolean = isBoolean;
18364 lodash.isBuffer = isBuffer;
18365 lodash.isDate = isDate;
18366 lodash.isElement = isElement;
18367 lodash.isEmpty = isEmpty;
18368 lodash.isEqual = isEqual;
18369 lodash.isEqualWith = isEqualWith;
18370 lodash.isError = isError;
18371 lodash.isFinite = isFinite;
18372 lodash.isFunction = isFunction;
18373 lodash.isInteger = isInteger;
18374 lodash.isLength = isLength;
18375 lodash.isMap = isMap;
18376 lodash.isMatch = isMatch;
18377 lodash.isMatchWith = isMatchWith;
18378 lodash.isNaN = isNaN;
18379 lodash.isNative = isNative;
18380 lodash.isNil = isNil;
18381 lodash.isNull = isNull;
18382 lodash.isNumber = isNumber;
18383 lodash.isObject = isObject;
18384 lodash.isObjectLike = isObjectLike;
18385 lodash.isPlainObject = isPlainObject;
18386 lodash.isRegExp = isRegExp;
18387 lodash.isSafeInteger = isSafeInteger;
18388 lodash.isSet = isSet;
18389 lodash.isString = isString;
18390 lodash.isSymbol = isSymbol;
18391 lodash.isTypedArray = isTypedArray;
18392 lodash.isUndefined = isUndefined;
18393 lodash.isWeakMap = isWeakMap;
18394 lodash.isWeakSet = isWeakSet;
18395 lodash.join = join;
18396 lodash.kebabCase = kebabCase;
18397 lodash.last = last;
18398 lodash.lastIndexOf = lastIndexOf;
18399 lodash.lowerCase = lowerCase;
18400 lodash.lowerFirst = lowerFirst;
18401 lodash.lt = lt;
18402 lodash.lte = lte;
18403 lodash.max = max;
18404 lodash.maxBy = maxBy;
18405 lodash.mean = mean;
18406 lodash.min = min;
18407 lodash.minBy = minBy;
18408 lodash.noConflict = noConflict;
18409 lodash.noop = noop;
18410 lodash.now = now;
18411 lodash.pad = pad;
18412 lodash.padEnd = padEnd;
18413 lodash.padStart = padStart;
18414 lodash.parseInt = parseInt;
18415 lodash.random = random;
18416 lodash.reduce = reduce;
18417 lodash.reduceRight = reduceRight;
18418 lodash.repeat = repeat;
18419 lodash.replace = replace;
18420 lodash.result = result;
18421 lodash.round = round;
18422 lodash.runInContext = runInContext;
18423 lodash.sample = sample;
18424 lodash.size = size;
18425 lodash.snakeCase = snakeCase;
18426 lodash.some = some;
18427 lodash.sortedIndex = sortedIndex;
18428 lodash.sortedIndexBy = sortedIndexBy;
18429 lodash.sortedIndexOf = sortedIndexOf;
18430 lodash.sortedLastIndex = sortedLastIndex;
18431 lodash.sortedLastIndexBy = sortedLastIndexBy;
18432 lodash.sortedLastIndexOf = sortedLastIndexOf;
18433 lodash.startCase = startCase;
18434 lodash.startsWith = startsWith;
18435 lodash.subtract = subtract;
18436 lodash.sum = sum;
18437 lodash.sumBy = sumBy;
18438 lodash.template = template;
18439 lodash.times = times;
18440 lodash.toInteger = toInteger;
18441 lodash.toLength = toLength;
18442 lodash.toLower = toLower;
18443 lodash.toNumber = toNumber;
18444 lodash.toSafeInteger = toSafeInteger;
18445 lodash.toString = toString;
18446 lodash.toUpper = toUpper;
18447 lodash.trim = trim;
18448 lodash.trimEnd = trimEnd;
18449 lodash.trimStart = trimStart;
18450 lodash.truncate = truncate;
18451 lodash.unescape = unescape;
18452 lodash.uniqueId = uniqueId;
18453 lodash.upperCase = upperCase;
18454 lodash.upperFirst = upperFirst;
18455
18456 // Add aliases.
18457 lodash.each = forEach;
18458 lodash.eachRight = forEachRight;
18459 lodash.first = head;
18460
18461 mixin(lodash, (function() {
18462 var source = {};
18463 baseForOwn(lodash, function(func, methodName) {
18464 if (!hasOwnProperty.call(lodash.prototype, methodName)) {
18465 source[methodName] = func;
18466 }
18467 });
18468 return source;
18469 }()), { 'chain': false });
18470
18471 /*------------------------------------------------------------------------*/
18472
18473 /**
18474 * The semantic version number.
18475 *
18476 * @static
18477 * @memberOf _
18478 * @type {string}
18479 */
18480 lodash.VERSION = VERSION;
18481
18482 // Assign default placeholders.
18483 arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) {
18484 lodash[methodName].placeholder = lodash;
18485 });
18486
18487 // Add `LazyWrapper` methods for `_.drop` and `_.take` variants.
18488 arrayEach(['drop', 'take'], function(methodName, index) {
18489 LazyWrapper.prototype[methodName] = function(n) {
18490 var filtered = this.__filtered__;
18491 if (filtered && !index) {
18492 return new LazyWrapper(this);
18493 }
18494 n = n === undefined ? 1 : nativeMax(toInteger(n), 0);
18495
18496 var result = this.clone();
18497 if (filtered) {
18498 result.__takeCount__ = nativeMin(n, result.__takeCount__);
18499 } else {
18500 result.__views__.push({
18501 'size': nativeMin(n, MAX_ARRAY_LENGTH),
18502 'type': methodName + (result.__dir__ < 0 ? 'Right' : '')
18503 });
18504 }
18505 return result;
18506 };
18507
18508 LazyWrapper.prototype[methodName + 'Right'] = function(n) {
18509 return this.reverse()[methodName](n).reverse();
18510 };
18511 });
18512
18513 // Add `LazyWrapper` methods that accept an `iteratee` value.
18514 arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) {
18515 var type = index + 1,
18516 isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG;
18517
18518 LazyWrapper.prototype[methodName] = function(iteratee) {
18519 var result = this.clone();
18520 result.__iteratees__.push({
18521 'iteratee': getIteratee(iteratee, 3),
18522 'type': type
18523 });
18524 result.__filtered__ = result.__filtered__ || isFilter;
18525 return result;
18526 };
18527 });
18528
18529 // Add `LazyWrapper` methods for `_.head` and `_.last`.
18530 arrayEach(['head', 'last'], function(methodName, index) {
18531 var takeName = 'take' + (index ? 'Right' : '');
18532
18533 LazyWrapper.prototype[methodName] = function() {
18534 return this[takeName](1).value()[0];
18535 };
18536 });
18537
18538 // Add `LazyWrapper` methods for `_.initial` and `_.tail`.
18539 arrayEach(['initial', 'tail'], function(methodName, index) {
18540 var dropName = 'drop' + (index ? '' : 'Right');
18541
18542 LazyWrapper.prototype[methodName] = function() {
18543 return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1);
18544 };
18545 });
18546
18547 LazyWrapper.prototype.compact = function() {
18548 return this.filter(identity);
18549 };
18550
18551 LazyWrapper.prototype.find = function(predicate) {
18552 return this.filter(predicate).head();
18553 };
18554
18555 LazyWrapper.prototype.findLast = function(predicate) {
18556 return this.reverse().find(predicate);
18557 };
18558
18559 LazyWrapper.prototype.invokeMap = rest(function(path, args) {
18560 if (typeof path == 'function') {
18561 return new LazyWrapper(this);
18562 }
18563 return this.map(function(value) {
18564 return baseInvoke(value, path, args);
18565 });
18566 });
18567
18568 LazyWrapper.prototype.reject = function(predicate) {
18569 predicate = getIteratee(predicate, 3);
18570 return this.filter(function(value) {
18571 return !predicate(value);
18572 });
18573 };
18574
18575 LazyWrapper.prototype.slice = function(start, end) {
18576 start = toInteger(start);
18577
18578 var result = this;
18579 if (result.__filtered__ && (start > 0 || end < 0)) {
18580 return new LazyWrapper(result);
18581 }
18582 if (start < 0) {
18583 result = result.takeRight(-start);
18584 } else if (start) {
18585 result = result.drop(start);
18586 }
18587 if (end !== undefined) {
18588 end = toInteger(end);
18589 result = end < 0 ? result.dropRight(-end) : result.take(end - start);
18590 }
18591 return result;
18592 };
18593
18594 LazyWrapper.prototype.takeRightWhile = function(predicate) {
18595 return this.reverse().takeWhile(predicate).reverse();
18596 };
18597
18598 LazyWrapper.prototype.toArray = function() {
18599 return this.take(MAX_ARRAY_LENGTH);
18600 };
18601
18602 // Add `LazyWrapper` methods to `lodash.prototype`.
18603 baseForOwn(LazyWrapper.prototype, function(func, methodName) {
18604 var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName),
18605 isTaker = /^(?:head|last)$/.test(methodName),
18606 lodashFunc = lodash[isTaker ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName],
18607 retUnwrapped = isTaker || /^find/.test(methodName);
18608
18609 if (!lodashFunc) {
18610 return;
18611 }
18612 lodash.prototype[methodName] = function() {
18613 var value = this.__wrapped__,
18614 args = isTaker ? [1] : arguments,
18615 isLazy = value instanceof LazyWrapper,
18616 iteratee = args[0],
18617 useLazy = isLazy || isArray(value);
18618
18619 var interceptor = function(value) {
18620 var result = lodashFunc.apply(lodash, arrayPush([value], args));
18621 return (isTaker && chainAll) ? result[0] : result;
18622 };
18623
18624 if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
18625 // Avoid lazy use if the iteratee has a "length" value other than `1`.
18626 isLazy = useLazy = false;
18627 }
18628 var chainAll = this.__chain__,
18629 isHybrid = !!this.__actions__.length,
18630 isUnwrapped = retUnwrapped && !chainAll,
18631 onlyLazy = isLazy && !isHybrid;
18632
18633 if (!retUnwrapped && useLazy) {
18634 value = onlyLazy ? value : new LazyWrapper(this);
18635 var result = func.apply(value, args);
18636 result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
18637 return new LodashWrapper(result, chainAll);
18638 }
18639 if (isUnwrapped && onlyLazy) {
18640 return func.apply(this, args);
18641 }
18642 result = this.thru(interceptor);
18643 return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
18644 };
18645 });
18646
18647 // Add `Array` and `String` methods to `lodash.prototype`.
18648 arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) {
18649 var func = arrayProto[methodName],
18650 chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru',
18651 retUnwrapped = /^(?:pop|shift)$/.test(methodName);
18652
18653 lodash.prototype[methodName] = function() {
18654 var args = arguments;
18655 if (retUnwrapped && !this.__chain__) {
18656 return func.apply(this.value(), args);
18657 }
18658 return this[chainName](function(value) {
18659 return func.apply(value, args);
18660 });
18661 };
18662 });
18663
18664 // Map minified function names to their real names.
18665 baseForOwn(LazyWrapper.prototype, function(func, methodName) {
18666 var lodashFunc = lodash[methodName];
18667 if (lodashFunc) {
18668 var key = (lodashFunc.name + ''),
18669 names = realNames[key] || (realNames[key] = []);
18670
18671 names.push({ 'name': methodName, 'func': lodashFunc });
18672 }
18673 });
18674
18675 realNames[createHybridWrapper(undefined, BIND_KEY_FLAG).name] = [{
18676 'name': 'wrapper',
18677 'func': undefined
18678 }];
18679
18680 // Add functions to the lazy wrapper.
18681 LazyWrapper.prototype.clone = lazyClone;
18682 LazyWrapper.prototype.reverse = lazyReverse;
18683 LazyWrapper.prototype.value = lazyValue;
18684
18685 // Add chaining functions to the `lodash` wrapper.
18686 lodash.prototype.at = wrapperAt;
18687 lodash.prototype.chain = wrapperChain;
18688 lodash.prototype.commit = wrapperCommit;
18689 lodash.prototype.flatMap = wrapperFlatMap;
18690 lodash.prototype.next = wrapperNext;
18691 lodash.prototype.plant = wrapperPlant;
18692 lodash.prototype.reverse = wrapperReverse;
18693 lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue;
18694
18695 if (iteratorSymbol) {
18696 lodash.prototype[iteratorSymbol] = wrapperToIterator;
18697 }
18698 return lodash;
18699 }
18700
18701 /*--------------------------------------------------------------------------*/
18702
18703 // Export lodash.
18704 var _ = runInContext();
18705
18706 // Expose lodash on the free variable `window` or `self` when available. This
18707 // prevents errors in cases where lodash is loaded by a script tag in the presence
18708 // of an AMD loader. See http://requirejs.org/docs/errors.html#mismatch for more details.
18709 (freeWindow || freeSelf || {})._ = _;
18710
18711 // Some AMD build optimizers like r.js check for condition patterns like the following:
18712 if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
18713 // Define as an anonymous module so, through path mapping, it can be
18714 // referenced as the "underscore" module.
18715 define(function() {
18716 return _;
18717 });
18718 }
18719 // Check for `exports` after `define` in case a build optimizer adds an `exports` object.
18720 else if (freeExports && freeModule) {
18721 // Export for Node.js.
18722 if (moduleExports) {
18723 (freeModule.exports = _)._ = _;
18724 }
18725 // Export for CommonJS support.
18726 freeExports._ = _;
18727 }
18728 else {
18729 // Export to the global object.
18730 root._ = _;
18731 }
18732}.call(this));
18733
18734}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
18735},{}],3:[function(require,module,exports){
18736(function (global){
18737"use strict";
18738
18739var numeric = (typeof exports === "undefined")?(function numeric() {}):(exports);
18740if(typeof global !== "undefined") { global.numeric = numeric; }
18741
18742numeric.version = "1.2.6";
18743
18744// 1. Utility functions
18745numeric.bench = function bench (f,interval) {
18746 var t1,t2,n,i;
18747 if(typeof interval === "undefined") { interval = 15; }
18748 n = 0.5;
18749 t1 = new Date();
18750 while(1) {
18751 n*=2;
18752 for(i=n;i>3;i-=4) { f(); f(); f(); f(); }
18753 while(i>0) { f(); i--; }
18754 t2 = new Date();
18755 if(t2-t1 > interval) break;
18756 }
18757 for(i=n;i>3;i-=4) { f(); f(); f(); f(); }
18758 while(i>0) { f(); i--; }
18759 t2 = new Date();
18760 return 1000*(3*n-1)/(t2-t1);
18761}
18762
18763numeric._myIndexOf = (function _myIndexOf(w) {
18764 var n = this.length,k;
18765 for(k=0;k<n;++k) if(this[k]===w) return k;
18766 return -1;
18767});
18768numeric.myIndexOf = (Array.prototype.indexOf)?Array.prototype.indexOf:numeric._myIndexOf;
18769
18770numeric.Function = Function;
18771numeric.precision = 4;
18772numeric.largeArray = 50;
18773
18774numeric.prettyPrint = function prettyPrint(x) {
18775 function fmtnum(x) {
18776 if(x === 0) { return '0'; }
18777 if(isNaN(x)) { return 'NaN'; }
18778 if(x<0) { return '-'+fmtnum(-x); }
18779 if(isFinite(x)) {
18780 var scale = Math.floor(Math.log(x) / Math.log(10));
18781 var normalized = x / Math.pow(10,scale);
18782 var basic = normalized.toPrecision(numeric.precision);
18783 if(parseFloat(basic) === 10) { scale++; normalized = 1; basic = normalized.toPrecision(numeric.precision); }
18784 return parseFloat(basic).toString()+'e'+scale.toString();
18785 }
18786 return 'Infinity';
18787 }
18788 var ret = [];
18789 function foo(x) {
18790 var k;
18791 if(typeof x === "undefined") { ret.push(Array(numeric.precision+8).join(' ')); return false; }
18792 if(typeof x === "string") { ret.push('"'+x+'"'); return false; }
18793 if(typeof x === "boolean") { ret.push(x.toString()); return false; }
18794 if(typeof x === "number") {
18795 var a = fmtnum(x);
18796 var b = x.toPrecision(numeric.precision);
18797 var c = parseFloat(x.toString()).toString();
18798 var d = [a,b,c,parseFloat(b).toString(),parseFloat(c).toString()];
18799 for(k=1;k<d.length;k++) { if(d[k].length < a.length) a = d[k]; }
18800 ret.push(Array(numeric.precision+8-a.length).join(' ')+a);
18801 return false;
18802 }
18803 if(x === null) { ret.push("null"); return false; }
18804 if(typeof x === "function") {
18805 ret.push(x.toString());
18806 var flag = false;
18807 for(k in x) { if(x.hasOwnProperty(k)) {
18808 if(flag) ret.push(',\n');
18809 else ret.push('\n{');
18810 flag = true;
18811 ret.push(k);
18812 ret.push(': \n');
18813 foo(x[k]);
18814 } }
18815 if(flag) ret.push('}\n');
18816 return true;
18817 }
18818 if(x instanceof Array) {
18819 if(x.length > numeric.largeArray) { ret.push('...Large Array...'); return true; }
18820 var flag = false;
18821 ret.push('[');
18822 for(k=0;k<x.length;k++) { if(k>0) { ret.push(','); if(flag) ret.push('\n '); } flag = foo(x[k]); }
18823 ret.push(']');
18824 return true;
18825 }
18826 ret.push('{');
18827 var flag = false;
18828 for(k in x) { if(x.hasOwnProperty(k)) { if(flag) ret.push(',\n'); flag = true; ret.push(k); ret.push(': \n'); foo(x[k]); } }
18829 ret.push('}');
18830 return true;
18831 }
18832 foo(x);
18833 return ret.join('');
18834}
18835
18836numeric.parseDate = function parseDate(d) {
18837 function foo(d) {
18838 if(typeof d === 'string') { return Date.parse(d.replace(/-/g,'/')); }
18839 if(!(d instanceof Array)) { throw new Error("parseDate: parameter must be arrays of strings"); }
18840 var ret = [],k;
18841 for(k=0;k<d.length;k++) { ret[k] = foo(d[k]); }
18842 return ret;
18843 }
18844 return foo(d);
18845}
18846
18847numeric.parseFloat = function parseFloat_(d) {
18848 function foo(d) {
18849 if(typeof d === 'string') { return parseFloat(d); }
18850 if(!(d instanceof Array)) { throw new Error("parseFloat: parameter must be arrays of strings"); }
18851 var ret = [],k;
18852 for(k=0;k<d.length;k++) { ret[k] = foo(d[k]); }
18853 return ret;
18854 }
18855 return foo(d);
18856}
18857
18858numeric.parseCSV = function parseCSV(t) {
18859 var foo = t.split('\n');
18860 var j,k;
18861 var ret = [];
18862 var pat = /(([^'",]*)|('[^']*')|("[^"]*")),/g;
18863 var patnum = /^\s*(([+-]?[0-9]+(\.[0-9]*)?(e[+-]?[0-9]+)?)|([+-]?[0-9]*(\.[0-9]+)?(e[+-]?[0-9]+)?))\s*$/;
18864 var stripper = function(n) { return n.substr(0,n.length-1); }
18865 var count = 0;
18866 for(k=0;k<foo.length;k++) {
18867 var bar = (foo[k]+",").match(pat),baz;
18868 if(bar.length>0) {
18869 ret[count] = [];
18870 for(j=0;j<bar.length;j++) {
18871 baz = stripper(bar[j]);
18872 if(patnum.test(baz)) { ret[count][j] = parseFloat(baz); }
18873 else ret[count][j] = baz;
18874 }
18875 count++;
18876 }
18877 }
18878 return ret;
18879}
18880
18881numeric.toCSV = function toCSV(A) {
18882 var s = numeric.dim(A);
18883 var i,j,m,n,row,ret;
18884 m = s[0];
18885 n = s[1];
18886 ret = [];
18887 for(i=0;i<m;i++) {
18888 row = [];
18889 for(j=0;j<m;j++) { row[j] = A[i][j].toString(); }
18890 ret[i] = row.join(', ');
18891 }
18892 return ret.join('\n')+'\n';
18893}
18894
18895numeric.getURL = function getURL(url) {
18896 var client = new XMLHttpRequest();
18897 client.open("GET",url,false);
18898 client.send();
18899 return client;
18900}
18901
18902numeric.imageURL = function imageURL(img) {
18903 function base64(A) {
18904 var n = A.length, i,x,y,z,p,q,r,s;
18905 var key = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
18906 var ret = "";
18907 for(i=0;i<n;i+=3) {
18908 x = A[i];
18909 y = A[i+1];
18910 z = A[i+2];
18911 p = x >> 2;
18912 q = ((x & 3) << 4) + (y >> 4);
18913 r = ((y & 15) << 2) + (z >> 6);
18914 s = z & 63;
18915 if(i+1>=n) { r = s = 64; }
18916 else if(i+2>=n) { s = 64; }
18917 ret += key.charAt(p) + key.charAt(q) + key.charAt(r) + key.charAt(s);
18918 }
18919 return ret;
18920 }
18921 function crc32Array (a,from,to) {
18922 if(typeof from === "undefined") { from = 0; }
18923 if(typeof to === "undefined") { to = a.length; }
18924 var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
18925 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
18926 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
18927 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
18928 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
18929 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
18930 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
18931 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
18932 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
18933 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
18934 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
18935 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
18936 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
18937 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
18938 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
18939 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
18940 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
18941 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
18942 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
18943 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
18944 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
18945 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
18946 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
18947 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
18948 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
18949 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
18950 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
18951 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
18952 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
18953 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
18954 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
18955 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D];
18956
18957 var crc = -1, y = 0, n = a.length,i;
18958
18959 for (i = from; i < to; i++) {
18960 y = (crc ^ a[i]) & 0xFF;
18961 crc = (crc >>> 8) ^ table[y];
18962 }
18963
18964 return crc ^ (-1);
18965 }
18966
18967 var h = img[0].length, w = img[0][0].length, s1, s2, next,k,length,a,b,i,j,adler32,crc32;
18968 var stream = [
18969 137, 80, 78, 71, 13, 10, 26, 10, // 0: PNG signature
18970 0,0,0,13, // 8: IHDR Chunk length
18971 73, 72, 68, 82, // 12: "IHDR"
18972 (w >> 24) & 255, (w >> 16) & 255, (w >> 8) & 255, w&255, // 16: Width
18973 (h >> 24) & 255, (h >> 16) & 255, (h >> 8) & 255, h&255, // 20: Height
18974 8, // 24: bit depth
18975 2, // 25: RGB
18976 0, // 26: deflate
18977 0, // 27: no filter
18978 0, // 28: no interlace
18979 -1,-2,-3,-4, // 29: CRC
18980 -5,-6,-7,-8, // 33: IDAT Chunk length
18981 73, 68, 65, 84, // 37: "IDAT"
18982 // RFC 1950 header starts here
18983 8, // 41: RFC1950 CMF
18984 29 // 42: RFC1950 FLG
18985 ];
18986 crc32 = crc32Array(stream,12,29);
18987 stream[29] = (crc32>>24)&255;
18988 stream[30] = (crc32>>16)&255;
18989 stream[31] = (crc32>>8)&255;
18990 stream[32] = (crc32)&255;
18991 s1 = 1;
18992 s2 = 0;
18993 for(i=0;i<h;i++) {
18994 if(i<h-1) { stream.push(0); }
18995 else { stream.push(1); }
18996 a = (3*w+1+(i===0))&255; b = ((3*w+1+(i===0))>>8)&255;
18997 stream.push(a); stream.push(b);
18998 stream.push((~a)&255); stream.push((~b)&255);
18999 if(i===0) stream.push(0);
19000 for(j=0;j<w;j++) {
19001 for(k=0;k<3;k++) {
19002 a = img[k][i][j];
19003 if(a>255) a = 255;
19004 else if(a<0) a=0;
19005 else a = Math.round(a);
19006 s1 = (s1 + a )%65521;
19007 s2 = (s2 + s1)%65521;
19008 stream.push(a);
19009 }
19010 }
19011 stream.push(0);
19012 }
19013 adler32 = (s2<<16)+s1;
19014 stream.push((adler32>>24)&255);
19015 stream.push((adler32>>16)&255);
19016 stream.push((adler32>>8)&255);
19017 stream.push((adler32)&255);
19018 length = stream.length - 41;
19019 stream[33] = (length>>24)&255;
19020 stream[34] = (length>>16)&255;
19021 stream[35] = (length>>8)&255;
19022 stream[36] = (length)&255;
19023 crc32 = crc32Array(stream,37);
19024 stream.push((crc32>>24)&255);
19025 stream.push((crc32>>16)&255);
19026 stream.push((crc32>>8)&255);
19027 stream.push((crc32)&255);
19028 stream.push(0);
19029 stream.push(0);
19030 stream.push(0);
19031 stream.push(0);
19032// a = stream.length;
19033 stream.push(73); // I
19034 stream.push(69); // E
19035 stream.push(78); // N
19036 stream.push(68); // D
19037 stream.push(174); // CRC1
19038 stream.push(66); // CRC2
19039 stream.push(96); // CRC3
19040 stream.push(130); // CRC4
19041 return 'data:image/png;base64,'+base64(stream);
19042}
19043
19044// 2. Linear algebra with Arrays.
19045numeric._dim = function _dim(x) {
19046 var ret = [];
19047 while(typeof x === "object") { ret.push(x.length); x = x[0]; }
19048 return ret;
19049}
19050
19051numeric.dim = function dim(x) {
19052 var y,z;
19053 if(typeof x === "object") {
19054 y = x[0];
19055 if(typeof y === "object") {
19056 z = y[0];
19057 if(typeof z === "object") {
19058 return numeric._dim(x);
19059 }
19060 return [x.length,y.length];
19061 }
19062 return [x.length];
19063 }
19064 return [];
19065}
19066
19067numeric.mapreduce = function mapreduce(body,init) {
19068 return Function('x','accum','_s','_k',
19069 'if(typeof accum === "undefined") accum = '+init+';\n'+
19070 'if(typeof x === "number") { var xi = x; '+body+'; return accum; }\n'+
19071 'if(typeof _s === "undefined") _s = numeric.dim(x);\n'+
19072 'if(typeof _k === "undefined") _k = 0;\n'+
19073 'var _n = _s[_k];\n'+
19074 'var i,xi;\n'+
19075 'if(_k < _s.length-1) {\n'+
19076 ' for(i=_n-1;i>=0;i--) {\n'+
19077 ' accum = arguments.callee(x[i],accum,_s,_k+1);\n'+
19078 ' }'+
19079 ' return accum;\n'+
19080 '}\n'+
19081 'for(i=_n-1;i>=1;i-=2) { \n'+
19082 ' xi = x[i];\n'+
19083 ' '+body+';\n'+
19084 ' xi = x[i-1];\n'+
19085 ' '+body+';\n'+
19086 '}\n'+
19087 'if(i === 0) {\n'+
19088 ' xi = x[i];\n'+
19089 ' '+body+'\n'+
19090 '}\n'+
19091 'return accum;'
19092 );
19093}
19094numeric.mapreduce2 = function mapreduce2(body,setup) {
19095 return Function('x',
19096 'var n = x.length;\n'+
19097 'var i,xi;\n'+setup+';\n'+
19098 'for(i=n-1;i!==-1;--i) { \n'+
19099 ' xi = x[i];\n'+
19100 ' '+body+';\n'+
19101 '}\n'+
19102 'return accum;'
19103 );
19104}
19105
19106
19107numeric.same = function same(x,y) {
19108 var i,n;
19109 if(!(x instanceof Array) || !(y instanceof Array)) { return false; }
19110 n = x.length;
19111 if(n !== y.length) { return false; }
19112 for(i=0;i<n;i++) {
19113 if(x[i] === y[i]) { continue; }
19114 if(typeof x[i] === "object") { if(!same(x[i],y[i])) return false; }
19115 else { return false; }
19116 }
19117 return true;
19118}
19119
19120numeric.rep = function rep(s,v,k) {
19121 if(typeof k === "undefined") { k=0; }
19122 var n = s[k], ret = Array(n), i;
19123 if(k === s.length-1) {
19124 for(i=n-2;i>=0;i-=2) { ret[i+1] = v; ret[i] = v; }
19125 if(i===-1) { ret[0] = v; }
19126 return ret;
19127 }
19128 for(i=n-1;i>=0;i--) { ret[i] = numeric.rep(s,v,k+1); }
19129 return ret;
19130}
19131
19132
19133numeric.dotMMsmall = function dotMMsmall(x,y) {
19134 var i,j,k,p,q,r,ret,foo,bar,woo,i0,k0,p0,r0;
19135 p = x.length; q = y.length; r = y[0].length;
19136 ret = Array(p);
19137 for(i=p-1;i>=0;i--) {
19138 foo = Array(r);
19139 bar = x[i];
19140 for(k=r-1;k>=0;k--) {
19141 woo = bar[q-1]*y[q-1][k];
19142 for(j=q-2;j>=1;j-=2) {
19143 i0 = j-1;
19144 woo += bar[j]*y[j][k] + bar[i0]*y[i0][k];
19145 }
19146 if(j===0) { woo += bar[0]*y[0][k]; }
19147 foo[k] = woo;
19148 }
19149 ret[i] = foo;
19150 }
19151 return ret;
19152}
19153numeric._getCol = function _getCol(A,j,x) {
19154 var n = A.length, i;
19155 for(i=n-1;i>0;--i) {
19156 x[i] = A[i][j];
19157 --i;
19158 x[i] = A[i][j];
19159 }
19160 if(i===0) x[0] = A[0][j];
19161}
19162numeric.dotMMbig = function dotMMbig(x,y){
19163 var gc = numeric._getCol, p = y.length, v = Array(p);
19164 var m = x.length, n = y[0].length, A = new Array(m), xj;
19165 var VV = numeric.dotVV;
19166 var i,j,k,z;
19167 --p;
19168 --m;
19169 for(i=m;i!==-1;--i) A[i] = Array(n);
19170 --n;
19171 for(i=n;i!==-1;--i) {
19172 gc(y,i,v);
19173 for(j=m;j!==-1;--j) {
19174 z=0;
19175 xj = x[j];
19176 A[j][i] = VV(xj,v);
19177 }
19178 }
19179 return A;
19180}
19181
19182numeric.dotMV = function dotMV(x,y) {
19183 var p = x.length, q = y.length,i;
19184 var ret = Array(p), dotVV = numeric.dotVV;
19185 for(i=p-1;i>=0;i--) { ret[i] = dotVV(x[i],y); }
19186 return ret;
19187}
19188
19189numeric.dotVM = function dotVM(x,y) {
19190 var i,j,k,p,q,r,ret,foo,bar,woo,i0,k0,p0,r0,s1,s2,s3,baz,accum;
19191 p = x.length; q = y[0].length;
19192 ret = Array(q);
19193 for(k=q-1;k>=0;k--) {
19194 woo = x[p-1]*y[p-1][k];
19195 for(j=p-2;j>=1;j-=2) {
19196 i0 = j-1;
19197 woo += x[j]*y[j][k] + x[i0]*y[i0][k];
19198 }
19199 if(j===0) { woo += x[0]*y[0][k]; }
19200 ret[k] = woo;
19201 }
19202 return ret;
19203}
19204
19205numeric.dotVV = function dotVV(x,y) {
19206 var i,n=x.length,i1,ret = x[n-1]*y[n-1];
19207 for(i=n-2;i>=1;i-=2) {
19208 i1 = i-1;
19209 ret += x[i]*y[i] + x[i1]*y[i1];
19210 }
19211 if(i===0) { ret += x[0]*y[0]; }
19212 return ret;
19213}
19214
19215numeric.dot = function dot(x,y) {
19216 var d = numeric.dim;
19217 switch(d(x).length*1000+d(y).length) {
19218 case 2002:
19219 if(y.length < 10) return numeric.dotMMsmall(x,y);
19220 else return numeric.dotMMbig(x,y);
19221 case 2001: return numeric.dotMV(x,y);
19222 case 1002: return numeric.dotVM(x,y);
19223 case 1001: return numeric.dotVV(x,y);
19224 case 1000: return numeric.mulVS(x,y);
19225 case 1: return numeric.mulSV(x,y);
19226 case 0: return x*y;
19227 default: throw new Error('numeric.dot only works on vectors and matrices');
19228 }
19229}
19230
19231numeric.diag = function diag(d) {
19232 var i,i1,j,n = d.length, A = Array(n), Ai;
19233 for(i=n-1;i>=0;i--) {
19234 Ai = Array(n);
19235 i1 = i+2;
19236 for(j=n-1;j>=i1;j-=2) {
19237 Ai[j] = 0;
19238 Ai[j-1] = 0;
19239 }
19240 if(j>i) { Ai[j] = 0; }
19241 Ai[i] = d[i];
19242 for(j=i-1;j>=1;j-=2) {
19243 Ai[j] = 0;
19244 Ai[j-1] = 0;
19245 }
19246 if(j===0) { Ai[0] = 0; }
19247 A[i] = Ai;
19248 }
19249 return A;
19250}
19251numeric.getDiag = function(A) {
19252 var n = Math.min(A.length,A[0].length),i,ret = Array(n);
19253 for(i=n-1;i>=1;--i) {
19254 ret[i] = A[i][i];
19255 --i;
19256 ret[i] = A[i][i];
19257 }
19258 if(i===0) {
19259 ret[0] = A[0][0];
19260 }
19261 return ret;
19262}
19263
19264numeric.identity = function identity(n) { return numeric.diag(numeric.rep([n],1)); }
19265numeric.pointwise = function pointwise(params,body,setup) {
19266 if(typeof setup === "undefined") { setup = ""; }
19267 var fun = [];
19268 var k;
19269 var avec = /\[i\]$/,p,thevec = '';
19270 var haveret = false;
19271 for(k=0;k<params.length;k++) {
19272 if(avec.test(params[k])) {
19273 p = params[k].substring(0,params[k].length-3);
19274 thevec = p;
19275 } else { p = params[k]; }
19276 if(p==='ret') haveret = true;
19277 fun.push(p);
19278 }
19279 fun[params.length] = '_s';
19280 fun[params.length+1] = '_k';
19281 fun[params.length+2] = (
19282 'if(typeof _s === "undefined") _s = numeric.dim('+thevec+');\n'+
19283 'if(typeof _k === "undefined") _k = 0;\n'+
19284 'var _n = _s[_k];\n'+
19285 'var i'+(haveret?'':', ret = Array(_n)')+';\n'+
19286 'if(_k < _s.length-1) {\n'+
19287 ' for(i=_n-1;i>=0;i--) ret[i] = arguments.callee('+params.join(',')+',_s,_k+1);\n'+
19288 ' return ret;\n'+
19289 '}\n'+
19290 setup+'\n'+
19291 'for(i=_n-1;i!==-1;--i) {\n'+
19292 ' '+body+'\n'+
19293 '}\n'+
19294 'return ret;'
19295 );
19296 return Function.apply(null,fun);
19297}
19298numeric.pointwise2 = function pointwise2(params,body,setup) {
19299 if(typeof setup === "undefined") { setup = ""; }
19300 var fun = [];
19301 var k;
19302 var avec = /\[i\]$/,p,thevec = '';
19303 var haveret = false;
19304 for(k=0;k<params.length;k++) {
19305 if(avec.test(params[k])) {
19306 p = params[k].substring(0,params[k].length-3);
19307 thevec = p;
19308 } else { p = params[k]; }
19309 if(p==='ret') haveret = true;
19310 fun.push(p);
19311 }
19312 fun[params.length] = (
19313 'var _n = '+thevec+'.length;\n'+
19314 'var i'+(haveret?'':', ret = Array(_n)')+';\n'+
19315 setup+'\n'+
19316 'for(i=_n-1;i!==-1;--i) {\n'+
19317 body+'\n'+
19318 '}\n'+
19319 'return ret;'
19320 );
19321 return Function.apply(null,fun);
19322}
19323numeric._biforeach = (function _biforeach(x,y,s,k,f) {
19324 if(k === s.length-1) { f(x,y); return; }
19325 var i,n=s[k];
19326 for(i=n-1;i>=0;i--) { _biforeach(typeof x==="object"?x[i]:x,typeof y==="object"?y[i]:y,s,k+1,f); }
19327});
19328numeric._biforeach2 = (function _biforeach2(x,y,s,k,f) {
19329 if(k === s.length-1) { return f(x,y); }
19330 var i,n=s[k],ret = Array(n);
19331 for(i=n-1;i>=0;--i) { ret[i] = _biforeach2(typeof x==="object"?x[i]:x,typeof y==="object"?y[i]:y,s,k+1,f); }
19332 return ret;
19333});
19334numeric._foreach = (function _foreach(x,s,k,f) {
19335 if(k === s.length-1) { f(x); return; }
19336 var i,n=s[k];
19337 for(i=n-1;i>=0;i--) { _foreach(x[i],s,k+1,f); }
19338});
19339numeric._foreach2 = (function _foreach2(x,s,k,f) {
19340 if(k === s.length-1) { return f(x); }
19341 var i,n=s[k], ret = Array(n);
19342 for(i=n-1;i>=0;i--) { ret[i] = _foreach2(x[i],s,k+1,f); }
19343 return ret;
19344});
19345
19346/*numeric.anyV = numeric.mapreduce('if(xi) return true;','false');
19347numeric.allV = numeric.mapreduce('if(!xi) return false;','true');
19348numeric.any = function(x) { if(typeof x.length === "undefined") return x; return numeric.anyV(x); }
19349numeric.all = function(x) { if(typeof x.length === "undefined") return x; return numeric.allV(x); }*/
19350
19351numeric.ops2 = {
19352 add: '+',
19353 sub: '-',
19354 mul: '*',
19355 div: '/',
19356 mod: '%',
19357 and: '&&',
19358 or: '||',
19359 eq: '===',
19360 neq: '!==',
19361 lt: '<',
19362 gt: '>',
19363 leq: '<=',
19364 geq: '>=',
19365 band: '&',
19366 bor: '|',
19367 bxor: '^',
19368 lshift: '<<',
19369 rshift: '>>',
19370 rrshift: '>>>'
19371};
19372numeric.opseq = {
19373 addeq: '+=',
19374 subeq: '-=',
19375 muleq: '*=',
19376 diveq: '/=',
19377 modeq: '%=',
19378 lshifteq: '<<=',
19379 rshifteq: '>>=',
19380 rrshifteq: '>>>=',
19381 bandeq: '&=',
19382 boreq: '|=',
19383 bxoreq: '^='
19384};
19385numeric.mathfuns = ['abs','acos','asin','atan','ceil','cos',
19386 'exp','floor','log','round','sin','sqrt','tan',
19387 'isNaN','isFinite'];
19388numeric.mathfuns2 = ['atan2','pow','max','min'];
19389numeric.ops1 = {
19390 neg: '-',
19391 not: '!',
19392 bnot: '~',
19393 clone: ''
19394};
19395numeric.mapreducers = {
19396 any: ['if(xi) return true;','var accum = false;'],
19397 all: ['if(!xi) return false;','var accum = true;'],
19398 sum: ['accum += xi;','var accum = 0;'],
19399 prod: ['accum *= xi;','var accum = 1;'],
19400 norm2Squared: ['accum += xi*xi;','var accum = 0;'],
19401 norminf: ['accum = max(accum,abs(xi));','var accum = 0, max = Math.max, abs = Math.abs;'],
19402 norm1: ['accum += abs(xi)','var accum = 0, abs = Math.abs;'],
19403 sup: ['accum = max(accum,xi);','var accum = -Infinity, max = Math.max;'],
19404 inf: ['accum = min(accum,xi);','var accum = Infinity, min = Math.min;']
19405};
19406
19407(function () {
19408 var i,o;
19409 for(i=0;i<numeric.mathfuns2.length;++i) {
19410 o = numeric.mathfuns2[i];
19411 numeric.ops2[o] = o;
19412 }
19413 for(i in numeric.ops2) {
19414 if(numeric.ops2.hasOwnProperty(i)) {
19415 o = numeric.ops2[i];
19416 var code, codeeq, setup = '';
19417 if(numeric.myIndexOf.call(numeric.mathfuns2,i)!==-1) {
19418 setup = 'var '+o+' = Math.'+o+';\n';
19419 code = function(r,x,y) { return r+' = '+o+'('+x+','+y+')'; };
19420 codeeq = function(x,y) { return x+' = '+o+'('+x+','+y+')'; };
19421 } else {
19422 code = function(r,x,y) { return r+' = '+x+' '+o+' '+y; };
19423 if(numeric.opseq.hasOwnProperty(i+'eq')) {
19424 codeeq = function(x,y) { return x+' '+o+'= '+y; };
19425 } else {
19426 codeeq = function(x,y) { return x+' = '+x+' '+o+' '+y; };
19427 }
19428 }
19429 numeric[i+'VV'] = numeric.pointwise2(['x[i]','y[i]'],code('ret[i]','x[i]','y[i]'),setup);
19430 numeric[i+'SV'] = numeric.pointwise2(['x','y[i]'],code('ret[i]','x','y[i]'),setup);
19431 numeric[i+'VS'] = numeric.pointwise2(['x[i]','y'],code('ret[i]','x[i]','y'),setup);
19432 numeric[i] = Function(
19433 'var n = arguments.length, i, x = arguments[0], y;\n'+
19434 'var VV = numeric.'+i+'VV, VS = numeric.'+i+'VS, SV = numeric.'+i+'SV;\n'+
19435 'var dim = numeric.dim;\n'+
19436 'for(i=1;i!==n;++i) { \n'+
19437 ' y = arguments[i];\n'+
19438 ' if(typeof x === "object") {\n'+
19439 ' if(typeof y === "object") x = numeric._biforeach2(x,y,dim(x),0,VV);\n'+
19440 ' else x = numeric._biforeach2(x,y,dim(x),0,VS);\n'+
19441 ' } else if(typeof y === "object") x = numeric._biforeach2(x,y,dim(y),0,SV);\n'+
19442 ' else '+codeeq('x','y')+'\n'+
19443 '}\nreturn x;\n');
19444 numeric[o] = numeric[i];
19445 numeric[i+'eqV'] = numeric.pointwise2(['ret[i]','x[i]'], codeeq('ret[i]','x[i]'),setup);
19446 numeric[i+'eqS'] = numeric.pointwise2(['ret[i]','x'], codeeq('ret[i]','x'),setup);
19447 numeric[i+'eq'] = Function(
19448 'var n = arguments.length, i, x = arguments[0], y;\n'+
19449 'var V = numeric.'+i+'eqV, S = numeric.'+i+'eqS\n'+
19450 'var s = numeric.dim(x);\n'+
19451 'for(i=1;i!==n;++i) { \n'+
19452 ' y = arguments[i];\n'+
19453 ' if(typeof y === "object") numeric._biforeach(x,y,s,0,V);\n'+
19454 ' else numeric._biforeach(x,y,s,0,S);\n'+
19455 '}\nreturn x;\n');
19456 }
19457 }
19458 for(i=0;i<numeric.mathfuns2.length;++i) {
19459 o = numeric.mathfuns2[i];
19460 delete numeric.ops2[o];
19461 }
19462 for(i=0;i<numeric.mathfuns.length;++i) {
19463 o = numeric.mathfuns[i];
19464 numeric.ops1[o] = o;
19465 }
19466 for(i in numeric.ops1) {
19467 if(numeric.ops1.hasOwnProperty(i)) {
19468 setup = '';
19469 o = numeric.ops1[i];
19470 if(numeric.myIndexOf.call(numeric.mathfuns,i)!==-1) {
19471 if(Math.hasOwnProperty(o)) setup = 'var '+o+' = Math.'+o+';\n';
19472 }
19473 numeric[i+'eqV'] = numeric.pointwise2(['ret[i]'],'ret[i] = '+o+'(ret[i]);',setup);
19474 numeric[i+'eq'] = Function('x',
19475 'if(typeof x !== "object") return '+o+'x\n'+
19476 'var i;\n'+
19477 'var V = numeric.'+i+'eqV;\n'+
19478 'var s = numeric.dim(x);\n'+
19479 'numeric._foreach(x,s,0,V);\n'+
19480 'return x;\n');
19481 numeric[i+'V'] = numeric.pointwise2(['x[i]'],'ret[i] = '+o+'(x[i]);',setup);
19482 numeric[i] = Function('x',
19483 'if(typeof x !== "object") return '+o+'(x)\n'+
19484 'var i;\n'+
19485 'var V = numeric.'+i+'V;\n'+
19486 'var s = numeric.dim(x);\n'+
19487 'return numeric._foreach2(x,s,0,V);\n');
19488 }
19489 }
19490 for(i=0;i<numeric.mathfuns.length;++i) {
19491 o = numeric.mathfuns[i];
19492 delete numeric.ops1[o];
19493 }
19494 for(i in numeric.mapreducers) {
19495 if(numeric.mapreducers.hasOwnProperty(i)) {
19496 o = numeric.mapreducers[i];
19497 numeric[i+'V'] = numeric.mapreduce2(o[0],o[1]);
19498 numeric[i] = Function('x','s','k',
19499 o[1]+
19500 'if(typeof x !== "object") {'+
19501 ' xi = x;\n'+
19502 o[0]+';\n'+
19503 ' return accum;\n'+
19504 '}'+
19505 'if(typeof s === "undefined") s = numeric.dim(x);\n'+
19506 'if(typeof k === "undefined") k = 0;\n'+
19507 'if(k === s.length-1) return numeric.'+i+'V(x);\n'+
19508 'var xi;\n'+
19509 'var n = x.length, i;\n'+
19510 'for(i=n-1;i!==-1;--i) {\n'+
19511 ' xi = arguments.callee(x[i]);\n'+
19512 o[0]+';\n'+
19513 '}\n'+
19514 'return accum;\n');
19515 }
19516 }
19517}());
19518
19519numeric.truncVV = numeric.pointwise(['x[i]','y[i]'],'ret[i] = round(x[i]/y[i])*y[i];','var round = Math.round;');
19520numeric.truncVS = numeric.pointwise(['x[i]','y'],'ret[i] = round(x[i]/y)*y;','var round = Math.round;');
19521numeric.truncSV = numeric.pointwise(['x','y[i]'],'ret[i] = round(x/y[i])*y[i];','var round = Math.round;');
19522numeric.trunc = function trunc(x,y) {
19523 if(typeof x === "object") {
19524 if(typeof y === "object") return numeric.truncVV(x,y);
19525 return numeric.truncVS(x,y);
19526 }
19527 if (typeof y === "object") return numeric.truncSV(x,y);
19528 return Math.round(x/y)*y;
19529}
19530
19531numeric.inv = function inv(x) {
19532 var s = numeric.dim(x), abs = Math.abs, m = s[0], n = s[1];
19533 var A = numeric.clone(x), Ai, Aj;
19534 var I = numeric.identity(m), Ii, Ij;
19535 var i,j,k,x;
19536 for(j=0;j<n;++j) {
19537 var i0 = -1;
19538 var v0 = -1;
19539 for(i=j;i!==m;++i) { k = abs(A[i][j]); if(k>v0) { i0 = i; v0 = k; } }
19540 Aj = A[i0]; A[i0] = A[j]; A[j] = Aj;
19541 Ij = I[i0]; I[i0] = I[j]; I[j] = Ij;
19542 x = Aj[j];
19543 for(k=j;k!==n;++k) Aj[k] /= x;
19544 for(k=n-1;k!==-1;--k) Ij[k] /= x;
19545 for(i=m-1;i!==-1;--i) {
19546 if(i!==j) {
19547 Ai = A[i];
19548 Ii = I[i];
19549 x = Ai[j];
19550 for(k=j+1;k!==n;++k) Ai[k] -= Aj[k]*x;
19551 for(k=n-1;k>0;--k) { Ii[k] -= Ij[k]*x; --k; Ii[k] -= Ij[k]*x; }
19552 if(k===0) Ii[0] -= Ij[0]*x;
19553 }
19554 }
19555 }
19556 return I;
19557}
19558
19559numeric.det = function det(x) {
19560 var s = numeric.dim(x);
19561 if(s.length !== 2 || s[0] !== s[1]) { throw new Error('numeric: det() only works on square matrices'); }
19562 var n = s[0], ret = 1,i,j,k,A = numeric.clone(x),Aj,Ai,alpha,temp,k1,k2,k3;
19563 for(j=0;j<n-1;j++) {
19564 k=j;
19565 for(i=j+1;i<n;i++) { if(Math.abs(A[i][j]) > Math.abs(A[k][j])) { k = i; } }
19566 if(k !== j) {
19567 temp = A[k]; A[k] = A[j]; A[j] = temp;
19568 ret *= -1;
19569 }
19570 Aj = A[j];
19571 for(i=j+1;i<n;i++) {
19572 Ai = A[i];
19573 alpha = Ai[j]/Aj[j];
19574 for(k=j+1;k<n-1;k+=2) {
19575 k1 = k+1;
19576 Ai[k] -= Aj[k]*alpha;
19577 Ai[k1] -= Aj[k1]*alpha;
19578 }
19579 if(k!==n) { Ai[k] -= Aj[k]*alpha; }
19580 }
19581 if(Aj[j] === 0) { return 0; }
19582 ret *= Aj[j];
19583 }
19584 return ret*A[j][j];
19585}
19586
19587numeric.transpose = function transpose(x) {
19588 var i,j,m = x.length,n = x[0].length, ret=Array(n),A0,A1,Bj;
19589 for(j=0;j<n;j++) ret[j] = Array(m);
19590 for(i=m-1;i>=1;i-=2) {
19591 A1 = x[i];
19592 A0 = x[i-1];
19593 for(j=n-1;j>=1;--j) {
19594 Bj = ret[j]; Bj[i] = A1[j]; Bj[i-1] = A0[j];
19595 --j;
19596 Bj = ret[j]; Bj[i] = A1[j]; Bj[i-1] = A0[j];
19597 }
19598 if(j===0) {
19599 Bj = ret[0]; Bj[i] = A1[0]; Bj[i-1] = A0[0];
19600 }
19601 }
19602 if(i===0) {
19603 A0 = x[0];
19604 for(j=n-1;j>=1;--j) {
19605 ret[j][0] = A0[j];
19606 --j;
19607 ret[j][0] = A0[j];
19608 }
19609 if(j===0) { ret[0][0] = A0[0]; }
19610 }
19611 return ret;
19612}
19613numeric.negtranspose = function negtranspose(x) {
19614 var i,j,m = x.length,n = x[0].length, ret=Array(n),A0,A1,Bj;
19615 for(j=0;j<n;j++) ret[j] = Array(m);
19616 for(i=m-1;i>=1;i-=2) {
19617 A1 = x[i];
19618 A0 = x[i-1];
19619 for(j=n-1;j>=1;--j) {
19620 Bj = ret[j]; Bj[i] = -A1[j]; Bj[i-1] = -A0[j];
19621 --j;
19622 Bj = ret[j]; Bj[i] = -A1[j]; Bj[i-1] = -A0[j];
19623 }
19624 if(j===0) {
19625 Bj = ret[0]; Bj[i] = -A1[0]; Bj[i-1] = -A0[0];
19626 }
19627 }
19628 if(i===0) {
19629 A0 = x[0];
19630 for(j=n-1;j>=1;--j) {
19631 ret[j][0] = -A0[j];
19632 --j;
19633 ret[j][0] = -A0[j];
19634 }
19635 if(j===0) { ret[0][0] = -A0[0]; }
19636 }
19637 return ret;
19638}
19639
19640numeric._random = function _random(s,k) {
19641 var i,n=s[k],ret=Array(n), rnd;
19642 if(k === s.length-1) {
19643 rnd = Math.random;
19644 for(i=n-1;i>=1;i-=2) {
19645 ret[i] = rnd();
19646 ret[i-1] = rnd();
19647 }
19648 if(i===0) { ret[0] = rnd(); }
19649 return ret;
19650 }
19651 for(i=n-1;i>=0;i--) ret[i] = _random(s,k+1);
19652 return ret;
19653}
19654numeric.random = function random(s) { return numeric._random(s,0); }
19655
19656numeric.norm2 = function norm2(x) { return Math.sqrt(numeric.norm2Squared(x)); }
19657
19658numeric.linspace = function linspace(a,b,n) {
19659 if(typeof n === "undefined") n = Math.max(Math.round(b-a)+1,1);
19660 if(n<2) { return n===1?[a]:[]; }
19661 var i,ret = Array(n);
19662 n--;
19663 for(i=n;i>=0;i--) { ret[i] = (i*b+(n-i)*a)/n; }
19664 return ret;
19665}
19666
19667numeric.getBlock = function getBlock(x,from,to) {
19668 var s = numeric.dim(x);
19669 function foo(x,k) {
19670 var i,a = from[k], n = to[k]-a, ret = Array(n);
19671 if(k === s.length-1) {
19672 for(i=n;i>=0;i--) { ret[i] = x[i+a]; }
19673 return ret;
19674 }
19675 for(i=n;i>=0;i--) { ret[i] = foo(x[i+a],k+1); }
19676 return ret;
19677 }
19678 return foo(x,0);
19679}
19680
19681numeric.setBlock = function setBlock(x,from,to,B) {
19682 var s = numeric.dim(x);
19683 function foo(x,y,k) {
19684 var i,a = from[k], n = to[k]-a;
19685 if(k === s.length-1) { for(i=n;i>=0;i--) { x[i+a] = y[i]; } }
19686 for(i=n;i>=0;i--) { foo(x[i+a],y[i],k+1); }
19687 }
19688 foo(x,B,0);
19689 return x;
19690}
19691
19692numeric.getRange = function getRange(A,I,J) {
19693 var m = I.length, n = J.length;
19694 var i,j;
19695 var B = Array(m), Bi, AI;
19696 for(i=m-1;i!==-1;--i) {
19697 B[i] = Array(n);
19698 Bi = B[i];
19699 AI = A[I[i]];
19700 for(j=n-1;j!==-1;--j) Bi[j] = AI[J[j]];
19701 }
19702 return B;
19703}
19704
19705numeric.blockMatrix = function blockMatrix(X) {
19706 var s = numeric.dim(X);
19707 if(s.length<4) return numeric.blockMatrix([X]);
19708 var m=s[0],n=s[1],M,N,i,j,Xij;
19709 M = 0; N = 0;
19710 for(i=0;i<m;++i) M+=X[i][0].length;
19711 for(j=0;j<n;++j) N+=X[0][j][0].length;
19712 var Z = Array(M);
19713 for(i=0;i<M;++i) Z[i] = Array(N);
19714 var I=0,J,ZI,k,l,Xijk;
19715 for(i=0;i<m;++i) {
19716 J=N;
19717 for(j=n-1;j!==-1;--j) {
19718 Xij = X[i][j];
19719 J -= Xij[0].length;
19720 for(k=Xij.length-1;k!==-1;--k) {
19721 Xijk = Xij[k];
19722 ZI = Z[I+k];
19723 for(l = Xijk.length-1;l!==-1;--l) ZI[J+l] = Xijk[l];
19724 }
19725 }
19726 I += X[i][0].length;
19727 }
19728 return Z;
19729}
19730
19731numeric.tensor = function tensor(x,y) {
19732 if(typeof x === "number" || typeof y === "number") return numeric.mul(x,y);
19733 var s1 = numeric.dim(x), s2 = numeric.dim(y);
19734 if(s1.length !== 1 || s2.length !== 1) {
19735 throw new Error('numeric: tensor product is only defined for vectors');
19736 }
19737 var m = s1[0], n = s2[0], A = Array(m), Ai, i,j,xi;
19738 for(i=m-1;i>=0;i--) {
19739 Ai = Array(n);
19740 xi = x[i];
19741 for(j=n-1;j>=3;--j) {
19742 Ai[j] = xi * y[j];
19743 --j;
19744 Ai[j] = xi * y[j];
19745 --j;
19746 Ai[j] = xi * y[j];
19747 --j;
19748 Ai[j] = xi * y[j];
19749 }
19750 while(j>=0) { Ai[j] = xi * y[j]; --j; }
19751 A[i] = Ai;
19752 }
19753 return A;
19754}
19755
19756// 3. The Tensor type T
19757numeric.T = function T(x,y) { this.x = x; this.y = y; }
19758numeric.t = function t(x,y) { return new numeric.T(x,y); }
19759
19760numeric.Tbinop = function Tbinop(rr,rc,cr,cc,setup) {
19761 var io = numeric.indexOf;
19762 if(typeof setup !== "string") {
19763 var k;
19764 setup = '';
19765 for(k in numeric) {
19766 if(numeric.hasOwnProperty(k) && (rr.indexOf(k)>=0 || rc.indexOf(k)>=0 || cr.indexOf(k)>=0 || cc.indexOf(k)>=0) && k.length>1) {
19767 setup += 'var '+k+' = numeric.'+k+';\n';
19768 }
19769 }
19770 }
19771 return Function(['y'],
19772 'var x = this;\n'+
19773 'if(!(y instanceof numeric.T)) { y = new numeric.T(y); }\n'+
19774 setup+'\n'+
19775 'if(x.y) {'+
19776 ' if(y.y) {'+
19777 ' return new numeric.T('+cc+');\n'+
19778 ' }\n'+
19779 ' return new numeric.T('+cr+');\n'+
19780 '}\n'+
19781 'if(y.y) {\n'+
19782 ' return new numeric.T('+rc+');\n'+
19783 '}\n'+
19784 'return new numeric.T('+rr+');\n'
19785 );
19786}
19787
19788numeric.T.prototype.add = numeric.Tbinop(
19789 'add(x.x,y.x)',
19790 'add(x.x,y.x),y.y',
19791 'add(x.x,y.x),x.y',
19792 'add(x.x,y.x),add(x.y,y.y)');
19793numeric.T.prototype.sub = numeric.Tbinop(
19794 'sub(x.x,y.x)',
19795 'sub(x.x,y.x),neg(y.y)',
19796 'sub(x.x,y.x),x.y',
19797 'sub(x.x,y.x),sub(x.y,y.y)');
19798numeric.T.prototype.mul = numeric.Tbinop(
19799 'mul(x.x,y.x)',
19800 'mul(x.x,y.x),mul(x.x,y.y)',
19801 'mul(x.x,y.x),mul(x.y,y.x)',
19802 'sub(mul(x.x,y.x),mul(x.y,y.y)),add(mul(x.x,y.y),mul(x.y,y.x))');
19803
19804numeric.T.prototype.reciprocal = function reciprocal() {
19805 var mul = numeric.mul, div = numeric.div;
19806 if(this.y) {
19807 var d = numeric.add(mul(this.x,this.x),mul(this.y,this.y));
19808 return new numeric.T(div(this.x,d),div(numeric.neg(this.y),d));
19809 }
19810 return new T(div(1,this.x));
19811}
19812numeric.T.prototype.div = function div(y) {
19813 if(!(y instanceof numeric.T)) y = new numeric.T(y);
19814 if(y.y) { return this.mul(y.reciprocal()); }
19815 var div = numeric.div;
19816 if(this.y) { return new numeric.T(div(this.x,y.x),div(this.y,y.x)); }
19817 return new numeric.T(div(this.x,y.x));
19818}
19819numeric.T.prototype.dot = numeric.Tbinop(
19820 'dot(x.x,y.x)',
19821 'dot(x.x,y.x),dot(x.x,y.y)',
19822 'dot(x.x,y.x),dot(x.y,y.x)',
19823 'sub(dot(x.x,y.x),dot(x.y,y.y)),add(dot(x.x,y.y),dot(x.y,y.x))'
19824 );
19825numeric.T.prototype.transpose = function transpose() {
19826 var t = numeric.transpose, x = this.x, y = this.y;
19827 if(y) { return new numeric.T(t(x),t(y)); }
19828 return new numeric.T(t(x));
19829}
19830numeric.T.prototype.transjugate = function transjugate() {
19831 var t = numeric.transpose, x = this.x, y = this.y;
19832 if(y) { return new numeric.T(t(x),numeric.negtranspose(y)); }
19833 return new numeric.T(t(x));
19834}
19835numeric.Tunop = function Tunop(r,c,s) {
19836 if(typeof s !== "string") { s = ''; }
19837 return Function(
19838 'var x = this;\n'+
19839 s+'\n'+
19840 'if(x.y) {'+
19841 ' '+c+';\n'+
19842 '}\n'+
19843 r+';\n'
19844 );
19845}
19846
19847numeric.T.prototype.exp = numeric.Tunop(
19848 'return new numeric.T(ex)',
19849 'return new numeric.T(mul(cos(x.y),ex),mul(sin(x.y),ex))',
19850 'var ex = numeric.exp(x.x), cos = numeric.cos, sin = numeric.sin, mul = numeric.mul;');
19851numeric.T.prototype.conj = numeric.Tunop(
19852 'return new numeric.T(x.x);',
19853 'return new numeric.T(x.x,numeric.neg(x.y));');
19854numeric.T.prototype.neg = numeric.Tunop(
19855 'return new numeric.T(neg(x.x));',
19856 'return new numeric.T(neg(x.x),neg(x.y));',
19857 'var neg = numeric.neg;');
19858numeric.T.prototype.sin = numeric.Tunop(
19859 'return new numeric.T(numeric.sin(x.x))',
19860 'return x.exp().sub(x.neg().exp()).div(new numeric.T(0,2));');
19861numeric.T.prototype.cos = numeric.Tunop(
19862 'return new numeric.T(numeric.cos(x.x))',
19863 'return x.exp().add(x.neg().exp()).div(2);');
19864numeric.T.prototype.abs = numeric.Tunop(
19865 'return new numeric.T(numeric.abs(x.x));',
19866 'return new numeric.T(numeric.sqrt(numeric.add(mul(x.x,x.x),mul(x.y,x.y))));',
19867 'var mul = numeric.mul;');
19868numeric.T.prototype.log = numeric.Tunop(
19869 'return new numeric.T(numeric.log(x.x));',
19870 'var theta = new numeric.T(numeric.atan2(x.y,x.x)), r = x.abs();\n'+
19871 'return new numeric.T(numeric.log(r.x),theta.x);');
19872numeric.T.prototype.norm2 = numeric.Tunop(
19873 'return numeric.norm2(x.x);',
19874 'var f = numeric.norm2Squared;\n'+
19875 'return Math.sqrt(f(x.x)+f(x.y));');
19876numeric.T.prototype.inv = function inv() {
19877 var A = this;
19878 if(typeof A.y === "undefined") { return new numeric.T(numeric.inv(A.x)); }
19879 var n = A.x.length, i, j, k;
19880 var Rx = numeric.identity(n),Ry = numeric.rep([n,n],0);
19881 var Ax = numeric.clone(A.x), Ay = numeric.clone(A.y);
19882 var Aix, Aiy, Ajx, Ajy, Rix, Riy, Rjx, Rjy;
19883 var i,j,k,d,d1,ax,ay,bx,by,temp;
19884 for(i=0;i<n;i++) {
19885 ax = Ax[i][i]; ay = Ay[i][i];
19886 d = ax*ax+ay*ay;
19887 k = i;
19888 for(j=i+1;j<n;j++) {
19889 ax = Ax[j][i]; ay = Ay[j][i];
19890 d1 = ax*ax+ay*ay;
19891 if(d1 > d) { k=j; d = d1; }
19892 }
19893 if(k!==i) {
19894 temp = Ax[i]; Ax[i] = Ax[k]; Ax[k] = temp;
19895 temp = Ay[i]; Ay[i] = Ay[k]; Ay[k] = temp;
19896 temp = Rx[i]; Rx[i] = Rx[k]; Rx[k] = temp;
19897 temp = Ry[i]; Ry[i] = Ry[k]; Ry[k] = temp;
19898 }
19899 Aix = Ax[i]; Aiy = Ay[i];
19900 Rix = Rx[i]; Riy = Ry[i];
19901 ax = Aix[i]; ay = Aiy[i];
19902 for(j=i+1;j<n;j++) {
19903 bx = Aix[j]; by = Aiy[j];
19904 Aix[j] = (bx*ax+by*ay)/d;
19905 Aiy[j] = (by*ax-bx*ay)/d;
19906 }
19907 for(j=0;j<n;j++) {
19908 bx = Rix[j]; by = Riy[j];
19909 Rix[j] = (bx*ax+by*ay)/d;
19910 Riy[j] = (by*ax-bx*ay)/d;
19911 }
19912 for(j=i+1;j<n;j++) {
19913 Ajx = Ax[j]; Ajy = Ay[j];
19914 Rjx = Rx[j]; Rjy = Ry[j];
19915 ax = Ajx[i]; ay = Ajy[i];
19916 for(k=i+1;k<n;k++) {
19917 bx = Aix[k]; by = Aiy[k];
19918 Ajx[k] -= bx*ax-by*ay;
19919 Ajy[k] -= by*ax+bx*ay;
19920 }
19921 for(k=0;k<n;k++) {
19922 bx = Rix[k]; by = Riy[k];
19923 Rjx[k] -= bx*ax-by*ay;
19924 Rjy[k] -= by*ax+bx*ay;
19925 }
19926 }
19927 }
19928 for(i=n-1;i>0;i--) {
19929 Rix = Rx[i]; Riy = Ry[i];
19930 for(j=i-1;j>=0;j--) {
19931 Rjx = Rx[j]; Rjy = Ry[j];
19932 ax = Ax[j][i]; ay = Ay[j][i];
19933 for(k=n-1;k>=0;k--) {
19934 bx = Rix[k]; by = Riy[k];
19935 Rjx[k] -= ax*bx - ay*by;
19936 Rjy[k] -= ax*by + ay*bx;
19937 }
19938 }
19939 }
19940 return new numeric.T(Rx,Ry);
19941}
19942numeric.T.prototype.get = function get(i) {
19943 var x = this.x, y = this.y, k = 0, ik, n = i.length;
19944 if(y) {
19945 while(k<n) {
19946 ik = i[k];
19947 x = x[ik];
19948 y = y[ik];
19949 k++;
19950 }
19951 return new numeric.T(x,y);
19952 }
19953 while(k<n) {
19954 ik = i[k];
19955 x = x[ik];
19956 k++;
19957 }
19958 return new numeric.T(x);
19959}
19960numeric.T.prototype.set = function set(i,v) {
19961 var x = this.x, y = this.y, k = 0, ik, n = i.length, vx = v.x, vy = v.y;
19962 if(n===0) {
19963 if(vy) { this.y = vy; }
19964 else if(y) { this.y = undefined; }
19965 this.x = x;
19966 return this;
19967 }
19968 if(vy) {
19969 if(y) { /* ok */ }
19970 else {
19971 y = numeric.rep(numeric.dim(x),0);
19972 this.y = y;
19973 }
19974 while(k<n-1) {
19975 ik = i[k];
19976 x = x[ik];
19977 y = y[ik];
19978 k++;
19979 }
19980 ik = i[k];
19981 x[ik] = vx;
19982 y[ik] = vy;
19983 return this;
19984 }
19985 if(y) {
19986 while(k<n-1) {
19987 ik = i[k];
19988 x = x[ik];
19989 y = y[ik];
19990 k++;
19991 }
19992 ik = i[k];
19993 x[ik] = vx;
19994 if(vx instanceof Array) y[ik] = numeric.rep(numeric.dim(vx),0);
19995 else y[ik] = 0;
19996 return this;
19997 }
19998 while(k<n-1) {
19999 ik = i[k];
20000 x = x[ik];
20001 k++;
20002 }
20003 ik = i[k];
20004 x[ik] = vx;
20005 return this;
20006}
20007numeric.T.prototype.getRows = function getRows(i0,i1) {
20008 var n = i1-i0+1, j;
20009 var rx = Array(n), ry, x = this.x, y = this.y;
20010 for(j=i0;j<=i1;j++) { rx[j-i0] = x[j]; }
20011 if(y) {
20012 ry = Array(n);
20013 for(j=i0;j<=i1;j++) { ry[j-i0] = y[j]; }
20014 return new numeric.T(rx,ry);
20015 }
20016 return new numeric.T(rx);
20017}
20018numeric.T.prototype.setRows = function setRows(i0,i1,A) {
20019 var j;
20020 var rx = this.x, ry = this.y, x = A.x, y = A.y;
20021 for(j=i0;j<=i1;j++) { rx[j] = x[j-i0]; }
20022 if(y) {
20023 if(!ry) { ry = numeric.rep(numeric.dim(rx),0); this.y = ry; }
20024 for(j=i0;j<=i1;j++) { ry[j] = y[j-i0]; }
20025 } else if(ry) {
20026 for(j=i0;j<=i1;j++) { ry[j] = numeric.rep([x[j-i0].length],0); }
20027 }
20028 return this;
20029}
20030numeric.T.prototype.getRow = function getRow(k) {
20031 var x = this.x, y = this.y;
20032 if(y) { return new numeric.T(x[k],y[k]); }
20033 return new numeric.T(x[k]);
20034}
20035numeric.T.prototype.setRow = function setRow(i,v) {
20036 var rx = this.x, ry = this.y, x = v.x, y = v.y;
20037 rx[i] = x;
20038 if(y) {
20039 if(!ry) { ry = numeric.rep(numeric.dim(rx),0); this.y = ry; }
20040 ry[i] = y;
20041 } else if(ry) {
20042 ry = numeric.rep([x.length],0);
20043 }
20044 return this;
20045}
20046
20047numeric.T.prototype.getBlock = function getBlock(from,to) {
20048 var x = this.x, y = this.y, b = numeric.getBlock;
20049 if(y) { return new numeric.T(b(x,from,to),b(y,from,to)); }
20050 return new numeric.T(b(x,from,to));
20051}
20052numeric.T.prototype.setBlock = function setBlock(from,to,A) {
20053 if(!(A instanceof numeric.T)) A = new numeric.T(A);
20054 var x = this.x, y = this.y, b = numeric.setBlock, Ax = A.x, Ay = A.y;
20055 if(Ay) {
20056 if(!y) { this.y = numeric.rep(numeric.dim(this),0); y = this.y; }
20057 b(x,from,to,Ax);
20058 b(y,from,to,Ay);
20059 return this;
20060 }
20061 b(x,from,to,Ax);
20062 if(y) b(y,from,to,numeric.rep(numeric.dim(Ax),0));
20063}
20064numeric.T.rep = function rep(s,v) {
20065 var T = numeric.T;
20066 if(!(v instanceof T)) v = new T(v);
20067 var x = v.x, y = v.y, r = numeric.rep;
20068 if(y) return new T(r(s,x),r(s,y));
20069 return new T(r(s,x));
20070}
20071numeric.T.diag = function diag(d) {
20072 if(!(d instanceof numeric.T)) d = new numeric.T(d);
20073 var x = d.x, y = d.y, diag = numeric.diag;
20074 if(y) return new numeric.T(diag(x),diag(y));
20075 return new numeric.T(diag(x));
20076}
20077numeric.T.eig = function eig() {
20078 if(this.y) { throw new Error('eig: not implemented for complex matrices.'); }
20079 return numeric.eig(this.x);
20080}
20081numeric.T.identity = function identity(n) { return new numeric.T(numeric.identity(n)); }
20082numeric.T.prototype.getDiag = function getDiag() {
20083 var n = numeric;
20084 var x = this.x, y = this.y;
20085 if(y) { return new n.T(n.getDiag(x),n.getDiag(y)); }
20086 return new n.T(n.getDiag(x));
20087}
20088
20089// 4. Eigenvalues of real matrices
20090
20091numeric.house = function house(x) {
20092 var v = numeric.clone(x);
20093 var s = x[0] >= 0 ? 1 : -1;
20094 var alpha = s*numeric.norm2(x);
20095 v[0] += alpha;
20096 var foo = numeric.norm2(v);
20097 if(foo === 0) { /* this should not happen */ throw new Error('eig: internal error'); }
20098 return numeric.div(v,foo);
20099}
20100
20101numeric.toUpperHessenberg = function toUpperHessenberg(me) {
20102 var s = numeric.dim(me);
20103 if(s.length !== 2 || s[0] !== s[1]) { throw new Error('numeric: toUpperHessenberg() only works on square matrices'); }
20104 var m = s[0], i,j,k,x,v,A = numeric.clone(me),B,C,Ai,Ci,Q = numeric.identity(m),Qi;
20105 for(j=0;j<m-2;j++) {
20106 x = Array(m-j-1);
20107 for(i=j+1;i<m;i++) { x[i-j-1] = A[i][j]; }
20108 if(numeric.norm2(x)>0) {
20109 v = numeric.house(x);
20110 B = numeric.getBlock(A,[j+1,j],[m-1,m-1]);
20111 C = numeric.tensor(v,numeric.dot(v,B));
20112 for(i=j+1;i<m;i++) { Ai = A[i]; Ci = C[i-j-1]; for(k=j;k<m;k++) Ai[k] -= 2*Ci[k-j]; }
20113 B = numeric.getBlock(A,[0,j+1],[m-1,m-1]);
20114 C = numeric.tensor(numeric.dot(B,v),v);
20115 for(i=0;i<m;i++) { Ai = A[i]; Ci = C[i]; for(k=j+1;k<m;k++) Ai[k] -= 2*Ci[k-j-1]; }
20116 B = Array(m-j-1);
20117 for(i=j+1;i<m;i++) B[i-j-1] = Q[i];
20118 C = numeric.tensor(v,numeric.dot(v,B));
20119 for(i=j+1;i<m;i++) { Qi = Q[i]; Ci = C[i-j-1]; for(k=0;k<m;k++) Qi[k] -= 2*Ci[k]; }
20120 }
20121 }
20122 return {H:A, Q:Q};
20123}
20124
20125numeric.epsilon = 2.220446049250313e-16;
20126
20127numeric.QRFrancis = function(H,maxiter) {
20128 if(typeof maxiter === "undefined") { maxiter = 10000; }
20129 H = numeric.clone(H);
20130 var H0 = numeric.clone(H);
20131 var s = numeric.dim(H),m=s[0],x,v,a,b,c,d,det,tr, Hloc, Q = numeric.identity(m), Qi, Hi, B, C, Ci,i,j,k,iter;
20132 if(m<3) { return {Q:Q, B:[ [0,m-1] ]}; }
20133 var epsilon = numeric.epsilon;
20134 for(iter=0;iter<maxiter;iter++) {
20135 for(j=0;j<m-1;j++) {
20136 if(Math.abs(H[j+1][j]) < epsilon*(Math.abs(H[j][j])+Math.abs(H[j+1][j+1]))) {
20137 var QH1 = numeric.QRFrancis(numeric.getBlock(H,[0,0],[j,j]),maxiter);
20138 var QH2 = numeric.QRFrancis(numeric.getBlock(H,[j+1,j+1],[m-1,m-1]),maxiter);
20139 B = Array(j+1);
20140 for(i=0;i<=j;i++) { B[i] = Q[i]; }
20141 C = numeric.dot(QH1.Q,B);
20142 for(i=0;i<=j;i++) { Q[i] = C[i]; }
20143 B = Array(m-j-1);
20144 for(i=j+1;i<m;i++) { B[i-j-1] = Q[i]; }
20145 C = numeric.dot(QH2.Q,B);
20146 for(i=j+1;i<m;i++) { Q[i] = C[i-j-1]; }
20147 return {Q:Q,B:QH1.B.concat(numeric.add(QH2.B,j+1))};
20148 }
20149 }
20150 a = H[m-2][m-2]; b = H[m-2][m-1];
20151 c = H[m-1][m-2]; d = H[m-1][m-1];
20152 tr = a+d;
20153 det = (a*d-b*c);
20154 Hloc = numeric.getBlock(H, [0,0], [2,2]);
20155 if(tr*tr>=4*det) {
20156 var s1,s2;
20157 s1 = 0.5*(tr+Math.sqrt(tr*tr-4*det));
20158 s2 = 0.5*(tr-Math.sqrt(tr*tr-4*det));
20159 Hloc = numeric.add(numeric.sub(numeric.dot(Hloc,Hloc),
20160 numeric.mul(Hloc,s1+s2)),
20161 numeric.diag(numeric.rep([3],s1*s2)));
20162 } else {
20163 Hloc = numeric.add(numeric.sub(numeric.dot(Hloc,Hloc),
20164 numeric.mul(Hloc,tr)),
20165 numeric.diag(numeric.rep([3],det)));
20166 }
20167 x = [Hloc[0][0],Hloc[1][0],Hloc[2][0]];
20168 v = numeric.house(x);
20169 B = [H[0],H[1],H[2]];
20170 C = numeric.tensor(v,numeric.dot(v,B));
20171 for(i=0;i<3;i++) { Hi = H[i]; Ci = C[i]; for(k=0;k<m;k++) Hi[k] -= 2*Ci[k]; }
20172 B = numeric.getBlock(H, [0,0],[m-1,2]);
20173 C = numeric.tensor(numeric.dot(B,v),v);
20174 for(i=0;i<m;i++) { Hi = H[i]; Ci = C[i]; for(k=0;k<3;k++) Hi[k] -= 2*Ci[k]; }
20175 B = [Q[0],Q[1],Q[2]];
20176 C = numeric.tensor(v,numeric.dot(v,B));
20177 for(i=0;i<3;i++) { Qi = Q[i]; Ci = C[i]; for(k=0;k<m;k++) Qi[k] -= 2*Ci[k]; }
20178 var J;
20179 for(j=0;j<m-2;j++) {
20180 for(k=j;k<=j+1;k++) {
20181 if(Math.abs(H[k+1][k]) < epsilon*(Math.abs(H[k][k])+Math.abs(H[k+1][k+1]))) {
20182 var QH1 = numeric.QRFrancis(numeric.getBlock(H,[0,0],[k,k]),maxiter);
20183 var QH2 = numeric.QRFrancis(numeric.getBlock(H,[k+1,k+1],[m-1,m-1]),maxiter);
20184 B = Array(k+1);
20185 for(i=0;i<=k;i++) { B[i] = Q[i]; }
20186 C = numeric.dot(QH1.Q,B);
20187 for(i=0;i<=k;i++) { Q[i] = C[i]; }
20188 B = Array(m-k-1);
20189 for(i=k+1;i<m;i++) { B[i-k-1] = Q[i]; }
20190 C = numeric.dot(QH2.Q,B);
20191 for(i=k+1;i<m;i++) { Q[i] = C[i-k-1]; }
20192 return {Q:Q,B:QH1.B.concat(numeric.add(QH2.B,k+1))};
20193 }
20194 }
20195 J = Math.min(m-1,j+3);
20196 x = Array(J-j);
20197 for(i=j+1;i<=J;i++) { x[i-j-1] = H[i][j]; }
20198 v = numeric.house(x);
20199 B = numeric.getBlock(H, [j+1,j],[J,m-1]);
20200 C = numeric.tensor(v,numeric.dot(v,B));
20201 for(i=j+1;i<=J;i++) { Hi = H[i]; Ci = C[i-j-1]; for(k=j;k<m;k++) Hi[k] -= 2*Ci[k-j]; }
20202 B = numeric.getBlock(H, [0,j+1],[m-1,J]);
20203 C = numeric.tensor(numeric.dot(B,v),v);
20204 for(i=0;i<m;i++) { Hi = H[i]; Ci = C[i]; for(k=j+1;k<=J;k++) Hi[k] -= 2*Ci[k-j-1]; }
20205 B = Array(J-j);
20206 for(i=j+1;i<=J;i++) B[i-j-1] = Q[i];
20207 C = numeric.tensor(v,numeric.dot(v,B));
20208 for(i=j+1;i<=J;i++) { Qi = Q[i]; Ci = C[i-j-1]; for(k=0;k<m;k++) Qi[k] -= 2*Ci[k]; }
20209 }
20210 }
20211 throw new Error('numeric: eigenvalue iteration does not converge -- increase maxiter?');
20212}
20213
20214numeric.eig = function eig(A,maxiter) {
20215 var QH = numeric.toUpperHessenberg(A);
20216 var QB = numeric.QRFrancis(QH.H,maxiter);
20217 var T = numeric.T;
20218 var n = A.length,i,k,flag = false,B = QB.B,H = numeric.dot(QB.Q,numeric.dot(QH.H,numeric.transpose(QB.Q)));
20219 var Q = new T(numeric.dot(QB.Q,QH.Q)),Q0;
20220 var m = B.length,j;
20221 var a,b,c,d,p1,p2,disc,x,y,p,q,n1,n2;
20222 var sqrt = Math.sqrt;
20223 for(k=0;k<m;k++) {
20224 i = B[k][0];
20225 if(i === B[k][1]) {
20226 // nothing
20227 } else {
20228 j = i+1;
20229 a = H[i][i];
20230 b = H[i][j];
20231 c = H[j][i];
20232 d = H[j][j];
20233 if(b === 0 && c === 0) continue;
20234 p1 = -a-d;
20235 p2 = a*d-b*c;
20236 disc = p1*p1-4*p2;
20237 if(disc>=0) {
20238 if(p1<0) x = -0.5*(p1-sqrt(disc));
20239 else x = -0.5*(p1+sqrt(disc));
20240 n1 = (a-x)*(a-x)+b*b;
20241 n2 = c*c+(d-x)*(d-x);
20242 if(n1>n2) {
20243 n1 = sqrt(n1);
20244 p = (a-x)/n1;
20245 q = b/n1;
20246 } else {
20247 n2 = sqrt(n2);
20248 p = c/n2;
20249 q = (d-x)/n2;
20250 }
20251 Q0 = new T([[q,-p],[p,q]]);
20252 Q.setRows(i,j,Q0.dot(Q.getRows(i,j)));
20253 } else {
20254 x = -0.5*p1;
20255 y = 0.5*sqrt(-disc);
20256 n1 = (a-x)*(a-x)+b*b;
20257 n2 = c*c+(d-x)*(d-x);
20258 if(n1>n2) {
20259 n1 = sqrt(n1+y*y);
20260 p = (a-x)/n1;
20261 q = b/n1;
20262 x = 0;
20263 y /= n1;
20264 } else {
20265 n2 = sqrt(n2+y*y);
20266 p = c/n2;
20267 q = (d-x)/n2;
20268 x = y/n2;
20269 y = 0;
20270 }
20271 Q0 = new T([[q,-p],[p,q]],[[x,y],[y,-x]]);
20272 Q.setRows(i,j,Q0.dot(Q.getRows(i,j)));
20273 }
20274 }
20275 }
20276 var R = Q.dot(A).dot(Q.transjugate()), n = A.length, E = numeric.T.identity(n);
20277 for(j=0;j<n;j++) {
20278 if(j>0) {
20279 for(k=j-1;k>=0;k--) {
20280 var Rk = R.get([k,k]), Rj = R.get([j,j]);
20281 if(numeric.neq(Rk.x,Rj.x) || numeric.neq(Rk.y,Rj.y)) {
20282 x = R.getRow(k).getBlock([k],[j-1]);
20283 y = E.getRow(j).getBlock([k],[j-1]);
20284 E.set([j,k],(R.get([k,j]).neg().sub(x.dot(y))).div(Rk.sub(Rj)));
20285 } else {
20286 E.setRow(j,E.getRow(k));
20287 continue;
20288 }
20289 }
20290 }
20291 }
20292 for(j=0;j<n;j++) {
20293 x = E.getRow(j);
20294 E.setRow(j,x.div(x.norm2()));
20295 }
20296 E = E.transpose();
20297 E = Q.transjugate().dot(E);
20298 return { lambda:R.getDiag(), E:E };
20299};
20300
20301// 5. Compressed Column Storage matrices
20302numeric.ccsSparse = function ccsSparse(A) {
20303 var m = A.length,n,foo, i,j, counts = [];
20304 for(i=m-1;i!==-1;--i) {
20305 foo = A[i];
20306 for(j in foo) {
20307 j = parseInt(j);
20308 while(j>=counts.length) counts[counts.length] = 0;
20309 if(foo[j]!==0) counts[j]++;
20310 }
20311 }
20312 var n = counts.length;
20313 var Ai = Array(n+1);
20314 Ai[0] = 0;
20315 for(i=0;i<n;++i) Ai[i+1] = Ai[i] + counts[i];
20316 var Aj = Array(Ai[n]), Av = Array(Ai[n]);
20317 for(i=m-1;i!==-1;--i) {
20318 foo = A[i];
20319 for(j in foo) {
20320 if(foo[j]!==0) {
20321 counts[j]--;
20322 Aj[Ai[j]+counts[j]] = i;
20323 Av[Ai[j]+counts[j]] = foo[j];
20324 }
20325 }
20326 }
20327 return [Ai,Aj,Av];
20328}
20329numeric.ccsFull = function ccsFull(A) {
20330 var Ai = A[0], Aj = A[1], Av = A[2], s = numeric.ccsDim(A), m = s[0], n = s[1], i,j,j0,j1,k;
20331 var B = numeric.rep([m,n],0);
20332 for(i=0;i<n;i++) {
20333 j0 = Ai[i];
20334 j1 = Ai[i+1];
20335 for(j=j0;j<j1;++j) { B[Aj[j]][i] = Av[j]; }
20336 }
20337 return B;
20338}
20339numeric.ccsTSolve = function ccsTSolve(A,b,x,bj,xj) {
20340 var Ai = A[0], Aj = A[1], Av = A[2],m = Ai.length-1, max = Math.max,n=0;
20341 if(typeof bj === "undefined") x = numeric.rep([m],0);
20342 if(typeof bj === "undefined") bj = numeric.linspace(0,x.length-1);
20343 if(typeof xj === "undefined") xj = [];
20344 function dfs(j) {
20345 var k;
20346 if(x[j] !== 0) return;
20347 x[j] = 1;
20348 for(k=Ai[j];k<Ai[j+1];++k) dfs(Aj[k]);
20349 xj[n] = j;
20350 ++n;
20351 }
20352 var i,j,j0,j1,k,l,l0,l1,a;
20353 for(i=bj.length-1;i!==-1;--i) { dfs(bj[i]); }
20354 xj.length = n;
20355 for(i=xj.length-1;i!==-1;--i) { x[xj[i]] = 0; }
20356 for(i=bj.length-1;i!==-1;--i) { j = bj[i]; x[j] = b[j]; }
20357 for(i=xj.length-1;i!==-1;--i) {
20358 j = xj[i];
20359 j0 = Ai[j];
20360 j1 = max(Ai[j+1],j0);
20361 for(k=j0;k!==j1;++k) { if(Aj[k] === j) { x[j] /= Av[k]; break; } }
20362 a = x[j];
20363 for(k=j0;k!==j1;++k) {
20364 l = Aj[k];
20365 if(l !== j) x[l] -= a*Av[k];
20366 }
20367 }
20368 return x;
20369}
20370numeric.ccsDFS = function ccsDFS(n) {
20371 this.k = Array(n);
20372 this.k1 = Array(n);
20373 this.j = Array(n);
20374}
20375numeric.ccsDFS.prototype.dfs = function dfs(J,Ai,Aj,x,xj,Pinv) {
20376 var m = 0,foo,n=xj.length;
20377 var k = this.k, k1 = this.k1, j = this.j,km,k11;
20378 if(x[J]!==0) return;
20379 x[J] = 1;
20380 j[0] = J;
20381 k[0] = km = Ai[J];
20382 k1[0] = k11 = Ai[J+1];
20383 while(1) {
20384 if(km >= k11) {
20385 xj[n] = j[m];
20386 if(m===0) return;
20387 ++n;
20388 --m;
20389 km = k[m];
20390 k11 = k1[m];
20391 } else {
20392 foo = Pinv[Aj[km]];
20393 if(x[foo] === 0) {
20394 x[foo] = 1;
20395 k[m] = km;
20396 ++m;
20397 j[m] = foo;
20398 km = Ai[foo];
20399 k1[m] = k11 = Ai[foo+1];
20400 } else ++km;
20401 }
20402 }
20403}
20404numeric.ccsLPSolve = function ccsLPSolve(A,B,x,xj,I,Pinv,dfs) {
20405 var Ai = A[0], Aj = A[1], Av = A[2],m = Ai.length-1, n=0;
20406 var Bi = B[0], Bj = B[1], Bv = B[2];
20407
20408 var i,i0,i1,j,J,j0,j1,k,l,l0,l1,a;
20409 i0 = Bi[I];
20410 i1 = Bi[I+1];
20411 xj.length = 0;
20412 for(i=i0;i<i1;++i) { dfs.dfs(Pinv[Bj[i]],Ai,Aj,x,xj,Pinv); }
20413 for(i=xj.length-1;i!==-1;--i) { x[xj[i]] = 0; }
20414 for(i=i0;i!==i1;++i) { j = Pinv[Bj[i]]; x[j] = Bv[i]; }
20415 for(i=xj.length-1;i!==-1;--i) {
20416 j = xj[i];
20417 j0 = Ai[j];
20418 j1 = Ai[j+1];
20419 for(k=j0;k<j1;++k) { if(Pinv[Aj[k]] === j) { x[j] /= Av[k]; break; } }
20420 a = x[j];
20421 for(k=j0;k<j1;++k) {
20422 l = Pinv[Aj[k]];
20423 if(l !== j) x[l] -= a*Av[k];
20424 }
20425 }
20426 return x;
20427}
20428numeric.ccsLUP1 = function ccsLUP1(A,threshold) {
20429 var m = A[0].length-1;
20430 var L = [numeric.rep([m+1],0),[],[]], U = [numeric.rep([m+1], 0),[],[]];
20431 var Li = L[0], Lj = L[1], Lv = L[2], Ui = U[0], Uj = U[1], Uv = U[2];
20432 var x = numeric.rep([m],0), xj = numeric.rep([m],0);
20433 var i,j,k,j0,j1,a,e,c,d,K;
20434 var sol = numeric.ccsLPSolve, max = Math.max, abs = Math.abs;
20435 var P = numeric.linspace(0,m-1),Pinv = numeric.linspace(0,m-1);
20436 var dfs = new numeric.ccsDFS(m);
20437 if(typeof threshold === "undefined") { threshold = 1; }
20438 for(i=0;i<m;++i) {
20439 sol(L,A,x,xj,i,Pinv,dfs);
20440 a = -1;
20441 e = -1;
20442 for(j=xj.length-1;j!==-1;--j) {
20443 k = xj[j];
20444 if(k <= i) continue;
20445 c = abs(x[k]);
20446 if(c > a) { e = k; a = c; }
20447 }
20448 if(abs(x[i])<threshold*a) {
20449 j = P[i];
20450 a = P[e];
20451 P[i] = a; Pinv[a] = i;
20452 P[e] = j; Pinv[j] = e;
20453 a = x[i]; x[i] = x[e]; x[e] = a;
20454 }
20455 a = Li[i];
20456 e = Ui[i];
20457 d = x[i];
20458 Lj[a] = P[i];
20459 Lv[a] = 1;
20460 ++a;
20461 for(j=xj.length-1;j!==-1;--j) {
20462 k = xj[j];
20463 c = x[k];
20464 xj[j] = 0;
20465 x[k] = 0;
20466 if(k<=i) { Uj[e] = k; Uv[e] = c; ++e; }
20467 else { Lj[a] = P[k]; Lv[a] = c/d; ++a; }
20468 }
20469 Li[i+1] = a;
20470 Ui[i+1] = e;
20471 }
20472 for(j=Lj.length-1;j!==-1;--j) { Lj[j] = Pinv[Lj[j]]; }
20473 return {L:L, U:U, P:P, Pinv:Pinv};
20474}
20475numeric.ccsDFS0 = function ccsDFS0(n) {
20476 this.k = Array(n);
20477 this.k1 = Array(n);
20478 this.j = Array(n);
20479}
20480numeric.ccsDFS0.prototype.dfs = function dfs(J,Ai,Aj,x,xj,Pinv,P) {
20481 var m = 0,foo,n=xj.length;
20482 var k = this.k, k1 = this.k1, j = this.j,km,k11;
20483 if(x[J]!==0) return;
20484 x[J] = 1;
20485 j[0] = J;
20486 k[0] = km = Ai[Pinv[J]];
20487 k1[0] = k11 = Ai[Pinv[J]+1];
20488 while(1) {
20489 if(isNaN(km)) throw new Error("Ow!");
20490 if(km >= k11) {
20491 xj[n] = Pinv[j[m]];
20492 if(m===0) return;
20493 ++n;
20494 --m;
20495 km = k[m];
20496 k11 = k1[m];
20497 } else {
20498 foo = Aj[km];
20499 if(x[foo] === 0) {
20500 x[foo] = 1;
20501 k[m] = km;
20502 ++m;
20503 j[m] = foo;
20504 foo = Pinv[foo];
20505 km = Ai[foo];
20506 k1[m] = k11 = Ai[foo+1];
20507 } else ++km;
20508 }
20509 }
20510}
20511numeric.ccsLPSolve0 = function ccsLPSolve0(A,B,y,xj,I,Pinv,P,dfs) {
20512 var Ai = A[0], Aj = A[1], Av = A[2],m = Ai.length-1, n=0;
20513 var Bi = B[0], Bj = B[1], Bv = B[2];
20514
20515 var i,i0,i1,j,J,j0,j1,k,l,l0,l1,a;
20516 i0 = Bi[I];
20517 i1 = Bi[I+1];
20518 xj.length = 0;
20519 for(i=i0;i<i1;++i) { dfs.dfs(Bj[i],Ai,Aj,y,xj,Pinv,P); }
20520 for(i=xj.length-1;i!==-1;--i) { j = xj[i]; y[P[j]] = 0; }
20521 for(i=i0;i!==i1;++i) { j = Bj[i]; y[j] = Bv[i]; }
20522 for(i=xj.length-1;i!==-1;--i) {
20523 j = xj[i];
20524 l = P[j];
20525 j0 = Ai[j];
20526 j1 = Ai[j+1];
20527 for(k=j0;k<j1;++k) { if(Aj[k] === l) { y[l] /= Av[k]; break; } }
20528 a = y[l];
20529 for(k=j0;k<j1;++k) y[Aj[k]] -= a*Av[k];
20530 y[l] = a;
20531 }
20532}
20533numeric.ccsLUP0 = function ccsLUP0(A,threshold) {
20534 var m = A[0].length-1;
20535 var L = [numeric.rep([m+1],0),[],[]], U = [numeric.rep([m+1], 0),[],[]];
20536 var Li = L[0], Lj = L[1], Lv = L[2], Ui = U[0], Uj = U[1], Uv = U[2];
20537 var y = numeric.rep([m],0), xj = numeric.rep([m],0);
20538 var i,j,k,j0,j1,a,e,c,d,K;
20539 var sol = numeric.ccsLPSolve0, max = Math.max, abs = Math.abs;
20540 var P = numeric.linspace(0,m-1),Pinv = numeric.linspace(0,m-1);
20541 var dfs = new numeric.ccsDFS0(m);
20542 if(typeof threshold === "undefined") { threshold = 1; }
20543 for(i=0;i<m;++i) {
20544 sol(L,A,y,xj,i,Pinv,P,dfs);
20545 a = -1;
20546 e = -1;
20547 for(j=xj.length-1;j!==-1;--j) {
20548 k = xj[j];
20549 if(k <= i) continue;
20550 c = abs(y[P[k]]);
20551 if(c > a) { e = k; a = c; }
20552 }
20553 if(abs(y[P[i]])<threshold*a) {
20554 j = P[i];
20555 a = P[e];
20556 P[i] = a; Pinv[a] = i;
20557 P[e] = j; Pinv[j] = e;
20558 }
20559 a = Li[i];
20560 e = Ui[i];
20561 d = y[P[i]];
20562 Lj[a] = P[i];
20563 Lv[a] = 1;
20564 ++a;
20565 for(j=xj.length-1;j!==-1;--j) {
20566 k = xj[j];
20567 c = y[P[k]];
20568 xj[j] = 0;
20569 y[P[k]] = 0;
20570 if(k<=i) { Uj[e] = k; Uv[e] = c; ++e; }
20571 else { Lj[a] = P[k]; Lv[a] = c/d; ++a; }
20572 }
20573 Li[i+1] = a;
20574 Ui[i+1] = e;
20575 }
20576 for(j=Lj.length-1;j!==-1;--j) { Lj[j] = Pinv[Lj[j]]; }
20577 return {L:L, U:U, P:P, Pinv:Pinv};
20578}
20579numeric.ccsLUP = numeric.ccsLUP0;
20580
20581numeric.ccsDim = function ccsDim(A) { return [numeric.sup(A[1])+1,A[0].length-1]; }
20582numeric.ccsGetBlock = function ccsGetBlock(A,i,j) {
20583 var s = numeric.ccsDim(A),m=s[0],n=s[1];
20584 if(typeof i === "undefined") { i = numeric.linspace(0,m-1); }
20585 else if(typeof i === "number") { i = [i]; }
20586 if(typeof j === "undefined") { j = numeric.linspace(0,n-1); }
20587 else if(typeof j === "number") { j = [j]; }
20588 var p,p0,p1,P = i.length,q,Q = j.length,r,jq,ip;
20589 var Bi = numeric.rep([n],0), Bj=[], Bv=[], B = [Bi,Bj,Bv];
20590 var Ai = A[0], Aj = A[1], Av = A[2];
20591 var x = numeric.rep([m],0),count=0,flags = numeric.rep([m],0);
20592 for(q=0;q<Q;++q) {
20593 jq = j[q];
20594 var q0 = Ai[jq];
20595 var q1 = Ai[jq+1];
20596 for(p=q0;p<q1;++p) {
20597 r = Aj[p];
20598 flags[r] = 1;
20599 x[r] = Av[p];
20600 }
20601 for(p=0;p<P;++p) {
20602 ip = i[p];
20603 if(flags[ip]) {
20604 Bj[count] = p;
20605 Bv[count] = x[i[p]];
20606 ++count;
20607 }
20608 }
20609 for(p=q0;p<q1;++p) {
20610 r = Aj[p];
20611 flags[r] = 0;
20612 }
20613 Bi[q+1] = count;
20614 }
20615 return B;
20616}
20617
20618numeric.ccsDot = function ccsDot(A,B) {
20619 var Ai = A[0], Aj = A[1], Av = A[2];
20620 var Bi = B[0], Bj = B[1], Bv = B[2];
20621 var sA = numeric.ccsDim(A), sB = numeric.ccsDim(B);
20622 var m = sA[0], n = sA[1], o = sB[1];
20623 var x = numeric.rep([m],0), flags = numeric.rep([m],0), xj = Array(m);
20624 var Ci = numeric.rep([o],0), Cj = [], Cv = [], C = [Ci,Cj,Cv];
20625 var i,j,k,j0,j1,i0,i1,l,p,a,b;
20626 for(k=0;k!==o;++k) {
20627 j0 = Bi[k];
20628 j1 = Bi[k+1];
20629 p = 0;
20630 for(j=j0;j<j1;++j) {
20631 a = Bj[j];
20632 b = Bv[j];
20633 i0 = Ai[a];
20634 i1 = Ai[a+1];
20635 for(i=i0;i<i1;++i) {
20636 l = Aj[i];
20637 if(flags[l]===0) {
20638 xj[p] = l;
20639 flags[l] = 1;
20640 p = p+1;
20641 }
20642 x[l] = x[l] + Av[i]*b;
20643 }
20644 }
20645 j0 = Ci[k];
20646 j1 = j0+p;
20647 Ci[k+1] = j1;
20648 for(j=p-1;j!==-1;--j) {
20649 b = j0+j;
20650 i = xj[j];
20651 Cj[b] = i;
20652 Cv[b] = x[i];
20653 flags[i] = 0;
20654 x[i] = 0;
20655 }
20656 Ci[k+1] = Ci[k]+p;
20657 }
20658 return C;
20659}
20660
20661numeric.ccsLUPSolve = function ccsLUPSolve(LUP,B) {
20662 var L = LUP.L, U = LUP.U, P = LUP.P;
20663 var Bi = B[0];
20664 var flag = false;
20665 if(typeof Bi !== "object") { B = [[0,B.length],numeric.linspace(0,B.length-1),B]; Bi = B[0]; flag = true; }
20666 var Bj = B[1], Bv = B[2];
20667 var n = L[0].length-1, m = Bi.length-1;
20668 var x = numeric.rep([n],0), xj = Array(n);
20669 var b = numeric.rep([n],0), bj = Array(n);
20670 var Xi = numeric.rep([m+1],0), Xj = [], Xv = [];
20671 var sol = numeric.ccsTSolve;
20672 var i,j,j0,j1,k,J,N=0;
20673 for(i=0;i<m;++i) {
20674 k = 0;
20675 j0 = Bi[i];
20676 j1 = Bi[i+1];
20677 for(j=j0;j<j1;++j) {
20678 J = LUP.Pinv[Bj[j]];
20679 bj[k] = J;
20680 b[J] = Bv[j];
20681 ++k;
20682 }
20683 bj.length = k;
20684 sol(L,b,x,bj,xj);
20685 for(j=bj.length-1;j!==-1;--j) b[bj[j]] = 0;
20686 sol(U,x,b,xj,bj);
20687 if(flag) return b;
20688 for(j=xj.length-1;j!==-1;--j) x[xj[j]] = 0;
20689 for(j=bj.length-1;j!==-1;--j) {
20690 J = bj[j];
20691 Xj[N] = J;
20692 Xv[N] = b[J];
20693 b[J] = 0;
20694 ++N;
20695 }
20696 Xi[i+1] = N;
20697 }
20698 return [Xi,Xj,Xv];
20699}
20700
20701numeric.ccsbinop = function ccsbinop(body,setup) {
20702 if(typeof setup === "undefined") setup='';
20703 return Function('X','Y',
20704 'var Xi = X[0], Xj = X[1], Xv = X[2];\n'+
20705 'var Yi = Y[0], Yj = Y[1], Yv = Y[2];\n'+
20706 'var n = Xi.length-1,m = Math.max(numeric.sup(Xj),numeric.sup(Yj))+1;\n'+
20707 'var Zi = numeric.rep([n+1],0), Zj = [], Zv = [];\n'+
20708 'var x = numeric.rep([m],0),y = numeric.rep([m],0);\n'+
20709 'var xk,yk,zk;\n'+
20710 'var i,j,j0,j1,k,p=0;\n'+
20711 setup+
20712 'for(i=0;i<n;++i) {\n'+
20713 ' j0 = Xi[i]; j1 = Xi[i+1];\n'+
20714 ' for(j=j0;j!==j1;++j) {\n'+
20715 ' k = Xj[j];\n'+
20716 ' x[k] = 1;\n'+
20717 ' Zj[p] = k;\n'+
20718 ' ++p;\n'+
20719 ' }\n'+
20720 ' j0 = Yi[i]; j1 = Yi[i+1];\n'+
20721 ' for(j=j0;j!==j1;++j) {\n'+
20722 ' k = Yj[j];\n'+
20723 ' y[k] = Yv[j];\n'+
20724 ' if(x[k] === 0) {\n'+
20725 ' Zj[p] = k;\n'+
20726 ' ++p;\n'+
20727 ' }\n'+
20728 ' }\n'+
20729 ' Zi[i+1] = p;\n'+
20730 ' j0 = Xi[i]; j1 = Xi[i+1];\n'+
20731 ' for(j=j0;j!==j1;++j) x[Xj[j]] = Xv[j];\n'+
20732 ' j0 = Zi[i]; j1 = Zi[i+1];\n'+
20733 ' for(j=j0;j!==j1;++j) {\n'+
20734 ' k = Zj[j];\n'+
20735 ' xk = x[k];\n'+
20736 ' yk = y[k];\n'+
20737 body+'\n'+
20738 ' Zv[j] = zk;\n'+
20739 ' }\n'+
20740 ' j0 = Xi[i]; j1 = Xi[i+1];\n'+
20741 ' for(j=j0;j!==j1;++j) x[Xj[j]] = 0;\n'+
20742 ' j0 = Yi[i]; j1 = Yi[i+1];\n'+
20743 ' for(j=j0;j!==j1;++j) y[Yj[j]] = 0;\n'+
20744 '}\n'+
20745 'return [Zi,Zj,Zv];'
20746 );
20747};
20748
20749(function() {
20750 var k,A,B,C;
20751 for(k in numeric.ops2) {
20752 if(isFinite(eval('1'+numeric.ops2[k]+'0'))) A = '[Y[0],Y[1],numeric.'+k+'(X,Y[2])]';
20753 else A = 'NaN';
20754 if(isFinite(eval('0'+numeric.ops2[k]+'1'))) B = '[X[0],X[1],numeric.'+k+'(X[2],Y)]';
20755 else B = 'NaN';
20756 if(isFinite(eval('1'+numeric.ops2[k]+'0')) && isFinite(eval('0'+numeric.ops2[k]+'1'))) C = 'numeric.ccs'+k+'MM(X,Y)';
20757 else C = 'NaN';
20758 numeric['ccs'+k+'MM'] = numeric.ccsbinop('zk = xk '+numeric.ops2[k]+'yk;');
20759 numeric['ccs'+k] = Function('X','Y',
20760 'if(typeof X === "number") return '+A+';\n'+
20761 'if(typeof Y === "number") return '+B+';\n'+
20762 'return '+C+';\n'
20763 );
20764 }
20765}());
20766
20767numeric.ccsScatter = function ccsScatter(A) {
20768 var Ai = A[0], Aj = A[1], Av = A[2];
20769 var n = numeric.sup(Aj)+1,m=Ai.length;
20770 var Ri = numeric.rep([n],0),Rj=Array(m), Rv = Array(m);
20771 var counts = numeric.rep([n],0),i;
20772 for(i=0;i<m;++i) counts[Aj[i]]++;
20773 for(i=0;i<n;++i) Ri[i+1] = Ri[i] + counts[i];
20774 var ptr = Ri.slice(0),k,Aii;
20775 for(i=0;i<m;++i) {
20776 Aii = Aj[i];
20777 k = ptr[Aii];
20778 Rj[k] = Ai[i];
20779 Rv[k] = Av[i];
20780 ptr[Aii]=ptr[Aii]+1;
20781 }
20782 return [Ri,Rj,Rv];
20783}
20784
20785numeric.ccsGather = function ccsGather(A) {
20786 var Ai = A[0], Aj = A[1], Av = A[2];
20787 var n = Ai.length-1,m = Aj.length;
20788 var Ri = Array(m), Rj = Array(m), Rv = Array(m);
20789 var i,j,j0,j1,p;
20790 p=0;
20791 for(i=0;i<n;++i) {
20792 j0 = Ai[i];
20793 j1 = Ai[i+1];
20794 for(j=j0;j!==j1;++j) {
20795 Rj[p] = i;
20796 Ri[p] = Aj[j];
20797 Rv[p] = Av[j];
20798 ++p;
20799 }
20800 }
20801 return [Ri,Rj,Rv];
20802}
20803
20804// The following sparse linear algebra routines are deprecated.
20805
20806numeric.sdim = function dim(A,ret,k) {
20807 if(typeof ret === "undefined") { ret = []; }
20808 if(typeof A !== "object") return ret;
20809 if(typeof k === "undefined") { k=0; }
20810 if(!(k in ret)) { ret[k] = 0; }
20811 if(A.length > ret[k]) ret[k] = A.length;
20812 var i;
20813 for(i in A) {
20814 if(A.hasOwnProperty(i)) dim(A[i],ret,k+1);
20815 }
20816 return ret;
20817};
20818
20819numeric.sclone = function clone(A,k,n) {
20820 if(typeof k === "undefined") { k=0; }
20821 if(typeof n === "undefined") { n = numeric.sdim(A).length; }
20822 var i,ret = Array(A.length);
20823 if(k === n-1) {
20824 for(i in A) { if(A.hasOwnProperty(i)) ret[i] = A[i]; }
20825 return ret;
20826 }
20827 for(i in A) {
20828 if(A.hasOwnProperty(i)) ret[i] = clone(A[i],k+1,n);
20829 }
20830 return ret;
20831}
20832
20833numeric.sdiag = function diag(d) {
20834 var n = d.length,i,ret = Array(n),i1,i2,i3;
20835 for(i=n-1;i>=1;i-=2) {
20836 i1 = i-1;
20837 ret[i] = []; ret[i][i] = d[i];
20838 ret[i1] = []; ret[i1][i1] = d[i1];
20839 }
20840 if(i===0) { ret[0] = []; ret[0][0] = d[i]; }
20841 return ret;
20842}
20843
20844numeric.sidentity = function identity(n) { return numeric.sdiag(numeric.rep([n],1)); }
20845
20846numeric.stranspose = function transpose(A) {
20847 var ret = [], n = A.length, i,j,Ai;
20848 for(i in A) {
20849 if(!(A.hasOwnProperty(i))) continue;
20850 Ai = A[i];
20851 for(j in Ai) {
20852 if(!(Ai.hasOwnProperty(j))) continue;
20853 if(typeof ret[j] !== "object") { ret[j] = []; }
20854 ret[j][i] = Ai[j];
20855 }
20856 }
20857 return ret;
20858}
20859
20860numeric.sLUP = function LUP(A,tol) {
20861 throw new Error("The function numeric.sLUP had a bug in it and has been removed. Please use the new numeric.ccsLUP function instead.");
20862};
20863
20864numeric.sdotMM = function dotMM(A,B) {
20865 var p = A.length, q = B.length, BT = numeric.stranspose(B), r = BT.length, Ai, BTk;
20866 var i,j,k,accum;
20867 var ret = Array(p),reti;
20868 for(i=p-1;i>=0;i--) {
20869 reti = [];
20870 Ai = A[i];
20871 for(k=r-1;k>=0;k--) {
20872 accum = 0;
20873 BTk = BT[k];
20874 for(j in Ai) {
20875 if(!(Ai.hasOwnProperty(j))) continue;
20876 if(j in BTk) { accum += Ai[j]*BTk[j]; }
20877 }
20878 if(accum) reti[k] = accum;
20879 }
20880 ret[i] = reti;
20881 }
20882 return ret;
20883}
20884
20885numeric.sdotMV = function dotMV(A,x) {
20886 var p = A.length, Ai, i,j;
20887 var ret = Array(p), accum;
20888 for(i=p-1;i>=0;i--) {
20889 Ai = A[i];
20890 accum = 0;
20891 for(j in Ai) {
20892 if(!(Ai.hasOwnProperty(j))) continue;
20893 if(x[j]) accum += Ai[j]*x[j];
20894 }
20895 if(accum) ret[i] = accum;
20896 }
20897 return ret;
20898}
20899
20900numeric.sdotVM = function dotMV(x,A) {
20901 var i,j,Ai,alpha;
20902 var ret = [], accum;
20903 for(i in x) {
20904 if(!x.hasOwnProperty(i)) continue;
20905 Ai = A[i];
20906 alpha = x[i];
20907 for(j in Ai) {
20908 if(!Ai.hasOwnProperty(j)) continue;
20909 if(!ret[j]) { ret[j] = 0; }
20910 ret[j] += alpha*Ai[j];
20911 }
20912 }
20913 return ret;
20914}
20915
20916numeric.sdotVV = function dotVV(x,y) {
20917 var i,ret=0;
20918 for(i in x) { if(x[i] && y[i]) ret+= x[i]*y[i]; }
20919 return ret;
20920}
20921
20922numeric.sdot = function dot(A,B) {
20923 var m = numeric.sdim(A).length, n = numeric.sdim(B).length;
20924 var k = m*1000+n;
20925 switch(k) {
20926 case 0: return A*B;
20927 case 1001: return numeric.sdotVV(A,B);
20928 case 2001: return numeric.sdotMV(A,B);
20929 case 1002: return numeric.sdotVM(A,B);
20930 case 2002: return numeric.sdotMM(A,B);
20931 default: throw new Error('numeric.sdot not implemented for tensors of order '+m+' and '+n);
20932 }
20933}
20934
20935numeric.sscatter = function scatter(V) {
20936 var n = V[0].length, Vij, i, j, m = V.length, A = [], Aj;
20937 for(i=n-1;i>=0;--i) {
20938 if(!V[m-1][i]) continue;
20939 Aj = A;
20940 for(j=0;j<m-2;j++) {
20941 Vij = V[j][i];
20942 if(!Aj[Vij]) Aj[Vij] = [];
20943 Aj = Aj[Vij];
20944 }
20945 Aj[V[j][i]] = V[j+1][i];
20946 }
20947 return A;
20948}
20949
20950numeric.sgather = function gather(A,ret,k) {
20951 if(typeof ret === "undefined") ret = [];
20952 if(typeof k === "undefined") k = [];
20953 var n,i,Ai;
20954 n = k.length;
20955 for(i in A) {
20956 if(A.hasOwnProperty(i)) {
20957 k[n] = parseInt(i);
20958 Ai = A[i];
20959 if(typeof Ai === "number") {
20960 if(Ai) {
20961 if(ret.length === 0) {
20962 for(i=n+1;i>=0;--i) ret[i] = [];
20963 }
20964 for(i=n;i>=0;--i) ret[i].push(k[i]);
20965 ret[n+1].push(Ai);
20966 }
20967 } else gather(Ai,ret,k);
20968 }
20969 }
20970 if(k.length>n) k.pop();
20971 return ret;
20972}
20973
20974// 6. Coordinate matrices
20975numeric.cLU = function LU(A) {
20976 var I = A[0], J = A[1], V = A[2];
20977 var p = I.length, m=0, i,j,k,a,b,c;
20978 for(i=0;i<p;i++) if(I[i]>m) m=I[i];
20979 m++;
20980 var L = Array(m), U = Array(m), left = numeric.rep([m],Infinity), right = numeric.rep([m],-Infinity);
20981 var Ui, Uj,alpha;
20982 for(k=0;k<p;k++) {
20983 i = I[k];
20984 j = J[k];
20985 if(j<left[i]) left[i] = j;
20986 if(j>right[i]) right[i] = j;
20987 }
20988 for(i=0;i<m-1;i++) { if(right[i] > right[i+1]) right[i+1] = right[i]; }
20989 for(i=m-1;i>=1;i--) { if(left[i]<left[i-1]) left[i-1] = left[i]; }
20990 var countL = 0, countU = 0;
20991 for(i=0;i<m;i++) {
20992 U[i] = numeric.rep([right[i]-left[i]+1],0);
20993 L[i] = numeric.rep([i-left[i]],0);
20994 countL += i-left[i]+1;
20995 countU += right[i]-i+1;
20996 }
20997 for(k=0;k<p;k++) { i = I[k]; U[i][J[k]-left[i]] = V[k]; }
20998 for(i=0;i<m-1;i++) {
20999 a = i-left[i];
21000 Ui = U[i];
21001 for(j=i+1;left[j]<=i && j<m;j++) {
21002 b = i-left[j];
21003 c = right[i]-i;
21004 Uj = U[j];
21005 alpha = Uj[b]/Ui[a];
21006 if(alpha) {
21007 for(k=1;k<=c;k++) { Uj[k+b] -= alpha*Ui[k+a]; }
21008 L[j][i-left[j]] = alpha;
21009 }
21010 }
21011 }
21012 var Ui = [], Uj = [], Uv = [], Li = [], Lj = [], Lv = [];
21013 var p,q,foo;
21014 p=0; q=0;
21015 for(i=0;i<m;i++) {
21016 a = left[i];
21017 b = right[i];
21018 foo = U[i];
21019 for(j=i;j<=b;j++) {
21020 if(foo[j-a]) {
21021 Ui[p] = i;
21022 Uj[p] = j;
21023 Uv[p] = foo[j-a];
21024 p++;
21025 }
21026 }
21027 foo = L[i];
21028 for(j=a;j<i;j++) {
21029 if(foo[j-a]) {
21030 Li[q] = i;
21031 Lj[q] = j;
21032 Lv[q] = foo[j-a];
21033 q++;
21034 }
21035 }
21036 Li[q] = i;
21037 Lj[q] = i;
21038 Lv[q] = 1;
21039 q++;
21040 }
21041 return {U:[Ui,Uj,Uv], L:[Li,Lj,Lv]};
21042};
21043
21044numeric.cLUsolve = function LUsolve(lu,b) {
21045 var L = lu.L, U = lu.U, ret = numeric.clone(b);
21046 var Li = L[0], Lj = L[1], Lv = L[2];
21047 var Ui = U[0], Uj = U[1], Uv = U[2];
21048 var p = Ui.length, q = Li.length;
21049 var m = ret.length,i,j,k;
21050 k = 0;
21051 for(i=0;i<m;i++) {
21052 while(Lj[k] < i) {
21053 ret[i] -= Lv[k]*ret[Lj[k]];
21054 k++;
21055 }
21056 k++;
21057 }
21058 k = p-1;
21059 for(i=m-1;i>=0;i--) {
21060 while(Uj[k] > i) {
21061 ret[i] -= Uv[k]*ret[Uj[k]];
21062 k--;
21063 }
21064 ret[i] /= Uv[k];
21065 k--;
21066 }
21067 return ret;
21068};
21069
21070numeric.cgrid = function grid(n,shape) {
21071 if(typeof n === "number") n = [n,n];
21072 var ret = numeric.rep(n,-1);
21073 var i,j,count;
21074 if(typeof shape !== "function") {
21075 switch(shape) {
21076 case 'L':
21077 shape = function(i,j) { return (i>=n[0]/2 || j<n[1]/2); }
21078 break;
21079 default:
21080 shape = function(i,j) { return true; };
21081 break;
21082 }
21083 }
21084 count=0;
21085 for(i=1;i<n[0]-1;i++) for(j=1;j<n[1]-1;j++)
21086 if(shape(i,j)) {
21087 ret[i][j] = count;
21088 count++;
21089 }
21090 return ret;
21091}
21092
21093numeric.cdelsq = function delsq(g) {
21094 var dir = [[-1,0],[0,-1],[0,1],[1,0]];
21095 var s = numeric.dim(g), m = s[0], n = s[1], i,j,k,p,q;
21096 var Li = [], Lj = [], Lv = [];
21097 for(i=1;i<m-1;i++) for(j=1;j<n-1;j++) {
21098 if(g[i][j]<0) continue;
21099 for(k=0;k<4;k++) {
21100 p = i+dir[k][0];
21101 q = j+dir[k][1];
21102 if(g[p][q]<0) continue;
21103 Li.push(g[i][j]);
21104 Lj.push(g[p][q]);
21105 Lv.push(-1);
21106 }
21107 Li.push(g[i][j]);
21108 Lj.push(g[i][j]);
21109 Lv.push(4);
21110 }
21111 return [Li,Lj,Lv];
21112}
21113
21114numeric.cdotMV = function dotMV(A,x) {
21115 var ret, Ai = A[0], Aj = A[1], Av = A[2],k,p=Ai.length,N;
21116 N=0;
21117 for(k=0;k<p;k++) { if(Ai[k]>N) N = Ai[k]; }
21118 N++;
21119 ret = numeric.rep([N],0);
21120 for(k=0;k<p;k++) { ret[Ai[k]]+=Av[k]*x[Aj[k]]; }
21121 return ret;
21122}
21123
21124// 7. Splines
21125
21126numeric.Spline = function Spline(x,yl,yr,kl,kr) { this.x = x; this.yl = yl; this.yr = yr; this.kl = kl; this.kr = kr; }
21127numeric.Spline.prototype._at = function _at(x1,p) {
21128 var x = this.x;
21129 var yl = this.yl;
21130 var yr = this.yr;
21131 var kl = this.kl;
21132 var kr = this.kr;
21133 var x1,a,b,t;
21134 var add = numeric.add, sub = numeric.sub, mul = numeric.mul;
21135 a = sub(mul(kl[p],x[p+1]-x[p]),sub(yr[p+1],yl[p]));
21136 b = add(mul(kr[p+1],x[p]-x[p+1]),sub(yr[p+1],yl[p]));
21137 t = (x1-x[p])/(x[p+1]-x[p]);
21138 var s = t*(1-t);
21139 return add(add(add(mul(1-t,yl[p]),mul(t,yr[p+1])),mul(a,s*(1-t))),mul(b,s*t));
21140}
21141numeric.Spline.prototype.at = function at(x0) {
21142 if(typeof x0 === "number") {
21143 var x = this.x;
21144 var n = x.length;
21145 var p,q,mid,floor = Math.floor,a,b,t;
21146 p = 0;
21147 q = n-1;
21148 while(q-p>1) {
21149 mid = floor((p+q)/2);
21150 if(x[mid] <= x0) p = mid;
21151 else q = mid;
21152 }
21153 return this._at(x0,p);
21154 }
21155 var n = x0.length, i, ret = Array(n);
21156 for(i=n-1;i!==-1;--i) ret[i] = this.at(x0[i]);
21157 return ret;
21158}
21159numeric.Spline.prototype.diff = function diff() {
21160 var x = this.x;
21161 var yl = this.yl;
21162 var yr = this.yr;
21163 var kl = this.kl;
21164 var kr = this.kr;
21165 var n = yl.length;
21166 var i,dx,dy;
21167 var zl = kl, zr = kr, pl = Array(n), pr = Array(n);
21168 var add = numeric.add, mul = numeric.mul, div = numeric.div, sub = numeric.sub;
21169 for(i=n-1;i!==-1;--i) {
21170 dx = x[i+1]-x[i];
21171 dy = sub(yr[i+1],yl[i]);
21172 pl[i] = div(add(mul(dy, 6),mul(kl[i],-4*dx),mul(kr[i+1],-2*dx)),dx*dx);
21173 pr[i+1] = div(add(mul(dy,-6),mul(kl[i], 2*dx),mul(kr[i+1], 4*dx)),dx*dx);
21174 }
21175 return new numeric.Spline(x,zl,zr,pl,pr);
21176}
21177numeric.Spline.prototype.roots = function roots() {
21178 function sqr(x) { return x*x; }
21179 function heval(y0,y1,k0,k1,x) {
21180 var A = k0*2-(y1-y0);
21181 var B = -k1*2+(y1-y0);
21182 var t = (x+1)*0.5;
21183 var s = t*(1-t);
21184 return (1-t)*y0+t*y1+A*s*(1-t)+B*s*t;
21185 }
21186 var ret = [];
21187 var x = this.x, yl = this.yl, yr = this.yr, kl = this.kl, kr = this.kr;
21188 if(typeof yl[0] === "number") {
21189 yl = [yl];
21190 yr = [yr];
21191 kl = [kl];
21192 kr = [kr];
21193 }
21194 var m = yl.length,n=x.length-1,i,j,k,y,s,t;
21195 var ai,bi,ci,di, ret = Array(m),ri,k0,k1,y0,y1,A,B,D,dx,cx,stops,z0,z1,zm,t0,t1,tm;
21196 var sqrt = Math.sqrt;
21197 for(i=0;i!==m;++i) {
21198 ai = yl[i];
21199 bi = yr[i];
21200 ci = kl[i];
21201 di = kr[i];
21202 ri = [];
21203 for(j=0;j!==n;j++) {
21204 if(j>0 && bi[j]*ai[j]<0) ri.push(x[j]);
21205 dx = (x[j+1]-x[j]);
21206 cx = x[j];
21207 y0 = ai[j];
21208 y1 = bi[j+1];
21209 k0 = ci[j]/dx;
21210 k1 = di[j+1]/dx;
21211 D = sqr(k0-k1+3*(y0-y1)) + 12*k1*y0;
21212 A = k1+3*y0+2*k0-3*y1;
21213 B = 3*(k1+k0+2*(y0-y1));
21214 if(D<=0) {
21215 z0 = A/B;
21216 if(z0>x[j] && z0<x[j+1]) stops = [x[j],z0,x[j+1]];
21217 else stops = [x[j],x[j+1]];
21218 } else {
21219 z0 = (A-sqrt(D))/B;
21220 z1 = (A+sqrt(D))/B;
21221 stops = [x[j]];
21222 if(z0>x[j] && z0<x[j+1]) stops.push(z0);
21223 if(z1>x[j] && z1<x[j+1]) stops.push(z1);
21224 stops.push(x[j+1]);
21225 }
21226 t0 = stops[0];
21227 z0 = this._at(t0,j);
21228 for(k=0;k<stops.length-1;k++) {
21229 t1 = stops[k+1];
21230 z1 = this._at(t1,j);
21231 if(z0 === 0) {
21232 ri.push(t0);
21233 t0 = t1;
21234 z0 = z1;
21235 continue;
21236 }
21237 if(z1 === 0 || z0*z1>0) {
21238 t0 = t1;
21239 z0 = z1;
21240 continue;
21241 }
21242 var side = 0;
21243 while(1) {
21244 tm = (z0*t1-z1*t0)/(z0-z1);
21245 if(tm <= t0 || tm >= t1) { break; }
21246 zm = this._at(tm,j);
21247 if(zm*z1>0) {
21248 t1 = tm;
21249 z1 = zm;
21250 if(side === -1) z0*=0.5;
21251 side = -1;
21252 } else if(zm*z0>0) {
21253 t0 = tm;
21254 z0 = zm;
21255 if(side === 1) z1*=0.5;
21256 side = 1;
21257 } else break;
21258 }
21259 ri.push(tm);
21260 t0 = stops[k+1];
21261 z0 = this._at(t0, j);
21262 }
21263 if(z1 === 0) ri.push(t1);
21264 }
21265 ret[i] = ri;
21266 }
21267 if(typeof this.yl[0] === "number") return ret[0];
21268 return ret;
21269}
21270numeric.spline = function spline(x,y,k1,kn) {
21271 var n = x.length, b = [], dx = [], dy = [];
21272 var i;
21273 var sub = numeric.sub,mul = numeric.mul,add = numeric.add;
21274 for(i=n-2;i>=0;i--) { dx[i] = x[i+1]-x[i]; dy[i] = sub(y[i+1],y[i]); }
21275 if(typeof k1 === "string" || typeof kn === "string") {
21276 k1 = kn = "periodic";
21277 }
21278 // Build sparse tridiagonal system
21279 var T = [[],[],[]];
21280 switch(typeof k1) {
21281 case "undefined":
21282 b[0] = mul(3/(dx[0]*dx[0]),dy[0]);
21283 T[0].push(0,0);
21284 T[1].push(0,1);
21285 T[2].push(2/dx[0],1/dx[0]);
21286 break;
21287 case "string":
21288 b[0] = add(mul(3/(dx[n-2]*dx[n-2]),dy[n-2]),mul(3/(dx[0]*dx[0]),dy[0]));
21289 T[0].push(0,0,0);
21290 T[1].push(n-2,0,1);
21291 T[2].push(1/dx[n-2],2/dx[n-2]+2/dx[0],1/dx[0]);
21292 break;
21293 default:
21294 b[0] = k1;
21295 T[0].push(0);
21296 T[1].push(0);
21297 T[2].push(1);
21298 break;
21299 }
21300 for(i=1;i<n-1;i++) {
21301 b[i] = add(mul(3/(dx[i-1]*dx[i-1]),dy[i-1]),mul(3/(dx[i]*dx[i]),dy[i]));
21302 T[0].push(i,i,i);
21303 T[1].push(i-1,i,i+1);
21304 T[2].push(1/dx[i-1],2/dx[i-1]+2/dx[i],1/dx[i]);
21305 }
21306 switch(typeof kn) {
21307 case "undefined":
21308 b[n-1] = mul(3/(dx[n-2]*dx[n-2]),dy[n-2]);
21309 T[0].push(n-1,n-1);
21310 T[1].push(n-2,n-1);
21311 T[2].push(1/dx[n-2],2/dx[n-2]);
21312 break;
21313 case "string":
21314 T[1][T[1].length-1] = 0;
21315 break;
21316 default:
21317 b[n-1] = kn;
21318 T[0].push(n-1);
21319 T[1].push(n-1);
21320 T[2].push(1);
21321 break;
21322 }
21323 if(typeof b[0] !== "number") b = numeric.transpose(b);
21324 else b = [b];
21325 var k = Array(b.length);
21326 if(typeof k1 === "string") {
21327 for(i=k.length-1;i!==-1;--i) {
21328 k[i] = numeric.ccsLUPSolve(numeric.ccsLUP(numeric.ccsScatter(T)),b[i]);
21329 k[i][n-1] = k[i][0];
21330 }
21331 } else {
21332 for(i=k.length-1;i!==-1;--i) {
21333 k[i] = numeric.cLUsolve(numeric.cLU(T),b[i]);
21334 }
21335 }
21336 if(typeof y[0] === "number") k = k[0];
21337 else k = numeric.transpose(k);
21338 return new numeric.Spline(x,y,y,k,k);
21339}
21340
21341// 8. FFT
21342numeric.fftpow2 = function fftpow2(x,y) {
21343 var n = x.length;
21344 if(n === 1) return;
21345 var cos = Math.cos, sin = Math.sin, i,j;
21346 var xe = Array(n/2), ye = Array(n/2), xo = Array(n/2), yo = Array(n/2);
21347 j = n/2;
21348 for(i=n-1;i!==-1;--i) {
21349 --j;
21350 xo[j] = x[i];
21351 yo[j] = y[i];
21352 --i;
21353 xe[j] = x[i];
21354 ye[j] = y[i];
21355 }
21356 fftpow2(xe,ye);
21357 fftpow2(xo,yo);
21358 j = n/2;
21359 var t,k = (-6.2831853071795864769252867665590057683943387987502116419/n),ci,si;
21360 for(i=n-1;i!==-1;--i) {
21361 --j;
21362 if(j === -1) j = n/2-1;
21363 t = k*i;
21364 ci = cos(t);
21365 si = sin(t);
21366 x[i] = xe[j] + ci*xo[j] - si*yo[j];
21367 y[i] = ye[j] + ci*yo[j] + si*xo[j];
21368 }
21369}
21370numeric._ifftpow2 = function _ifftpow2(x,y) {
21371 var n = x.length;
21372 if(n === 1) return;
21373 var cos = Math.cos, sin = Math.sin, i,j;
21374 var xe = Array(n/2), ye = Array(n/2), xo = Array(n/2), yo = Array(n/2);
21375 j = n/2;
21376 for(i=n-1;i!==-1;--i) {
21377 --j;
21378 xo[j] = x[i];
21379 yo[j] = y[i];
21380 --i;
21381 xe[j] = x[i];
21382 ye[j] = y[i];
21383 }
21384 _ifftpow2(xe,ye);
21385 _ifftpow2(xo,yo);
21386 j = n/2;
21387 var t,k = (6.2831853071795864769252867665590057683943387987502116419/n),ci,si;
21388 for(i=n-1;i!==-1;--i) {
21389 --j;
21390 if(j === -1) j = n/2-1;
21391 t = k*i;
21392 ci = cos(t);
21393 si = sin(t);
21394 x[i] = xe[j] + ci*xo[j] - si*yo[j];
21395 y[i] = ye[j] + ci*yo[j] + si*xo[j];
21396 }
21397}
21398numeric.ifftpow2 = function ifftpow2(x,y) {
21399 numeric._ifftpow2(x,y);
21400 numeric.diveq(x,x.length);
21401 numeric.diveq(y,y.length);
21402}
21403numeric.convpow2 = function convpow2(ax,ay,bx,by) {
21404 numeric.fftpow2(ax,ay);
21405 numeric.fftpow2(bx,by);
21406 var i,n = ax.length,axi,bxi,ayi,byi;
21407 for(i=n-1;i!==-1;--i) {
21408 axi = ax[i]; ayi = ay[i]; bxi = bx[i]; byi = by[i];
21409 ax[i] = axi*bxi-ayi*byi;
21410 ay[i] = axi*byi+ayi*bxi;
21411 }
21412 numeric.ifftpow2(ax,ay);
21413}
21414numeric.T.prototype.fft = function fft() {
21415 var x = this.x, y = this.y;
21416 var n = x.length, log = Math.log, log2 = log(2),
21417 p = Math.ceil(log(2*n-1)/log2), m = Math.pow(2,p);
21418 var cx = numeric.rep([m],0), cy = numeric.rep([m],0), cos = Math.cos, sin = Math.sin;
21419 var k, c = (-3.141592653589793238462643383279502884197169399375105820/n),t;
21420 var a = numeric.rep([m],0), b = numeric.rep([m],0),nhalf = Math.floor(n/2);
21421 for(k=0;k<n;k++) a[k] = x[k];
21422 if(typeof y !== "undefined") for(k=0;k<n;k++) b[k] = y[k];
21423 cx[0] = 1;
21424 for(k=1;k<=m/2;k++) {
21425 t = c*k*k;
21426 cx[k] = cos(t);
21427 cy[k] = sin(t);
21428 cx[m-k] = cos(t);
21429 cy[m-k] = sin(t)
21430 }
21431 var X = new numeric.T(a,b), Y = new numeric.T(cx,cy);
21432 X = X.mul(Y);
21433 numeric.convpow2(X.x,X.y,numeric.clone(Y.x),numeric.neg(Y.y));
21434 X = X.mul(Y);
21435 X.x.length = n;
21436 X.y.length = n;
21437 return X;
21438}
21439numeric.T.prototype.ifft = function ifft() {
21440 var x = this.x, y = this.y;
21441 var n = x.length, log = Math.log, log2 = log(2),
21442 p = Math.ceil(log(2*n-1)/log2), m = Math.pow(2,p);
21443 var cx = numeric.rep([m],0), cy = numeric.rep([m],0), cos = Math.cos, sin = Math.sin;
21444 var k, c = (3.141592653589793238462643383279502884197169399375105820/n),t;
21445 var a = numeric.rep([m],0), b = numeric.rep([m],0),nhalf = Math.floor(n/2);
21446 for(k=0;k<n;k++) a[k] = x[k];
21447 if(typeof y !== "undefined") for(k=0;k<n;k++) b[k] = y[k];
21448 cx[0] = 1;
21449 for(k=1;k<=m/2;k++) {
21450 t = c*k*k;
21451 cx[k] = cos(t);
21452 cy[k] = sin(t);
21453 cx[m-k] = cos(t);
21454 cy[m-k] = sin(t)
21455 }
21456 var X = new numeric.T(a,b), Y = new numeric.T(cx,cy);
21457 X = X.mul(Y);
21458 numeric.convpow2(X.x,X.y,numeric.clone(Y.x),numeric.neg(Y.y));
21459 X = X.mul(Y);
21460 X.x.length = n;
21461 X.y.length = n;
21462 return X.div(n);
21463}
21464
21465//9. Unconstrained optimization
21466numeric.gradient = function gradient(f,x) {
21467 var n = x.length;
21468 var f0 = f(x);
21469 if(isNaN(f0)) throw new Error('gradient: f(x) is a NaN!');
21470 var max = Math.max;
21471 var i,x0 = numeric.clone(x),f1,f2, J = Array(n);
21472 var div = numeric.div, sub = numeric.sub,errest,roundoff,max = Math.max,eps = 1e-3,abs = Math.abs, min = Math.min;
21473 var t0,t1,t2,it=0,d1,d2,N;
21474 for(i=0;i<n;i++) {
21475 var h = max(1e-6*f0,1e-8);
21476 while(1) {
21477 ++it;
21478 if(it>20) { throw new Error("Numerical gradient fails"); }
21479 x0[i] = x[i]+h;
21480 f1 = f(x0);
21481 x0[i] = x[i]-h;
21482 f2 = f(x0);
21483 x0[i] = x[i];
21484 if(isNaN(f1) || isNaN(f2)) { h/=16; continue; }
21485 J[i] = (f1-f2)/(2*h);
21486 t0 = x[i]-h;
21487 t1 = x[i];
21488 t2 = x[i]+h;
21489 d1 = (f1-f0)/h;
21490 d2 = (f0-f2)/h;
21491 N = max(abs(J[i]),abs(f0),abs(f1),abs(f2),abs(t0),abs(t1),abs(t2),1e-8);
21492 errest = min(max(abs(d1-J[i]),abs(d2-J[i]),abs(d1-d2))/N,h/N);
21493 if(errest>eps) { h/=16; }
21494 else break;
21495 }
21496 }
21497 return J;
21498}
21499
21500numeric.uncmin = function uncmin(f,x0,tol,gradient,maxit,callback,options) {
21501 var grad = numeric.gradient;
21502 if(typeof options === "undefined") { options = {}; }
21503 if(typeof tol === "undefined") { tol = 1e-8; }
21504 if(typeof gradient === "undefined") { gradient = function(x) { return grad(f,x); }; }
21505 if(typeof maxit === "undefined") maxit = 1000;
21506 x0 = numeric.clone(x0);
21507 var n = x0.length;
21508 var f0 = f(x0),f1,df0;
21509 if(isNaN(f0)) throw new Error('uncmin: f(x0) is a NaN!');
21510 var max = Math.max, norm2 = numeric.norm2;
21511 tol = max(tol,numeric.epsilon);
21512 var step,g0,g1,H1 = options.Hinv || numeric.identity(n);
21513 var dot = numeric.dot, inv = numeric.inv, sub = numeric.sub, add = numeric.add, ten = numeric.tensor, div = numeric.div, mul = numeric.mul;
21514 var all = numeric.all, isfinite = numeric.isFinite, neg = numeric.neg;
21515 var it=0,i,s,x1,y,Hy,Hs,ys,i0,t,nstep,t1,t2;
21516 var msg = "";
21517 g0 = gradient(x0);
21518 while(it<maxit) {
21519 if(typeof callback === "function") { if(callback(it,x0,f0,g0,H1)) { msg = "Callback returned true"; break; } }
21520 if(!all(isfinite(g0))) { msg = "Gradient has Infinity or NaN"; break; }
21521 step = neg(dot(H1,g0));
21522 if(!all(isfinite(step))) { msg = "Search direction has Infinity or NaN"; break; }
21523 nstep = norm2(step);
21524 if(nstep < tol) { msg="Newton step smaller than tol"; break; }
21525 t = 1;
21526 df0 = dot(g0,step);
21527 // line search
21528 x1 = x0;
21529 while(it < maxit) {
21530 if(t*nstep < tol) { break; }
21531 s = mul(step,t);
21532 x1 = add(x0,s);
21533 f1 = f(x1);
21534 if(f1-f0 >= 0.1*t*df0 || isNaN(f1)) {
21535 t *= 0.5;
21536 ++it;
21537 continue;
21538 }
21539 break;
21540 }
21541 if(t*nstep < tol) { msg = "Line search step size smaller than tol"; break; }
21542 if(it === maxit) { msg = "maxit reached during line search"; break; }
21543 g1 = gradient(x1);
21544 y = sub(g1,g0);
21545 ys = dot(y,s);
21546 Hy = dot(H1,y);
21547 H1 = sub(add(H1,
21548 mul(
21549 (ys+dot(y,Hy))/(ys*ys),
21550 ten(s,s) )),
21551 div(add(ten(Hy,s),ten(s,Hy)),ys));
21552 x0 = x1;
21553 f0 = f1;
21554 g0 = g1;
21555 ++it;
21556 }
21557 return {solution: x0, f: f0, gradient: g0, invHessian: H1, iterations:it, message: msg};
21558}
21559
21560// 10. Ode solver (Dormand-Prince)
21561numeric.Dopri = function Dopri(x,y,f,ymid,iterations,msg,events) {
21562 this.x = x;
21563 this.y = y;
21564 this.f = f;
21565 this.ymid = ymid;
21566 this.iterations = iterations;
21567 this.events = events;
21568 this.message = msg;
21569}
21570numeric.Dopri.prototype._at = function _at(xi,j) {
21571 function sqr(x) { return x*x; }
21572 var sol = this;
21573 var xs = sol.x;
21574 var ys = sol.y;
21575 var k1 = sol.f;
21576 var ymid = sol.ymid;
21577 var n = xs.length;
21578 var x0,x1,xh,y0,y1,yh,xi;
21579 var floor = Math.floor,h;
21580 var c = 0.5;
21581 var add = numeric.add, mul = numeric.mul,sub = numeric.sub, p,q,w;
21582 x0 = xs[j];
21583 x1 = xs[j+1];
21584 y0 = ys[j];
21585 y1 = ys[j+1];
21586 h = x1-x0;
21587 xh = x0+c*h;
21588 yh = ymid[j];
21589 p = sub(k1[j ],mul(y0,1/(x0-xh)+2/(x0-x1)));
21590 q = sub(k1[j+1],mul(y1,1/(x1-xh)+2/(x1-x0)));
21591 w = [sqr(xi - x1) * (xi - xh) / sqr(x0 - x1) / (x0 - xh),
21592 sqr(xi - x0) * sqr(xi - x1) / sqr(x0 - xh) / sqr(x1 - xh),
21593 sqr(xi - x0) * (xi - xh) / sqr(x1 - x0) / (x1 - xh),
21594 (xi - x0) * sqr(xi - x1) * (xi - xh) / sqr(x0-x1) / (x0 - xh),
21595 (xi - x1) * sqr(xi - x0) * (xi - xh) / sqr(x0-x1) / (x1 - xh)];
21596 return add(add(add(add(mul(y0,w[0]),
21597 mul(yh,w[1])),
21598 mul(y1,w[2])),
21599 mul( p,w[3])),
21600 mul( q,w[4]));
21601}
21602numeric.Dopri.prototype.at = function at(x) {
21603 var i,j,k,floor = Math.floor;
21604 if(typeof x !== "number") {
21605 var n = x.length, ret = Array(n);
21606 for(i=n-1;i!==-1;--i) {
21607 ret[i] = this.at(x[i]);
21608 }
21609 return ret;
21610 }
21611 var x0 = this.x;
21612 i = 0; j = x0.length-1;
21613 while(j-i>1) {
21614 k = floor(0.5*(i+j));
21615 if(x0[k] <= x) i = k;
21616 else j = k;
21617 }
21618 return this._at(x,i);
21619}
21620
21621numeric.dopri = function dopri(x0,x1,y0,f,tol,maxit,event) {
21622 if(typeof tol === "undefined") { tol = 1e-6; }
21623 if(typeof maxit === "undefined") { maxit = 1000; }
21624 var xs = [x0], ys = [y0], k1 = [f(x0,y0)], k2,k3,k4,k5,k6,k7, ymid = [];
21625 var A2 = 1/5;
21626 var A3 = [3/40,9/40];
21627 var A4 = [44/45,-56/15,32/9];
21628 var A5 = [19372/6561,-25360/2187,64448/6561,-212/729];
21629 var A6 = [9017/3168,-355/33,46732/5247,49/176,-5103/18656];
21630 var b = [35/384,0,500/1113,125/192,-2187/6784,11/84];
21631 var bm = [0.5*6025192743/30085553152,
21632 0,
21633 0.5*51252292925/65400821598,
21634 0.5*-2691868925/45128329728,
21635 0.5*187940372067/1594534317056,
21636 0.5*-1776094331/19743644256,
21637 0.5*11237099/235043384];
21638 var c = [1/5,3/10,4/5,8/9,1,1];
21639 var e = [-71/57600,0,71/16695,-71/1920,17253/339200,-22/525,1/40];
21640 var i = 0,er,j;
21641 var h = (x1-x0)/10;
21642 var it = 0;
21643 var add = numeric.add, mul = numeric.mul, y1,erinf;
21644 var max = Math.max, min = Math.min, abs = Math.abs, norminf = numeric.norminf,pow = Math.pow;
21645 var any = numeric.any, lt = numeric.lt, and = numeric.and, sub = numeric.sub;
21646 var e0, e1, ev;
21647 var ret = new numeric.Dopri(xs,ys,k1,ymid,-1,"");
21648 if(typeof event === "function") e0 = event(x0,y0);
21649 while(x0<x1 && it<maxit) {
21650 ++it;
21651 if(x0+h>x1) h = x1-x0;
21652 k2 = f(x0+c[0]*h, add(y0,mul( A2*h,k1[i])));
21653 k3 = f(x0+c[1]*h, add(add(y0,mul(A3[0]*h,k1[i])),mul(A3[1]*h,k2)));
21654 k4 = f(x0+c[2]*h, add(add(add(y0,mul(A4[0]*h,k1[i])),mul(A4[1]*h,k2)),mul(A4[2]*h,k3)));
21655 k5 = f(x0+c[3]*h, add(add(add(add(y0,mul(A5[0]*h,k1[i])),mul(A5[1]*h,k2)),mul(A5[2]*h,k3)),mul(A5[3]*h,k4)));
21656 k6 = f(x0+c[4]*h,add(add(add(add(add(y0,mul(A6[0]*h,k1[i])),mul(A6[1]*h,k2)),mul(A6[2]*h,k3)),mul(A6[3]*h,k4)),mul(A6[4]*h,k5)));
21657 y1 = add(add(add(add(add(y0,mul(k1[i],h*b[0])),mul(k3,h*b[2])),mul(k4,h*b[3])),mul(k5,h*b[4])),mul(k6,h*b[5]));
21658 k7 = f(x0+h,y1);
21659 er = add(add(add(add(add(mul(k1[i],h*e[0]),mul(k3,h*e[2])),mul(k4,h*e[3])),mul(k5,h*e[4])),mul(k6,h*e[5])),mul(k7,h*e[6]));
21660 if(typeof er === "number") erinf = abs(er);
21661 else erinf = norminf(er);
21662 if(erinf > tol) { // reject
21663 h = 0.2*h*pow(tol/erinf,0.25);
21664 if(x0+h === x0) {
21665 ret.msg = "Step size became too small";
21666 break;
21667 }
21668 continue;
21669 }
21670 ymid[i] = add(add(add(add(add(add(y0,
21671 mul(k1[i],h*bm[0])),
21672 mul(k3 ,h*bm[2])),
21673 mul(k4 ,h*bm[3])),
21674 mul(k5 ,h*bm[4])),
21675 mul(k6 ,h*bm[5])),
21676 mul(k7 ,h*bm[6]));
21677 ++i;
21678 xs[i] = x0+h;
21679 ys[i] = y1;
21680 k1[i] = k7;
21681 if(typeof event === "function") {
21682 var yi,xl = x0,xr = x0+0.5*h,xi;
21683 e1 = event(xr,ymid[i-1]);
21684 ev = and(lt(e0,0),lt(0,e1));
21685 if(!any(ev)) { xl = xr; xr = x0+h; e0 = e1; e1 = event(xr,y1); ev = and(lt(e0,0),lt(0,e1)); }
21686 if(any(ev)) {
21687 var xc, yc, en,ei;
21688 var side=0, sl = 1.0, sr = 1.0;
21689 while(1) {
21690 if(typeof e0 === "number") xi = (sr*e1*xl-sl*e0*xr)/(sr*e1-sl*e0);
21691 else {
21692 xi = xr;
21693 for(j=e0.length-1;j!==-1;--j) {
21694 if(e0[j]<0 && e1[j]>0) xi = min(xi,(sr*e1[j]*xl-sl*e0[j]*xr)/(sr*e1[j]-sl*e0[j]));
21695 }
21696 }
21697 if(xi <= xl || xi >= xr) break;
21698 yi = ret._at(xi, i-1);
21699 ei = event(xi,yi);
21700 en = and(lt(e0,0),lt(0,ei));
21701 if(any(en)) {
21702 xr = xi;
21703 e1 = ei;
21704 ev = en;
21705 sr = 1.0;
21706 if(side === -1) sl *= 0.5;
21707 else sl = 1.0;
21708 side = -1;
21709 } else {
21710 xl = xi;
21711 e0 = ei;
21712 sl = 1.0;
21713 if(side === 1) sr *= 0.5;
21714 else sr = 1.0;
21715 side = 1;
21716 }
21717 }
21718 y1 = ret._at(0.5*(x0+xi),i-1);
21719 ret.f[i] = f(xi,yi);
21720 ret.x[i] = xi;
21721 ret.y[i] = yi;
21722 ret.ymid[i-1] = y1;
21723 ret.events = ev;
21724 ret.iterations = it;
21725 return ret;
21726 }
21727 }
21728 x0 += h;
21729 y0 = y1;
21730 e0 = e1;
21731 h = min(0.8*h*pow(tol/erinf,0.25),4*h);
21732 }
21733 ret.iterations = it;
21734 return ret;
21735}
21736
21737// 11. Ax = b
21738numeric.LU = function(A, fast) {
21739 fast = fast || false;
21740
21741 var abs = Math.abs;
21742 var i, j, k, absAjk, Akk, Ak, Pk, Ai;
21743 var max;
21744 var n = A.length, n1 = n-1;
21745 var P = new Array(n);
21746 if(!fast) A = numeric.clone(A);
21747
21748 for (k = 0; k < n; ++k) {
21749 Pk = k;
21750 Ak = A[k];
21751 max = abs(Ak[k]);
21752 for (j = k + 1; j < n; ++j) {
21753 absAjk = abs(A[j][k]);
21754 if (max < absAjk) {
21755 max = absAjk;
21756 Pk = j;
21757 }
21758 }
21759 P[k] = Pk;
21760
21761 if (Pk != k) {
21762 A[k] = A[Pk];
21763 A[Pk] = Ak;
21764 Ak = A[k];
21765 }
21766
21767 Akk = Ak[k];
21768
21769 for (i = k + 1; i < n; ++i) {
21770 A[i][k] /= Akk;
21771 }
21772
21773 for (i = k + 1; i < n; ++i) {
21774 Ai = A[i];
21775 for (j = k + 1; j < n1; ++j) {
21776 Ai[j] -= Ai[k] * Ak[j];
21777 ++j;
21778 Ai[j] -= Ai[k] * Ak[j];
21779 }
21780 if(j===n1) Ai[j] -= Ai[k] * Ak[j];
21781 }
21782 }
21783
21784 return {
21785 LU: A,
21786 P: P
21787 };
21788}
21789
21790numeric.LUsolve = function LUsolve(LUP, b) {
21791 var i, j;
21792 var LU = LUP.LU;
21793 var n = LU.length;
21794 var x = numeric.clone(b);
21795 var P = LUP.P;
21796 var Pi, LUi, LUii, tmp;
21797
21798 for (i=n-1;i!==-1;--i) x[i] = b[i];
21799 for (i = 0; i < n; ++i) {
21800 Pi = P[i];
21801 if (P[i] !== i) {
21802 tmp = x[i];
21803 x[i] = x[Pi];
21804 x[Pi] = tmp;
21805 }
21806
21807 LUi = LU[i];
21808 for (j = 0; j < i; ++j) {
21809 x[i] -= x[j] * LUi[j];
21810 }
21811 }
21812
21813 for (i = n - 1; i >= 0; --i) {
21814 LUi = LU[i];
21815 for (j = i + 1; j < n; ++j) {
21816 x[i] -= x[j] * LUi[j];
21817 }
21818
21819 x[i] /= LUi[i];
21820 }
21821
21822 return x;
21823}
21824
21825numeric.solve = function solve(A,b,fast) { return numeric.LUsolve(numeric.LU(A,fast), b); }
21826
21827// 12. Linear programming
21828numeric.echelonize = function echelonize(A) {
21829 var s = numeric.dim(A), m = s[0], n = s[1];
21830 var I = numeric.identity(m);
21831 var P = Array(m);
21832 var i,j,k,l,Ai,Ii,Z,a;
21833 var abs = Math.abs;
21834 var diveq = numeric.diveq;
21835 A = numeric.clone(A);
21836 for(i=0;i<m;++i) {
21837 k = 0;
21838 Ai = A[i];
21839 Ii = I[i];
21840 for(j=1;j<n;++j) if(abs(Ai[k])<abs(Ai[j])) k=j;
21841 P[i] = k;
21842 diveq(Ii,Ai[k]);
21843 diveq(Ai,Ai[k]);
21844 for(j=0;j<m;++j) if(j!==i) {
21845 Z = A[j]; a = Z[k];
21846 for(l=n-1;l!==-1;--l) Z[l] -= Ai[l]*a;
21847 Z = I[j];
21848 for(l=m-1;l!==-1;--l) Z[l] -= Ii[l]*a;
21849 }
21850 }
21851 return {I:I, A:A, P:P};
21852}
21853
21854numeric.__solveLP = function __solveLP(c,A,b,tol,maxit,x,flag) {
21855 var sum = numeric.sum, log = numeric.log, mul = numeric.mul, sub = numeric.sub, dot = numeric.dot, div = numeric.div, add = numeric.add;
21856 var m = c.length, n = b.length,y;
21857 var unbounded = false, cb,i0=0;
21858 var alpha = 1.0;
21859 var f0,df0,AT = numeric.transpose(A), svd = numeric.svd,transpose = numeric.transpose,leq = numeric.leq, sqrt = Math.sqrt, abs = Math.abs;
21860 var muleq = numeric.muleq;
21861 var norm = numeric.norminf, any = numeric.any,min = Math.min;
21862 var all = numeric.all, gt = numeric.gt;
21863 var p = Array(m), A0 = Array(n),e=numeric.rep([n],1), H;
21864 var solve = numeric.solve, z = sub(b,dot(A,x)),count;
21865 var dotcc = dot(c,c);
21866 var g;
21867 for(count=i0;count<maxit;++count) {
21868 var i,j,d;
21869 for(i=n-1;i!==-1;--i) A0[i] = div(A[i],z[i]);
21870 var A1 = transpose(A0);
21871 for(i=m-1;i!==-1;--i) p[i] = (/*x[i]+*/sum(A1[i]));
21872 alpha = 0.25*abs(dotcc/dot(c,p));
21873 var a1 = 100*sqrt(dotcc/dot(p,p));
21874 if(!isFinite(alpha) || alpha>a1) alpha = a1;
21875 g = add(c,mul(alpha,p));
21876 H = dot(A1,A0);
21877 for(i=m-1;i!==-1;--i) H[i][i] += 1;
21878 d = solve(H,div(g,alpha),true);
21879 var t0 = div(z,dot(A,d));
21880 var t = 1.0;
21881 for(i=n-1;i!==-1;--i) if(t0[i]<0) t = min(t,-0.999*t0[i]);
21882 y = sub(x,mul(d,t));
21883 z = sub(b,dot(A,y));
21884 if(!all(gt(z,0))) return { solution: x, message: "", iterations: count };
21885 x = y;
21886 if(alpha<tol) return { solution: y, message: "", iterations: count };
21887 if(flag) {
21888 var s = dot(c,g), Ag = dot(A,g);
21889 unbounded = true;
21890 for(i=n-1;i!==-1;--i) if(s*Ag[i]<0) { unbounded = false; break; }
21891 } else {
21892 if(x[m-1]>=0) unbounded = false;
21893 else unbounded = true;
21894 }
21895 if(unbounded) return { solution: y, message: "Unbounded", iterations: count };
21896 }
21897 return { solution: x, message: "maximum iteration count exceeded", iterations:count };
21898}
21899
21900numeric._solveLP = function _solveLP(c,A,b,tol,maxit) {
21901 var m = c.length, n = b.length,y;
21902 var sum = numeric.sum, log = numeric.log, mul = numeric.mul, sub = numeric.sub, dot = numeric.dot, div = numeric.div, add = numeric.add;
21903 var c0 = numeric.rep([m],0).concat([1]);
21904 var J = numeric.rep([n,1],-1);
21905 var A0 = numeric.blockMatrix([[A , J ]]);
21906 var b0 = b;
21907 var y = numeric.rep([m],0).concat(Math.max(0,numeric.sup(numeric.neg(b)))+1);
21908 var x0 = numeric.__solveLP(c0,A0,b0,tol,maxit,y,false);
21909 var x = numeric.clone(x0.solution);
21910 x.length = m;
21911 var foo = numeric.inf(sub(b,dot(A,x)));
21912 if(foo<0) { return { solution: NaN, message: "Infeasible", iterations: x0.iterations }; }
21913 var ret = numeric.__solveLP(c, A, b, tol, maxit-x0.iterations, x, true);
21914 ret.iterations += x0.iterations;
21915 return ret;
21916};
21917
21918numeric.solveLP = function solveLP(c,A,b,Aeq,beq,tol,maxit) {
21919 if(typeof maxit === "undefined") maxit = 1000;
21920 if(typeof tol === "undefined") tol = numeric.epsilon;
21921 if(typeof Aeq === "undefined") return numeric._solveLP(c,A,b,tol,maxit);
21922 var m = Aeq.length, n = Aeq[0].length, o = A.length;
21923 var B = numeric.echelonize(Aeq);
21924 var flags = numeric.rep([n],0);
21925 var P = B.P;
21926 var Q = [];
21927 var i;
21928 for(i=P.length-1;i!==-1;--i) flags[P[i]] = 1;
21929 for(i=n-1;i!==-1;--i) if(flags[i]===0) Q.push(i);
21930 var g = numeric.getRange;
21931 var I = numeric.linspace(0,m-1), J = numeric.linspace(0,o-1);
21932 var Aeq2 = g(Aeq,I,Q), A1 = g(A,J,P), A2 = g(A,J,Q), dot = numeric.dot, sub = numeric.sub;
21933 var A3 = dot(A1,B.I);
21934 var A4 = sub(A2,dot(A3,Aeq2)), b4 = sub(b,dot(A3,beq));
21935 var c1 = Array(P.length), c2 = Array(Q.length);
21936 for(i=P.length-1;i!==-1;--i) c1[i] = c[P[i]];
21937 for(i=Q.length-1;i!==-1;--i) c2[i] = c[Q[i]];
21938 var c4 = sub(c2,dot(c1,dot(B.I,Aeq2)));
21939 var S = numeric._solveLP(c4,A4,b4,tol,maxit);
21940 var x2 = S.solution;
21941 if(x2!==x2) return S;
21942 var x1 = dot(B.I,sub(beq,dot(Aeq2,x2)));
21943 var x = Array(c.length);
21944 for(i=P.length-1;i!==-1;--i) x[P[i]] = x1[i];
21945 for(i=Q.length-1;i!==-1;--i) x[Q[i]] = x2[i];
21946 return { solution: x, message:S.message, iterations: S.iterations };
21947}
21948
21949numeric.MPStoLP = function MPStoLP(MPS) {
21950 if(MPS instanceof String) { MPS.split('\n'); }
21951 var state = 0;
21952 var states = ['Initial state','NAME','ROWS','COLUMNS','RHS','BOUNDS','ENDATA'];
21953 var n = MPS.length;
21954 var i,j,z,N=0,rows = {}, sign = [], rl = 0, vars = {}, nv = 0;
21955 var name;
21956 var c = [], A = [], b = [];
21957 function err(e) { throw new Error('MPStoLP: '+e+'\nLine '+i+': '+MPS[i]+'\nCurrent state: '+states[state]+'\n'); }
21958 for(i=0;i<n;++i) {
21959 z = MPS[i];
21960 var w0 = z.match(/\S*/g);
21961 var w = [];
21962 for(j=0;j<w0.length;++j) if(w0[j]!=="") w.push(w0[j]);
21963 if(w.length === 0) continue;
21964 for(j=0;j<states.length;++j) if(z.substr(0,states[j].length) === states[j]) break;
21965 if(j<states.length) {
21966 state = j;
21967 if(j===1) { name = w[1]; }
21968 if(j===6) return { name:name, c:c, A:numeric.transpose(A), b:b, rows:rows, vars:vars };
21969 continue;
21970 }
21971 switch(state) {
21972 case 0: case 1: err('Unexpected line');
21973 case 2:
21974 switch(w[0]) {
21975 case 'N': if(N===0) N = w[1]; else err('Two or more N rows'); break;
21976 case 'L': rows[w[1]] = rl; sign[rl] = 1; b[rl] = 0; ++rl; break;
21977 case 'G': rows[w[1]] = rl; sign[rl] = -1;b[rl] = 0; ++rl; break;
21978 case 'E': rows[w[1]] = rl; sign[rl] = 0;b[rl] = 0; ++rl; break;
21979 default: err('Parse error '+numeric.prettyPrint(w));
21980 }
21981 break;
21982 case 3:
21983 if(!vars.hasOwnProperty(w[0])) { vars[w[0]] = nv; c[nv] = 0; A[nv] = numeric.rep([rl],0); ++nv; }
21984 var p = vars[w[0]];
21985 for(j=1;j<w.length;j+=2) {
21986 if(w[j] === N) { c[p] = parseFloat(w[j+1]); continue; }
21987 var q = rows[w[j]];
21988 A[p][q] = (sign[q]<0?-1:1)*parseFloat(w[j+1]);
21989 }
21990 break;
21991 case 4:
21992 for(j=1;j<w.length;j+=2) b[rows[w[j]]] = (sign[rows[w[j]]]<0?-1:1)*parseFloat(w[j+1]);
21993 break;
21994 case 5: /*FIXME*/ break;
21995 case 6: err('Internal error');
21996 }
21997 }
21998 err('Reached end of file without ENDATA');
21999}
22000// seedrandom.js version 2.0.
22001// Author: David Bau 4/2/2011
22002//
22003// Defines a method Math.seedrandom() that, when called, substitutes
22004// an explicitly seeded RC4-based algorithm for Math.random(). Also
22005// supports automatic seeding from local or network sources of entropy.
22006//
22007// Usage:
22008//
22009// <script src=http://davidbau.com/encode/seedrandom-min.js></script>
22010//
22011// Math.seedrandom('yipee'); Sets Math.random to a function that is
22012// initialized using the given explicit seed.
22013//
22014// Math.seedrandom(); Sets Math.random to a function that is
22015// seeded using the current time, dom state,
22016// and other accumulated local entropy.
22017// The generated seed string is returned.
22018//
22019// Math.seedrandom('yowza', true);
22020// Seeds using the given explicit seed mixed
22021// together with accumulated entropy.
22022//
22023// <script src="http://bit.ly/srandom-512"></script>
22024// Seeds using physical random bits downloaded
22025// from random.org.
22026//
22027// <script src="https://jsonlib.appspot.com/urandom?callback=Math.seedrandom">
22028// </script> Seeds using urandom bits from call.jsonlib.com,
22029// which is faster than random.org.
22030//
22031// Examples:
22032//
22033// Math.seedrandom("hello"); // Use "hello" as the seed.
22034// document.write(Math.random()); // Always 0.5463663768140734
22035// document.write(Math.random()); // Always 0.43973793770592234
22036// var rng1 = Math.random; // Remember the current prng.
22037//
22038// var autoseed = Math.seedrandom(); // New prng with an automatic seed.
22039// document.write(Math.random()); // Pretty much unpredictable.
22040//
22041// Math.random = rng1; // Continue "hello" prng sequence.
22042// document.write(Math.random()); // Always 0.554769432473455
22043//
22044// Math.seedrandom(autoseed); // Restart at the previous seed.
22045// document.write(Math.random()); // Repeat the 'unpredictable' value.
22046//
22047// Notes:
22048//
22049// Each time seedrandom('arg') is called, entropy from the passed seed
22050// is accumulated in a pool to help generate future seeds for the
22051// zero-argument form of Math.seedrandom, so entropy can be injected over
22052// time by calling seedrandom with explicit data repeatedly.
22053//
22054// On speed - This javascript implementation of Math.random() is about
22055// 3-10x slower than the built-in Math.random() because it is not native
22056// code, but this is typically fast enough anyway. Seeding is more expensive,
22057// especially if you use auto-seeding. Some details (timings on Chrome 4):
22058//
22059// Our Math.random() - avg less than 0.002 milliseconds per call
22060// seedrandom('explicit') - avg less than 0.5 milliseconds per call
22061// seedrandom('explicit', true) - avg less than 2 milliseconds per call
22062// seedrandom() - avg about 38 milliseconds per call
22063//
22064// LICENSE (BSD):
22065//
22066// Copyright 2010 David Bau, all rights reserved.
22067//
22068// Redistribution and use in source and binary forms, with or without
22069// modification, are permitted provided that the following conditions are met:
22070//
22071// 1. Redistributions of source code must retain the above copyright
22072// notice, this list of conditions and the following disclaimer.
22073//
22074// 2. Redistributions in binary form must reproduce the above copyright
22075// notice, this list of conditions and the following disclaimer in the
22076// documentation and/or other materials provided with the distribution.
22077//
22078// 3. Neither the name of this module nor the names of its contributors may
22079// be used to endorse or promote products derived from this software
22080// without specific prior written permission.
22081//
22082// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22083// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22084// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22085// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22086// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22087// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22088// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22089// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22090// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22091// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
22092// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
22093//
22094/**
22095 * All code is in an anonymous closure to keep the global namespace clean.
22096 *
22097 * @param {number=} overflow
22098 * @param {number=} startdenom
22099 */
22100
22101// Patched by Seb so that seedrandom.js does not pollute the Math object.
22102// My tests suggest that doing Math.trouble = 1 makes Math lookups about 5%
22103// slower.
22104numeric.seedrandom = { pow:Math.pow, random:Math.random };
22105
22106(function (pool, math, width, chunks, significance, overflow, startdenom) {
22107
22108
22109//
22110// seedrandom()
22111// This is the seedrandom function described above.
22112//
22113math['seedrandom'] = function seedrandom(seed, use_entropy) {
22114 var key = [];
22115 var arc4;
22116
22117 // Flatten the seed string or build one from local entropy if needed.
22118 seed = mixkey(flatten(
22119 use_entropy ? [seed, pool] :
22120 arguments.length ? seed :
22121 [new Date().getTime(), pool, window], 3), key);
22122
22123 // Use the seed to initialize an ARC4 generator.
22124 arc4 = new ARC4(key);
22125
22126 // Mix the randomness into accumulated entropy.
22127 mixkey(arc4.S, pool);
22128
22129 // Override Math.random
22130
22131 // This function returns a random double in [0, 1) that contains
22132 // randomness in every bit of the mantissa of the IEEE 754 value.
22133
22134 math['random'] = function random() { // Closure to return a random double:
22135 var n = arc4.g(chunks); // Start with a numerator n < 2 ^ 48
22136 var d = startdenom; // and denominator d = 2 ^ 48.
22137 var x = 0; // and no 'extra last byte'.
22138 while (n < significance) { // Fill up all significant digits by
22139 n = (n + x) * width; // shifting numerator and
22140 d *= width; // denominator and generating a
22141 x = arc4.g(1); // new least-significant-byte.
22142 }
22143 while (n >= overflow) { // To avoid rounding up, before adding
22144 n /= 2; // last byte, shift everything
22145 d /= 2; // right using integer math until
22146 x >>>= 1; // we have exactly the desired bits.
22147 }
22148 return (n + x) / d; // Form the number within [0, 1).
22149 };
22150
22151 // Return the seed that was used
22152 return seed;
22153};
22154
22155//
22156// ARC4
22157//
22158// An ARC4 implementation. The constructor takes a key in the form of
22159// an array of at most (width) integers that should be 0 <= x < (width).
22160//
22161// The g(count) method returns a pseudorandom integer that concatenates
22162// the next (count) outputs from ARC4. Its return value is a number x
22163// that is in the range 0 <= x < (width ^ count).
22164//
22165/** @constructor */
22166function ARC4(key) {
22167 var t, u, me = this, keylen = key.length;
22168 var i = 0, j = me.i = me.j = me.m = 0;
22169 me.S = [];
22170 me.c = [];
22171
22172 // The empty key [] is treated as [0].
22173 if (!keylen) { key = [keylen++]; }
22174
22175 // Set up S using the standard key scheduling algorithm.
22176 while (i < width) { me.S[i] = i++; }
22177 for (i = 0; i < width; i++) {
22178 t = me.S[i];
22179 j = lowbits(j + t + key[i % keylen]);
22180 u = me.S[j];
22181 me.S[i] = u;
22182 me.S[j] = t;
22183 }
22184
22185 // The "g" method returns the next (count) outputs as one number.
22186 me.g = function getnext(count) {
22187 var s = me.S;
22188 var i = lowbits(me.i + 1); var t = s[i];
22189 var j = lowbits(me.j + t); var u = s[j];
22190 s[i] = u;
22191 s[j] = t;
22192 var r = s[lowbits(t + u)];
22193 while (--count) {
22194 i = lowbits(i + 1); t = s[i];
22195 j = lowbits(j + t); u = s[j];
22196 s[i] = u;
22197 s[j] = t;
22198 r = r * width + s[lowbits(t + u)];
22199 }
22200 me.i = i;
22201 me.j = j;
22202 return r;
22203 };
22204 // For robust unpredictability discard an initial batch of values.
22205 // See http://www.rsa.com/rsalabs/node.asp?id=2009
22206 me.g(width);
22207}
22208
22209//
22210// flatten()
22211// Converts an object tree to nested arrays of strings.
22212//
22213/** @param {Object=} result
22214 * @param {string=} prop
22215 * @param {string=} typ */
22216function flatten(obj, depth, result, prop, typ) {
22217 result = [];
22218 typ = typeof(obj);
22219 if (depth && typ == 'object') {
22220 for (prop in obj) {
22221 if (prop.indexOf('S') < 5) { // Avoid FF3 bug (local/sessionStorage)
22222 try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}
22223 }
22224 }
22225 }
22226 return (result.length ? result : obj + (typ != 'string' ? '\0' : ''));
22227}
22228
22229//
22230// mixkey()
22231// Mixes a string seed into a key that is an array of integers, and
22232// returns a shortened string seed that is equivalent to the result key.
22233//
22234/** @param {number=} smear
22235 * @param {number=} j */
22236function mixkey(seed, key, smear, j) {
22237 seed += ''; // Ensure the seed is a string
22238 smear = 0;
22239 for (j = 0; j < seed.length; j++) {
22240 key[lowbits(j)] =
22241 lowbits((smear ^= key[lowbits(j)] * 19) + seed.charCodeAt(j));
22242 }
22243 seed = '';
22244 for (j in key) { seed += String.fromCharCode(key[j]); }
22245 return seed;
22246}
22247
22248//
22249// lowbits()
22250// A quick "n mod width" for width a power of 2.
22251//
22252function lowbits(n) { return n & (width - 1); }
22253
22254//
22255// The following constants are related to IEEE 754 limits.
22256//
22257startdenom = math.pow(width, chunks);
22258significance = math.pow(2, significance);
22259overflow = significance * 2;
22260
22261//
22262// When seedrandom.js is loaded, we immediately mix a few bits
22263// from the built-in RNG into the entropy pool. Because we do
22264// not want to intefere with determinstic PRNG state later,
22265// seedrandom will not call math.random on its own again after
22266// initialization.
22267//
22268mixkey(math.random(), pool);
22269
22270// End anonymous scope, and pass initial values.
22271}(
22272 [], // pool: entropy pool starts empty
22273 numeric.seedrandom, // math: package containing random, pow, and seedrandom
22274 256, // width: each RC4 output is 0 <= x < 256
22275 6, // chunks: at least six RC4 outputs for each double
22276 52 // significance: there are 52 significant digits in a double
22277 ));
22278/* This file is a slightly modified version of quadprog.js from Alberto Santini.
22279 * It has been slightly modified by Sébastien Loisel to make sure that it handles
22280 * 0-based Arrays instead of 1-based Arrays.
22281 * License is in resources/LICENSE.quadprog */
22282(function(exports) {
22283
22284function base0to1(A) {
22285 if(typeof A !== "object") { return A; }
22286 var ret = [], i,n=A.length;
22287 for(i=0;i<n;i++) ret[i+1] = base0to1(A[i]);
22288 return ret;
22289}
22290function base1to0(A) {
22291 if(typeof A !== "object") { return A; }
22292 var ret = [], i,n=A.length;
22293 for(i=1;i<n;i++) ret[i-1] = base1to0(A[i]);
22294 return ret;
22295}
22296
22297function dpori(a, lda, n) {
22298 var i, j, k, kp1, t;
22299
22300 for (k = 1; k <= n; k = k + 1) {
22301 a[k][k] = 1 / a[k][k];
22302 t = -a[k][k];
22303 //~ dscal(k - 1, t, a[1][k], 1);
22304 for (i = 1; i < k; i = i + 1) {
22305 a[i][k] = t * a[i][k];
22306 }
22307
22308 kp1 = k + 1;
22309 if (n < kp1) {
22310 break;
22311 }
22312 for (j = kp1; j <= n; j = j + 1) {
22313 t = a[k][j];
22314 a[k][j] = 0;
22315 //~ daxpy(k, t, a[1][k], 1, a[1][j], 1);
22316 for (i = 1; i <= k; i = i + 1) {
22317 a[i][j] = a[i][j] + (t * a[i][k]);
22318 }
22319 }
22320 }
22321
22322}
22323
22324function dposl(a, lda, n, b) {
22325 var i, k, kb, t;
22326
22327 for (k = 1; k <= n; k = k + 1) {
22328 //~ t = ddot(k - 1, a[1][k], 1, b[1], 1);
22329 t = 0;
22330 for (i = 1; i < k; i = i + 1) {
22331 t = t + (a[i][k] * b[i]);
22332 }
22333
22334 b[k] = (b[k] - t) / a[k][k];
22335 }
22336
22337 for (kb = 1; kb <= n; kb = kb + 1) {
22338 k = n + 1 - kb;
22339 b[k] = b[k] / a[k][k];
22340 t = -b[k];
22341 //~ daxpy(k - 1, t, a[1][k], 1, b[1], 1);
22342 for (i = 1; i < k; i = i + 1) {
22343 b[i] = b[i] + (t * a[i][k]);
22344 }
22345 }
22346}
22347
22348function dpofa(a, lda, n, info) {
22349 var i, j, jm1, k, t, s;
22350
22351 for (j = 1; j <= n; j = j + 1) {
22352 info[1] = j;
22353 s = 0;
22354 jm1 = j - 1;
22355 if (jm1 < 1) {
22356 s = a[j][j] - s;
22357 if (s <= 0) {
22358 break;
22359 }
22360 a[j][j] = Math.sqrt(s);
22361 } else {
22362 for (k = 1; k <= jm1; k = k + 1) {
22363 //~ t = a[k][j] - ddot(k - 1, a[1][k], 1, a[1][j], 1);
22364 t = a[k][j];
22365 for (i = 1; i < k; i = i + 1) {
22366 t = t - (a[i][j] * a[i][k]);
22367 }
22368 t = t / a[k][k];
22369 a[k][j] = t;
22370 s = s + t * t;
22371 }
22372 s = a[j][j] - s;
22373 if (s <= 0) {
22374 break;
22375 }
22376 a[j][j] = Math.sqrt(s);
22377 }
22378 info[1] = 0;
22379 }
22380}
22381
22382function qpgen2(dmat, dvec, fddmat, n, sol, crval, amat,
22383 bvec, fdamat, q, meq, iact, nact, iter, work, ierr) {
22384
22385 var i, j, l, l1, info, it1, iwzv, iwrv, iwrm, iwsv, iwuv, nvl, r, iwnbv,
22386 temp, sum, t1, tt, gc, gs, nu,
22387 t1inf, t2min,
22388 vsmall, tmpa, tmpb,
22389 go;
22390
22391 r = Math.min(n, q);
22392 l = 2 * n + (r * (r + 5)) / 2 + 2 * q + 1;
22393
22394 vsmall = 1.0e-60;
22395 do {
22396 vsmall = vsmall + vsmall;
22397 tmpa = 1 + 0.1 * vsmall;
22398 tmpb = 1 + 0.2 * vsmall;
22399 } while (tmpa <= 1 || tmpb <= 1);
22400
22401 for (i = 1; i <= n; i = i + 1) {
22402 work[i] = dvec[i];
22403 }
22404 for (i = n + 1; i <= l; i = i + 1) {
22405 work[i] = 0;
22406 }
22407 for (i = 1; i <= q; i = i + 1) {
22408 iact[i] = 0;
22409 }
22410
22411 info = [];
22412
22413 if (ierr[1] === 0) {
22414 dpofa(dmat, fddmat, n, info);
22415 if (info[1] !== 0) {
22416 ierr[1] = 2;
22417 return;
22418 }
22419 dposl(dmat, fddmat, n, dvec);
22420 dpori(dmat, fddmat, n);
22421 } else {
22422 for (j = 1; j <= n; j = j + 1) {
22423 sol[j] = 0;
22424 for (i = 1; i <= j; i = i + 1) {
22425 sol[j] = sol[j] + dmat[i][j] * dvec[i];
22426 }
22427 }
22428 for (j = 1; j <= n; j = j + 1) {
22429 dvec[j] = 0;
22430 for (i = j; i <= n; i = i + 1) {
22431 dvec[j] = dvec[j] + dmat[j][i] * sol[i];
22432 }
22433 }
22434 }
22435
22436 crval[1] = 0;
22437 for (j = 1; j <= n; j = j + 1) {
22438 sol[j] = dvec[j];
22439 crval[1] = crval[1] + work[j] * sol[j];
22440 work[j] = 0;
22441 for (i = j + 1; i <= n; i = i + 1) {
22442 dmat[i][j] = 0;
22443 }
22444 }
22445 crval[1] = -crval[1] / 2;
22446 ierr[1] = 0;
22447
22448 iwzv = n;
22449 iwrv = iwzv + n;
22450 iwuv = iwrv + r;
22451 iwrm = iwuv + r + 1;
22452 iwsv = iwrm + (r * (r + 1)) / 2;
22453 iwnbv = iwsv + q;
22454
22455 for (i = 1; i <= q; i = i + 1) {
22456 sum = 0;
22457 for (j = 1; j <= n; j = j + 1) {
22458 sum = sum + amat[j][i] * amat[j][i];
22459 }
22460 work[iwnbv + i] = Math.sqrt(sum);
22461 }
22462 nact = 0;
22463 iter[1] = 0;
22464 iter[2] = 0;
22465
22466 function fn_goto_50() {
22467 iter[1] = iter[1] + 1;
22468
22469 l = iwsv;
22470 for (i = 1; i <= q; i = i + 1) {
22471 l = l + 1;
22472 sum = -bvec[i];
22473 for (j = 1; j <= n; j = j + 1) {
22474 sum = sum + amat[j][i] * sol[j];
22475 }
22476 if (Math.abs(sum) < vsmall) {
22477 sum = 0;
22478 }
22479 if (i > meq) {
22480 work[l] = sum;
22481 } else {
22482 work[l] = -Math.abs(sum);
22483 if (sum > 0) {
22484 for (j = 1; j <= n; j = j + 1) {
22485 amat[j][i] = -amat[j][i];
22486 }
22487 bvec[i] = -bvec[i];
22488 }
22489 }
22490 }
22491
22492 for (i = 1; i <= nact; i = i + 1) {
22493 work[iwsv + iact[i]] = 0;
22494 }
22495
22496 nvl = 0;
22497 temp = 0;
22498 for (i = 1; i <= q; i = i + 1) {
22499 if (work[iwsv + i] < temp * work[iwnbv + i]) {
22500 nvl = i;
22501 temp = work[iwsv + i] / work[iwnbv + i];
22502 }
22503 }
22504 if (nvl === 0) {
22505 return 999;
22506 }
22507
22508 return 0;
22509 }
22510
22511 function fn_goto_55() {
22512 for (i = 1; i <= n; i = i + 1) {
22513 sum = 0;
22514 for (j = 1; j <= n; j = j + 1) {
22515 sum = sum + dmat[j][i] * amat[j][nvl];
22516 }
22517 work[i] = sum;
22518 }
22519
22520 l1 = iwzv;
22521 for (i = 1; i <= n; i = i + 1) {
22522 work[l1 + i] = 0;
22523 }
22524 for (j = nact + 1; j <= n; j = j + 1) {
22525 for (i = 1; i <= n; i = i + 1) {
22526 work[l1 + i] = work[l1 + i] + dmat[i][j] * work[j];
22527 }
22528 }
22529
22530 t1inf = true;
22531 for (i = nact; i >= 1; i = i - 1) {
22532 sum = work[i];
22533 l = iwrm + (i * (i + 3)) / 2;
22534 l1 = l - i;
22535 for (j = i + 1; j <= nact; j = j + 1) {
22536 sum = sum - work[l] * work[iwrv + j];
22537 l = l + j;
22538 }
22539 sum = sum / work[l1];
22540 work[iwrv + i] = sum;
22541 if (iact[i] < meq) {
22542 // continue;
22543 break;
22544 }
22545 if (sum < 0) {
22546 // continue;
22547 break;
22548 }
22549 t1inf = false;
22550 it1 = i;
22551 }
22552
22553 if (!t1inf) {
22554 t1 = work[iwuv + it1] / work[iwrv + it1];
22555 for (i = 1; i <= nact; i = i + 1) {
22556 if (iact[i] < meq) {
22557 // continue;
22558 break;
22559 }
22560 if (work[iwrv + i] < 0) {
22561 // continue;
22562 break;
22563 }
22564 temp = work[iwuv + i] / work[iwrv + i];
22565 if (temp < t1) {
22566 t1 = temp;
22567 it1 = i;
22568 }
22569 }
22570 }
22571
22572 sum = 0;
22573 for (i = iwzv + 1; i <= iwzv + n; i = i + 1) {
22574 sum = sum + work[i] * work[i];
22575 }
22576 if (Math.abs(sum) <= vsmall) {
22577 if (t1inf) {
22578 ierr[1] = 1;
22579 // GOTO 999
22580 return 999;
22581 } else {
22582 for (i = 1; i <= nact; i = i + 1) {
22583 work[iwuv + i] = work[iwuv + i] - t1 * work[iwrv + i];
22584 }
22585 work[iwuv + nact + 1] = work[iwuv + nact + 1] + t1;
22586 // GOTO 700
22587 return 700;
22588 }
22589 } else {
22590 sum = 0;
22591 for (i = 1; i <= n; i = i + 1) {
22592 sum = sum + work[iwzv + i] * amat[i][nvl];
22593 }
22594 tt = -work[iwsv + nvl] / sum;
22595 t2min = true;
22596 if (!t1inf) {
22597 if (t1 < tt) {
22598 tt = t1;
22599 t2min = false;
22600 }
22601 }
22602
22603 for (i = 1; i <= n; i = i + 1) {
22604 sol[i] = sol[i] + tt * work[iwzv + i];
22605 if (Math.abs(sol[i]) < vsmall) {
22606 sol[i] = 0;
22607 }
22608 }
22609
22610 crval[1] = crval[1] + tt * sum * (tt / 2 + work[iwuv + nact + 1]);
22611 for (i = 1; i <= nact; i = i + 1) {
22612 work[iwuv + i] = work[iwuv + i] - tt * work[iwrv + i];
22613 }
22614 work[iwuv + nact + 1] = work[iwuv + nact + 1] + tt;
22615
22616 if (t2min) {
22617 nact = nact + 1;
22618 iact[nact] = nvl;
22619
22620 l = iwrm + ((nact - 1) * nact) / 2 + 1;
22621 for (i = 1; i <= nact - 1; i = i + 1) {
22622 work[l] = work[i];
22623 l = l + 1;
22624 }
22625
22626 if (nact === n) {
22627 work[l] = work[n];
22628 } else {
22629 for (i = n; i >= nact + 1; i = i - 1) {
22630 if (work[i] === 0) {
22631 // continue;
22632 break;
22633 }
22634 gc = Math.max(Math.abs(work[i - 1]), Math.abs(work[i]));
22635 gs = Math.min(Math.abs(work[i - 1]), Math.abs(work[i]));
22636 if (work[i - 1] >= 0) {
22637 temp = Math.abs(gc * Math.sqrt(1 + gs * gs / (gc * gc)));
22638 } else {
22639 temp = -Math.abs(gc * Math.sqrt(1 + gs * gs / (gc * gc)));
22640 }
22641 gc = work[i - 1] / temp;
22642 gs = work[i] / temp;
22643
22644 if (gc === 1) {
22645 // continue;
22646 break;
22647 }
22648 if (gc === 0) {
22649 work[i - 1] = gs * temp;
22650 for (j = 1; j <= n; j = j + 1) {
22651 temp = dmat[j][i - 1];
22652 dmat[j][i - 1] = dmat[j][i];
22653 dmat[j][i] = temp;
22654 }
22655 } else {
22656 work[i - 1] = temp;
22657 nu = gs / (1 + gc);
22658 for (j = 1; j <= n; j = j + 1) {
22659 temp = gc * dmat[j][i - 1] + gs * dmat[j][i];
22660 dmat[j][i] = nu * (dmat[j][i - 1] + temp) - dmat[j][i];
22661 dmat[j][i - 1] = temp;
22662
22663 }
22664 }
22665 }
22666 work[l] = work[nact];
22667 }
22668 } else {
22669 sum = -bvec[nvl];
22670 for (j = 1; j <= n; j = j + 1) {
22671 sum = sum + sol[j] * amat[j][nvl];
22672 }
22673 if (nvl > meq) {
22674 work[iwsv + nvl] = sum;
22675 } else {
22676 work[iwsv + nvl] = -Math.abs(sum);
22677 if (sum > 0) {
22678 for (j = 1; j <= n; j = j + 1) {
22679 amat[j][nvl] = -amat[j][nvl];
22680 }
22681 bvec[nvl] = -bvec[nvl];
22682 }
22683 }
22684 // GOTO 700
22685 return 700;
22686 }
22687 }
22688
22689 return 0;
22690 }
22691
22692 function fn_goto_797() {
22693 l = iwrm + (it1 * (it1 + 1)) / 2 + 1;
22694 l1 = l + it1;
22695 if (work[l1] === 0) {
22696 // GOTO 798
22697 return 798;
22698 }
22699 gc = Math.max(Math.abs(work[l1 - 1]), Math.abs(work[l1]));
22700 gs = Math.min(Math.abs(work[l1 - 1]), Math.abs(work[l1]));
22701 if (work[l1 - 1] >= 0) {
22702 temp = Math.abs(gc * Math.sqrt(1 + gs * gs / (gc * gc)));
22703 } else {
22704 temp = -Math.abs(gc * Math.sqrt(1 + gs * gs / (gc * gc)));
22705 }
22706 gc = work[l1 - 1] / temp;
22707 gs = work[l1] / temp;
22708
22709 if (gc === 1) {
22710 // GOTO 798
22711 return 798;
22712 }
22713 if (gc === 0) {
22714 for (i = it1 + 1; i <= nact; i = i + 1) {
22715 temp = work[l1 - 1];
22716 work[l1 - 1] = work[l1];
22717 work[l1] = temp;
22718 l1 = l1 + i;
22719 }
22720 for (i = 1; i <= n; i = i + 1) {
22721 temp = dmat[i][it1];
22722 dmat[i][it1] = dmat[i][it1 + 1];
22723 dmat[i][it1 + 1] = temp;
22724 }
22725 } else {
22726 nu = gs / (1 + gc);
22727 for (i = it1 + 1; i <= nact; i = i + 1) {
22728 temp = gc * work[l1 - 1] + gs * work[l1];
22729 work[l1] = nu * (work[l1 - 1] + temp) - work[l1];
22730 work[l1 - 1] = temp;
22731 l1 = l1 + i;
22732 }
22733 for (i = 1; i <= n; i = i + 1) {
22734 temp = gc * dmat[i][it1] + gs * dmat[i][it1 + 1];
22735 dmat[i][it1 + 1] = nu * (dmat[i][it1] + temp) - dmat[i][it1 + 1];
22736 dmat[i][it1] = temp;
22737 }
22738 }
22739
22740 return 0;
22741 }
22742
22743 function fn_goto_798() {
22744 l1 = l - it1;
22745 for (i = 1; i <= it1; i = i + 1) {
22746 work[l1] = work[l];
22747 l = l + 1;
22748 l1 = l1 + 1;
22749 }
22750
22751 work[iwuv + it1] = work[iwuv + it1 + 1];
22752 iact[it1] = iact[it1 + 1];
22753 it1 = it1 + 1;
22754 if (it1 < nact) {
22755 // GOTO 797
22756 return 797;
22757 }
22758
22759 return 0;
22760 }
22761
22762 function fn_goto_799() {
22763 work[iwuv + nact] = work[iwuv + nact + 1];
22764 work[iwuv + nact + 1] = 0;
22765 iact[nact] = 0;
22766 nact = nact - 1;
22767 iter[2] = iter[2] + 1;
22768
22769 return 0;
22770 }
22771
22772 go = 0;
22773 while (true) {
22774 go = fn_goto_50();
22775 if (go === 999) {
22776 return;
22777 }
22778 while (true) {
22779 go = fn_goto_55();
22780 if (go === 0) {
22781 break;
22782 }
22783 if (go === 999) {
22784 return;
22785 }
22786 if (go === 700) {
22787 if (it1 === nact) {
22788 fn_goto_799();
22789 } else {
22790 while (true) {
22791 fn_goto_797();
22792 go = fn_goto_798();
22793 if (go !== 797) {
22794 break;
22795 }
22796 }
22797 fn_goto_799();
22798 }
22799 }
22800 }
22801 }
22802
22803}
22804
22805function solveQP(Dmat, dvec, Amat, bvec, meq, factorized) {
22806 Dmat = base0to1(Dmat);
22807 dvec = base0to1(dvec);
22808 Amat = base0to1(Amat);
22809 var i, n, q,
22810 nact, r,
22811 crval = [], iact = [], sol = [], work = [], iter = [],
22812 message;
22813
22814 meq = meq || 0;
22815 factorized = factorized ? base0to1(factorized) : [undefined, 0];
22816 bvec = bvec ? base0to1(bvec) : [];
22817
22818 // In Fortran the array index starts from 1
22819 n = Dmat.length - 1;
22820 q = Amat[1].length - 1;
22821
22822 if (!bvec) {
22823 for (i = 1; i <= q; i = i + 1) {
22824 bvec[i] = 0;
22825 }
22826 }
22827 for (i = 1; i <= q; i = i + 1) {
22828 iact[i] = 0;
22829 }
22830 nact = 0;
22831 r = Math.min(n, q);
22832 for (i = 1; i <= n; i = i + 1) {
22833 sol[i] = 0;
22834 }
22835 crval[1] = 0;
22836 for (i = 1; i <= (2 * n + (r * (r + 5)) / 2 + 2 * q + 1); i = i + 1) {
22837 work[i] = 0;
22838 }
22839 for (i = 1; i <= 2; i = i + 1) {
22840 iter[i] = 0;
22841 }
22842
22843 qpgen2(Dmat, dvec, n, n, sol, crval, Amat,
22844 bvec, n, q, meq, iact, nact, iter, work, factorized);
22845
22846 message = "";
22847 if (factorized[1] === 1) {
22848 message = "constraints are inconsistent, no solution!";
22849 }
22850 if (factorized[1] === 2) {
22851 message = "matrix D in quadratic function is not positive definite!";
22852 }
22853
22854 return {
22855 solution: base1to0(sol),
22856 value: base1to0(crval),
22857 unconstrained_solution: base1to0(dvec),
22858 iterations: base1to0(iter),
22859 iact: base1to0(iact),
22860 message: message
22861 };
22862}
22863exports.solveQP = solveQP;
22864}(numeric));
22865/*
22866Shanti Rao sent me this routine by private email. I had to modify it
22867slightly to work on Arrays instead of using a Matrix object.
22868It is apparently translated from http://stitchpanorama.sourceforge.net/Python/svd.py
22869*/
22870
22871numeric.svd= function svd(A) {
22872 var temp;
22873//Compute the thin SVD from G. H. Golub and C. Reinsch, Numer. Math. 14, 403-420 (1970)
22874 var prec= numeric.epsilon; //Math.pow(2,-52) // assumes double prec
22875 var tolerance= 1.e-64/prec;
22876 var itmax= 50;
22877 var c=0;
22878 var i=0;
22879 var j=0;
22880 var k=0;
22881 var l=0;
22882
22883 var u= numeric.clone(A);
22884 var m= u.length;
22885
22886 var n= u[0].length;
22887
22888 if (m < n) throw "Need more rows than columns"
22889
22890 var e = new Array(n);
22891 var q = new Array(n);
22892 for (i=0; i<n; i++) e[i] = q[i] = 0.0;
22893 var v = numeric.rep([n,n],0);
22894// v.zero();
22895
22896 function pythag(a,b)
22897 {
22898 a = Math.abs(a)
22899 b = Math.abs(b)
22900 if (a > b)
22901 return a*Math.sqrt(1.0+(b*b/a/a))
22902 else if (b == 0.0)
22903 return a
22904 return b*Math.sqrt(1.0+(a*a/b/b))
22905 }
22906
22907 //Householder's reduction to bidiagonal form
22908
22909 var f= 0.0;
22910 var g= 0.0;
22911 var h= 0.0;
22912 var x= 0.0;
22913 var y= 0.0;
22914 var z= 0.0;
22915 var s= 0.0;
22916
22917 for (i=0; i < n; i++)
22918 {
22919 e[i]= g;
22920 s= 0.0;
22921 l= i+1;
22922 for (j=i; j < m; j++)
22923 s += (u[j][i]*u[j][i]);
22924 if (s <= tolerance)
22925 g= 0.0;
22926 else
22927 {
22928 f= u[i][i];
22929 g= Math.sqrt(s);
22930 if (f >= 0.0) g= -g;
22931 h= f*g-s
22932 u[i][i]=f-g;
22933 for (j=l; j < n; j++)
22934 {
22935 s= 0.0
22936 for (k=i; k < m; k++)
22937 s += u[k][i]*u[k][j]
22938 f= s/h
22939 for (k=i; k < m; k++)
22940 u[k][j]+=f*u[k][i]
22941 }
22942 }
22943 q[i]= g
22944 s= 0.0
22945 for (j=l; j < n; j++)
22946 s= s + u[i][j]*u[i][j]
22947 if (s <= tolerance)
22948 g= 0.0
22949 else
22950 {
22951 f= u[i][i+1]
22952 g= Math.sqrt(s)
22953 if (f >= 0.0) g= -g
22954 h= f*g - s
22955 u[i][i+1] = f-g;
22956 for (j=l; j < n; j++) e[j]= u[i][j]/h
22957 for (j=l; j < m; j++)
22958 {
22959 s=0.0
22960 for (k=l; k < n; k++)
22961 s += (u[j][k]*u[i][k])
22962 for (k=l; k < n; k++)
22963 u[j][k]+=s*e[k]
22964 }
22965 }
22966 y= Math.abs(q[i])+Math.abs(e[i])
22967 if (y>x)
22968 x=y
22969 }
22970
22971 // accumulation of right hand gtransformations
22972 for (i=n-1; i != -1; i+= -1)
22973 {
22974 if (g != 0.0)
22975 {
22976 h= g*u[i][i+1]
22977 for (j=l; j < n; j++)
22978 v[j][i]=u[i][j]/h
22979 for (j=l; j < n; j++)
22980 {
22981 s=0.0
22982 for (k=l; k < n; k++)
22983 s += u[i][k]*v[k][j]
22984 for (k=l; k < n; k++)
22985 v[k][j]+=(s*v[k][i])
22986 }
22987 }
22988 for (j=l; j < n; j++)
22989 {
22990 v[i][j] = 0;
22991 v[j][i] = 0;
22992 }
22993 v[i][i] = 1;
22994 g= e[i]
22995 l= i
22996 }
22997
22998 // accumulation of left hand transformations
22999 for (i=n-1; i != -1; i+= -1)
23000 {
23001 l= i+1
23002 g= q[i]
23003 for (j=l; j < n; j++)
23004 u[i][j] = 0;
23005 if (g != 0.0)
23006 {
23007 h= u[i][i]*g
23008 for (j=l; j < n; j++)
23009 {
23010 s=0.0
23011 for (k=l; k < m; k++) s += u[k][i]*u[k][j];
23012 f= s/h
23013 for (k=i; k < m; k++) u[k][j]+=f*u[k][i];
23014 }
23015 for (j=i; j < m; j++) u[j][i] = u[j][i]/g;
23016 }
23017 else
23018 for (j=i; j < m; j++) u[j][i] = 0;
23019 u[i][i] += 1;
23020 }
23021
23022 // diagonalization of the bidiagonal form
23023 prec= prec*x
23024 for (k=n-1; k != -1; k+= -1)
23025 {
23026 for (var iteration=0; iteration < itmax; iteration++)
23027 { // test f splitting
23028 var test_convergence = false
23029 for (l=k; l != -1; l+= -1)
23030 {
23031 if (Math.abs(e[l]) <= prec)
23032 { test_convergence= true
23033 break
23034 }
23035 if (Math.abs(q[l-1]) <= prec)
23036 break
23037 }
23038 if (!test_convergence)
23039 { // cancellation of e[l] if l>0
23040 c= 0.0
23041 s= 1.0
23042 var l1= l-1
23043 for (i =l; i<k+1; i++)
23044 {
23045 f= s*e[i]
23046 e[i]= c*e[i]
23047 if (Math.abs(f) <= prec)
23048 break
23049 g= q[i]
23050 h= pythag(f,g)
23051 q[i]= h
23052 c= g/h
23053 s= -f/h
23054 for (j=0; j < m; j++)
23055 {
23056 y= u[j][l1]
23057 z= u[j][i]
23058 u[j][l1] = y*c+(z*s)
23059 u[j][i] = -y*s+(z*c)
23060 }
23061 }
23062 }
23063 // test f convergence
23064 z= q[k]
23065 if (l== k)
23066 { //convergence
23067 if (z<0.0)
23068 { //q[k] is made non-negative
23069 q[k]= -z
23070 for (j=0; j < n; j++)
23071 v[j][k] = -v[j][k]
23072 }
23073 break //break out of iteration loop and move on to next k value
23074 }
23075 if (iteration >= itmax-1)
23076 throw 'Error: no convergence.'
23077 // shift from bottom 2x2 minor
23078 x= q[l]
23079 y= q[k-1]
23080 g= e[k-1]
23081 h= e[k]
23082 f= ((y-z)*(y+z)+(g-h)*(g+h))/(2.0*h*y)
23083 g= pythag(f,1.0)
23084 if (f < 0.0)
23085 f= ((x-z)*(x+z)+h*(y/(f-g)-h))/x
23086 else
23087 f= ((x-z)*(x+z)+h*(y/(f+g)-h))/x
23088 // next QR transformation
23089 c= 1.0
23090 s= 1.0
23091 for (i=l+1; i< k+1; i++)
23092 {
23093 g= e[i]
23094 y= q[i]
23095 h= s*g
23096 g= c*g
23097 z= pythag(f,h)
23098 e[i-1]= z
23099 c= f/z
23100 s= h/z
23101 f= x*c+g*s
23102 g= -x*s+g*c
23103 h= y*s
23104 y= y*c
23105 for (j=0; j < n; j++)
23106 {
23107 x= v[j][i-1]
23108 z= v[j][i]
23109 v[j][i-1] = x*c+z*s
23110 v[j][i] = -x*s+z*c
23111 }
23112 z= pythag(f,h)
23113 q[i-1]= z
23114 c= f/z
23115 s= h/z
23116 f= c*g+s*y
23117 x= -s*g+c*y
23118 for (j=0; j < m; j++)
23119 {
23120 y= u[j][i-1]
23121 z= u[j][i]
23122 u[j][i-1] = y*c+z*s
23123 u[j][i] = -y*s+z*c
23124 }
23125 }
23126 e[l]= 0.0
23127 e[k]= f
23128 q[k]= x
23129 }
23130 }
23131
23132 //vt= transpose(v)
23133 //return (u,q,vt)
23134 for (i=0;i<q.length; i++)
23135 if (q[i] < prec) q[i] = 0
23136
23137 //sort eigenvalues
23138 for (i=0; i< n; i++)
23139 {
23140 //writeln(q)
23141 for (j=i-1; j >= 0; j--)
23142 {
23143 if (q[j] < q[i])
23144 {
23145 // writeln(i,'-',j)
23146 c = q[j]
23147 q[j] = q[i]
23148 q[i] = c
23149 for(k=0;k<u.length;k++) { temp = u[k][i]; u[k][i] = u[k][j]; u[k][j] = temp; }
23150 for(k=0;k<v.length;k++) { temp = v[k][i]; v[k][i] = v[k][j]; v[k][j] = temp; }
23151// u.swapCols(i,j)
23152// v.swapCols(i,j)
23153 i = j
23154 }
23155 }
23156 }
23157
23158 return {U:u,S:q,V:v}
23159};
23160
23161
23162}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
23163},{}],4:[function(require,module,exports){
23164var _ = require("lodash");
23165var J = require("jStat").jStat;
23166var M = require("numeric");
23167R = _;
23168R.M = M;
23169R.J = J;
23170
23171function _def(pair) {
23172 _.mixin(pair, {chain:false});
23173}
23174
23175function _mix(pair) {
23176 _.mixin(pair, {chain:true});
23177}
23178
23179var calls=function() {
23180 var args = Array.prototype.slice.call(arguments);
23181 var n = args[0];
23182 var f = args[1];
23183 var params = args.slice(2, args.length);
23184 var a=[];
23185 for (var i=0; i<n; i++)
23186 a.push(f.apply(null, params));
23187 return _.map(a);
23188}
23189
23190_mix({calls:calls});
23191
23192var fx = function() {
23193 var args = Array.prototype.slice.call(arguments);
23194 var f = args[0];
23195 var fargs = args.slice(1, arguments.length);
23196 return function(x) {
23197 return f.apply(null, [x].concat(fargs));
23198 };
23199}
23200
23201_mix({fx:fx});
23202
23203var samples=function(space, size, arg) {
23204 var arg = _.defaults(arg, {replace:true});
23205 if (arg.replace)
23206 return R.calls(size, function() { return _.sample(space); });
23207 else
23208 return _.sampleSize(space, size);
23209}
23210
23211_mix({samples:samples});
23212
23213var steps=function(start, end, step) {
23214 step = step || 1;
23215 return _.range(start, end+0.00001*step, step);
23216}
23217
23218_mix({steps:steps});
23219
23220// ============== format ==================
23221R.setPrecision=function(n) {
23222 R.precision = n;
23223 R.M.precision = n;
23224}
23225
23226R.setPrecision(2);
23227
23228// R.largeArray = 50;
23229
23230R.num2str=function(x) {
23231 if (isNaN(x))
23232 return "NaN";
23233 else if (Math.floor(x) === x) // 整數
23234 return x.toString();
23235 else if (isFinite(x)) { // 有小數點
23236// return x.toFixed(R.precision);
23237 return _.round(x, R.precision).toString();
23238 } else if (x < 0)
23239 return "-Infinity";
23240 else
23241 return "Infinity";
23242}
23243
23244R.ctrim=function(s, set, side) {
23245 side = side||"both";
23246 for (var b=0; b<s.length; b++)
23247 if (set.indexOf(s[b])<0) break;
23248 for (var e=s.length-1; e>=0; e--)
23249 if (set.indexOf(s[e])<0) break;
23250 if (side === "right") b=0;
23251 if (side === "left") e=s.length-1;
23252 return s.substring(b, e+1);
23253}
23254
23255R.array2str=function(x) {
23256 var s = "";
23257 for (var i in x)
23258 s+= R.str(x[i])+", ";
23259 return "["+R.ctrim(s, ", ")+"]";
23260}
23261
23262R.obj2str=function(x, sp) {
23263 var s = "";
23264 for (var k in x)
23265 s+= k+":"+R.str(x[k])+sp;
23266 return "{"+R.ctrim(s,sp)+"}";
23267}
23268
23269var str = function(x) {
23270 if (typeof x === 'undefined') return 'undefined';
23271 else if (x === null) return 'null';
23272 else if (typeof x === "number") return R.num2str(x);
23273 else if(typeof x === "string") return '\"'+x.toString()+'\"';
23274 else if (x instanceof Array) return R.array2str(x);
23275// else if (typeof x === "object") return R.obj2str(x, ",");
23276 else if (typeof x === "object") return x.toString();
23277 else if (typeof x === "function") return "";
23278 else return x.toString();
23279}
23280
23281// Number.prototype.str = function() { return R.num2str(this); }
23282Array.prototype.str = function() { return R.array2str(this); }
23283// Array.prototype.str = function() { return M.str(this); }
23284
23285var _str = function(x) { return str(x); }
23286
23287_def({str:_str});
23288
23289// ============== /format ==================
23290
23291// 標準差
23292_def({sd:function(a, flag) { return J.stdev(a, flag || 1); }});
23293// 協方差
23294_def({cov:function(x, y) { return J.stdev(x, y); }});
23295// 相關係數
23296_def({cor:function(x, y) { return J.corrcoeff(x, y); }});
23297// 階層 n!
23298_def({factorial : function(n) { return J.factorial(n); }});
23299// log(n!)
23300_def({lfactorial : function(n) { return J.factorialln(n); }});
23301// 組合 C(n,m)
23302_def({choose : function(n,m) { return J.combination(n, m); }});
23303// log C(n,m)
23304_def({lchoose : function(n,m) { return J.combinationln(n, m); }});
23305// 組合 C(n,m)
23306_def({permutation : function(n,m) { return J.permutation(n, m); }});
23307// log C(n,m)
23308_def({lchoose : function(n,m) { return J.combinationln(n, m); }});
23309
23310// 均等分布
23311_mix({runif:function(n, a, b) { return R.calls(n, J.uniform.sample, a, b); }});
23312_def({dunif:function(x, a, b) { return J.uniform.pdf(x, a, b); }});
23313_def({punif:function(q, a, b) { return J.uniform.cdf(q, a, b); }});
23314_def({qunif:function(p, a, b) { return J.uniform.inv(p, a, b); }});
23315// 常態分布
23316_mix({rnorm:function(n, mean, sd) { return R.calls(n, J.normal.sample, mean, sd); }});
23317_def({dnorm:function(x, mean, sd) { return J.normal.pdf(x, mean, sd); }});
23318_def({pnorm:function(q, mean, sd) { return J.normal.cdf(q, mean, sd); }});
23319_def({qnorm:function(p, mean, sd) { return J.normal.inv(p, mean, sd); }});
23320// 布瓦松分布
23321_mix({rpois:function(n, l) { return R.calls(n, J.poisson.sample, l); }});
23322_def({dpois:function(x, l) { return J.poisson.pdf(x, l); }});
23323_def({ppois:function(q, l) { return J.poisson.cdf(q, l); }});
23324_def({qpois:function(p, l) { return J.poisson.inv(p, l); }});
23325// F 分布
23326_mix({rf:function(n, df1, df2) { return R.calls(n, J.centralF.sample, df1, df2); }});
23327_def({df:function(x, df1, df2) { return J.centralF.pdf(x, df1, df2); }});
23328_def({pf:function(q, df1, df2) { return J.centralF.cdf(q, df1, df2); }});
23329_def({qf:function(p, df1, df2) { return J.centralF.inv(p, df1, df2); }});
23330// T 分布
23331_mix({rt:function(n, dof) { return R.calls(n, J.studentt.sample, dof); }});
23332_def({dt:function(x, dof) { return J.studentt.pdf(x, dof); }});
23333_def({pt:function(q, dof) { return J.studentt.cdf(q, dof); }});
23334_def({qt:function(p, dof) { return J.studentt.inv(p, dof); }});
23335// Beta 分布
23336_mix({rbeta:function(n, alpha, beta) { return R.calls(n, J.beta.sample, alpha, beta); }});
23337_def({dbeta:function(x, alpha, beta) { return J.beta.pdf(x, alpha, beta); }});
23338_def({pbeta:function(q, alpha, beta) { return J.beta.cdf(q, alpha, beta); }});
23339_def({qbeta:function(p, alpha, beta) { return J.beta.inv(p, alpha, beta); }});
23340// 柯西分布
23341_mix({rcauchy:function(n, local, scale) { return R.calls(n, J.cauchy.sample, local, scale); }});
23342_def({dcauchy:function(x, local, scale) { return J.cauchy.pdf(x, local, scale); }});
23343_def({pcauchy:function(q, local, scale) { return J.cauchy.cdf(q, local, scale); }});
23344_def({qcauchy:function(p, local, scale) { return J.cauchy.inv(p, local, scale); }});
23345// chisquare 分布
23346_mix({rchisq:function(n, dof) { return R.calls(n, J.chisquare.sample, dof); }});
23347_def({dchisq:function(x, dof) { return J.chisquare.pdf(x, dof); }});
23348_def({pchisq:function(q, dof) { return J.chisquare.cdf(q, dof); }});
23349_def({qchisq:function(p, dof) { return J.chisquare.inv(p, dof); }});
23350// 指數分布
23351_mix({rexp:function(n, rate) { return R.calls(n, J.exponential.sample, rate); }});
23352_def({dexp:function(x, rate) { return J.exponential.pdf(x, rate); }});
23353_def({pexp:function(q, rate) { return J.exponential.cdf(q, rate); }});
23354_def({qexp:function(p, rate) { return J.exponential.inv(p, rate); }});
23355// Gamma 分布
23356_mix({rgamma:function(n, shape, scale) { return R.calls(n, J.gamma.sample, shape, scale); }});
23357_def({dgamma:function(x, shape, scale) { return J.gamma.pdf(x, shape, scale); }});
23358_def({pgamma:function(q, shape, scale) { return J.gamma.cdf(q, shape, scale); }});
23359_def({qgamma:function(p, shape, scale) { return J.gamma.inv(p, shape, scale); }});
23360// 反 Gamma 分布
23361_mix({rinvgamma:function(n, shape, scale) { return R.calls(n, J.invgamma.sample, shape, scale); }});
23362_def({dinvgamma:function(x, shape, scale) { return J.invgamma.pdf(x, shape, scale); }});
23363_def({pinvgamma:function(q, shape, scale) { return J.invgamma.cdf(q, shape, scale); }});
23364_def({qinvgamma:function(p, shape, scale) { return J.invgamma.inv(p, shape, scale); }});
23365// 對數常態分布
23366_mix({rlognormal:function(n, mu, sigma) { return R.calls(n, J.lognormal.sample, mu, sigma); }});
23367_def({dlognormal:function(x, mu, sigma) { return J.lognormal.pdf(x, mu, sigma); }});
23368_def({plognormal:function(q, mu, sigma) { return J.lognormal.cdf(q, mu, sigma); }});
23369_def({qlognormal:function(p, mu, sigma) { return J.lognormal.inv(p, mu, sigma); }});
23370// Pareto 分布
23371_mix({rpareto:function(n, scale, shape) { return R.calls(n, J.pareto.sample, scale, shape); }});
23372_def({dpareto:function(x, scale, shape) { return J.pareto.pdf(x, scale, shape); }});
23373_def({ppareto:function(q, scale, shape) { return J.pareto.cdf(q, scale, shape); }});
23374_def({qpareto:function(p, scale, shape) { return J.pareto.inv(p, scale, shape); }});
23375// Weibull 分布
23376_mix({rweibull:function(n, scale, shape) { return R.calls(n, J.weibull.sample, scale, shape); }});
23377_def({dweibull:function(x, scale, shape) { return J.weibull.pdf(x, scale, shape); }});
23378_def({pweibull:function(q, scale, shape) { return J.weibull.cdf(q, scale, shape); }});
23379_def({qweibull:function(p, scale, shape) { return J.weibull.inv(p, scale, shape); }});
23380// 三角分布
23381_mix({rtriangular:function(n, a, b, c) { return R.calls(n, J.triangular.sample, a, b, c); }});
23382_def({dtriangular:function(x, a, b, c) { return J.triangular.pdf(x, a, b, c); }});
23383_def({ptriangular:function(q, a, b, c) { return J.triangular.cdf(q, a, b, c); }});
23384_def({qtriangular:function(p, a, b, c) { return J.triangular.inv(p, a, b, c); }});
23385// 類似 Beta 分布,但計算更簡單
23386_mix({rkumaraswamy:function(n, alpha, beta) { return R.calls(n, J.kumaraswamy.sample, alpha, beta); }});
23387_def({dkumaraswamy:function(x, alpha, beta) { return J.kumaraswamy.pdf(x, alpha, beta); }});
23388_def({pkumaraswamy:function(q, alpha, beta) { return J.kumaraswamy.cdf(q, alpha, beta); }});
23389_def({qkumaraswamy:function(p, alpha, beta) { return J.kumaraswamy.inv(p, alpha, beta); }});
23390
23391// ============= 離散分佈 ============
23392var qf=function(cdf, q, N, p) {
23393 for (var i=0; i<=N; i++) {
23394 if (cdf(i, N, p) > q) return i;
23395 }
23396 return N;
23397}
23398var rf=function(cdf, n, N, p) {
23399 var a = [];
23400 for (var i=0; i<n; i++) {
23401 var q = Math.random();
23402 a.push(cdf(q, N, p));
23403 }
23404 return a;
23405}
23406// 二項分布
23407_def({dbinom:function(x, N, p) { return J.binomial.pdf(x, N, p); }});
23408_def({pbinom:function(k, N, p) { return J.binomial.cdf(k, N, p); }});
23409_def({qbinom:function(q, N, p) { return qf(R.pbinom, q, N, p); }});
23410_mix({rbinom:function(n, N, p) { return rf(R.qbinom, n, N, p); }});
23411// 負二項分布
23412_def({dnbinom:function(x, N, p) { return jStat.negbin.pdf(x, N, p); }});
23413_def({pnbinom:function(k, N, p) { return jStat.negbin.cdf(k, N, p); }});
23414_def({qnbinom:function(q, N, p) { return qf(R.pnbinom, q, N, p); } });
23415_mix({rnbinom:function(n, N, p) { return rf(R.qnbinom, n, N, p); }});
23416// 超幾何分布
23417_def({dhyper:function(x, N, m, n) { return jStat.hypgeom.pdf(x, N, m, n); }});
23418_def({phyper:function(k, N, m, n) { return jStat.hypgeom.cdf(k, N, m, n); }});
23419_def({qhyper:function(q, N, m, n) { return qf(R.phyper, q, N, p); } });
23420_mix({rhyper:function(n, N, m, k) { return rf(R.qhyper, n, N, p); }});
23421
23422// =============== 檢定 ==============================
23423
23424// ---------------- 統計與檢定 ----------------------
23425function opAlt(op) {
23426 if (op === "=") return "!=";
23427 if (op === "<") return ">=";
23428 if (op === ">") return "<=";
23429 return null;
23430}
23431
23432R.test = function(o) { // name, D, x, mu, sd, y, alpha, op
23433 o = R.defaults(o, {alpha:0.05, op:"="});
23434 var alpha = o.alpha;
23435 var pvalue, interval;
23436 var D = o.D;
23437 var q1 = D.o2q(o); // 單尾檢定的 pvalue
23438
23439 if (o.op === "=") {
23440 if (q1>0.5) q1 = 1-q1; // (q1>0.5) 取右尾,否則取左尾。
23441 pvalue= 2*q1; // 對稱情況:雙尾檢定的 p 值是單尾的兩倍。
23442 interval = [D.q2p(alpha/2, o, "L"), D.q2p(1-alpha/2, o, "R")];
23443 } else {
23444 if (o.op === "<") { // 右尾檢定 H0: q < 1-alpha,
23445 interval = [ D.q2p(alpha, o, "L"), Infinity ];
23446 pvalue = 1-q1;
23447 }
23448 if (o.op === ">") { // 左尾檢定 H0: q > alpha
23449 interval=[-Infinity, D.q2p(1-alpha, o, "R")];
23450 pvalue = q1;
23451 }
23452 }
23453 return {
23454 name: o.name,
23455 h: D.h(o),
23456 alpha: alpha,
23457 op: o.op,
23458 pvalue: pvalue,
23459 ci : interval,
23460 df : D.df(o),
23461 report: function() { R.report(this) }
23462 };
23463}
23464
23465var t1 = { // 單樣本 T 檢定 t = (X-mu)/(S/sqrt(n))
23466 h:function(o) { return "H0:mu"+o.op+o.mu; },
23467 o2q:function(o) {
23468 var x = o.x, n = x.length;
23469 var t = (R.mean(x)-o.mu)/(R.sd(x)/Math.sqrt(n));
23470 return R.pt(t, n-1);
23471 },
23472 // P(X-mu/(S/sqrt(n))<t) = q ; 信賴區間 P(T<q)
23473 // P(mu > X-t*S/sqrt(n)) = q ; 這反而成了右尾檢定,所以左尾與右尾確實會反過來
23474 q2p:function(q, o) {
23475 var x = o.x, n = x.length;
23476 return R.mean(x) + R.qt(q, n-1) * R.sd(x) / Math.sqrt(n);
23477 },
23478 df:function(o) { return o.x.length-1; }
23479}
23480
23481var t2vareq = { // σ1=σ2, 合併 T 檢定 (雙樣本)
23482 h:function(o) { return "H0:mu1"+o.op+"mu2" },
23483 // S^2 = (n1-1)*S1^2+(n2-1)*S2^2)/(n1-1+n2-1)
23484 sd:function(o) {
23485 var x = o.x, n1 = x.length, y=o.y, n2=y.length;
23486 var S1= R.sd(x), S2 = R.sd(y);
23487 var S = Math.sqrt(((n1-1)*S1*S1+(n2-1)*S2*S2)/(n1-1+n2-1));
23488 return S;
23489 },
23490 // T = ((X-Y)-(mu1-mu2))/(sqrt(1/n1+1/n2)*S)
23491 o2q:function(o) {
23492 var x = o.x, n1 = x.length, y=o.y, n2=y.length;
23493 var S = this.sd(o);
23494 var t = (R.mean(x)-R.mean(y)-o.mu)/(Math.sqrt(1/n1+1/n2)*S);
23495 return R.pt(t, n1+n2-2);
23496 },
23497 // t=((X-Y)-mu)/(sqrt(1/n1+1/n2)*S), (X-Y)-t*sqrt(1/n1+1/n2)*S = mu
23498 q2p:function(q, o) {
23499 var x = o.x, n1 = x.length, y=o.y, n2=y.length;
23500 var S = this.sd(o);
23501 return R.mean(x)-R.mean(y)+ R.qt(q, n1+n2-2)*Math.sqrt(1/n1+1/n2)*S;
23502 },
23503 df:function(o) {
23504 var x = o.x, n1 = x.length, y=o.y, n2=y.length;
23505 return n1+n2-2;
23506 }
23507}
23508
23509var t2paired = { // 成對 T 檢定 T = (X-Y-mu)/(S/sqrt(n)) (雙樣本)
23510 h:function(o) { return "H0:mu1"+o.op+"mu2" },
23511 sd:function(o) { // S = sd(x-y)
23512 var x = o.x, n = x.length, y=o.y;
23513 var S= R.sd(R.sub(x,y));
23514 return S;
23515 },
23516 o2q:function(o) {
23517 var x = o.x, n = x.length, y=o.y;
23518 var S = this.sd(o);
23519 var t = (R.mean(R.sub(x,y))-o.mu)/(S/Math.sqrt(n));
23520 return R.pt(t, n-1);
23521 },
23522 // mean(x-y)+t*S/sqrt(n)
23523 q2p:function(q, o) {
23524 var x = o.x, n = x.length, y=o.y;
23525 var S = this.sd(o);
23526 return R.mean(R.sub(x,y))+ R.qt(q, n-1)*S/Math.sqrt(n);
23527 },
23528 df:function(o) {
23529 return o.x.length-1;
23530 }
23531}
23532
23533var t2varneq = { // σ1≠σ2, Welch's t test (雙樣本) (又稱 Smith-Satterwaite 程序)
23534// 參考:http://en.wikipedia.org/wiki/Welch's_t_test
23535 h:function(o) { return "H0:mu1"+o.op+"mu2" },
23536 // T = ((X-Y)-(mu1-mu2))/sqrt(S1^2/n1+S2^2/n2)
23537 o2q:function(o) {
23538 var x = o.x, n1 = x.length, y=o.y, n2=y.length;
23539 var S1 = R.sd(x), S2=R.sd(y);
23540 var t = (R.mean(x)-R.mean(y)-o.mu)/Math.sqrt(S1*S1/n1+S2*S2/n2);
23541 return R.pt(t, this.df(o));
23542 },
23543 // t=((X-Y)-mu)/sqrt(S1^2/n1+S2^2/n2), (X-Y)-t*sqrt(S1^2/n1+S2^2/n2) = mu
23544 q2p:function(q, o) {
23545 var x = o.x, n1 = x.length, y=o.y, n2=y.length;
23546 var S1 = R.sd(x), S2=R.sd(y);
23547 return R.mean(x)-R.mean(y)+ R.qt(q, this.df(o))*Math.sqrt(S1*S1/n1+S2*S2/n2);
23548 },
23549 df:function(o) {
23550 var x = o.x, n1 = x.length, y=o.y, n2=y.length;
23551 var S1 = R.sd(x), S2=R.sd(y);
23552 var Sn1 = S1*S1/n1, Sn2 = S2*S2/n2, Sn12 = Sn1+Sn2;
23553 var df = (Sn12*Sn12)/((Sn1*Sn1)/(n1-1)+(Sn2*Sn2)/(n2-1));
23554 return df;
23555 }
23556}
23557
23558R.ttest = function(o) {
23559 var t;
23560 if (typeof o.y === "undefined") {
23561 o.name = "ttest(X)";
23562 o.D = t1;
23563 t = R.test(o);
23564 t.mean = R.mean(o.x);
23565 t.sd = R.sd(o.x);
23566 } else {
23567 var varequal = R.opt(o, "varequal", false);
23568 var paired = R.opt(o, "paired", false);
23569 if (varequal) {
23570 o.name = "ttest(X,Y,mu="+o.mu+",varequal=true) (pooled)";
23571 o.D = t2vareq;
23572 t = R.test(o);
23573 } else if (paired) {
23574 o.name = "ttest(x,y,mu="+o.mu+",paired=true)";
23575 o.D = t2paired;
23576 t = R.test(o);
23577 t.mean = "mean(x-y)="+R.str(R.mean(R.sub(o.x, o.y)));
23578 t.sd = "sd(x-y)="+R.str(R.sd(R.sub(o.x, o.y)));
23579 } else {
23580 o.name = "ttest(x,y,mu="+o.mu+",varequal=false), Welch t-test";
23581 o.D = t2varneq;
23582 t = R.test(o);
23583 }
23584 if (typeof t.mean === "undefined") {
23585 t.mean = "mean(x)="+R.str(R.mean(o.x))+" mean(y)="+R.str(R.mean(o.y));
23586 t.sd = "sd(x)="+R.str(R.sd(o.x))+" sd(y)="+R.str(R.sd(o.y));
23587 }
23588 }
23589 return t;
23590}
23591
23592var f2 = { // 檢定 σ1/σ2 = 1?
23593 h:function(o) { return "H0:σ1/σ2"+o.op+"1"; },
23594 // F = S1^2/S2^2
23595 o2q:function(o) {
23596 var x = o.x, n1 = x.length, y=o.y, n2=y.length;
23597 var S1 = R.sd(x), S2=R.sd(y);
23598 var f = (S1*S1)/(S2*S2);
23599 var pf = R.pf(f, n1-1, n2-1);
23600 return pf;
23601 },
23602 // 信賴區間公式: S1^2/(S2^2*F(1-α/2), S1^2/(S2^2*F(α/2))
23603 // 也就是要用 S1^2/(S2^2*f(1-q)) ,參考 R 軟體、應用統計方法 (陳景祥) 389 頁。
23604 q2p:function(q, o) {
23605 var x = o.x, n1 = x.length, y=o.y, n2=y.length;
23606 var S1 = R.sd(x), S2=R.sd(y);
23607 var qf = R.qf(1-q, n1-1, n2-1);
23608 return (S1*S1)/(S2*S2*qf);
23609 },
23610 df:function(o) {
23611 var x = o.x, n1 = x.length, y=o.y, n2=y.length;
23612 return [n1-1, n2-1];
23613 }
23614}
23615
23616R.ftest = function(o) {
23617 o.name = "ftest(X, Y)";
23618 o.D = f2;
23619 var t = R.test(o);
23620 var rsd = R.sd(o.x)/R.sd(o.y);
23621 t.ratio = (rsd*rsd);
23622 return t;
23623}
23624
23625// R 軟體沒有此函數,測試請看湯銀才 143 頁
23626var chisq1 = { // 檢定 σ1 = σ ?
23627 h:function(o) { return "H0:σ1"+o.op+"σ"; },
23628 // χ(n-1) = (n-1)S^2/σ^2
23629 o2q:function(o) {
23630 var x = o.x, n = x.length, S=R.sd(x);
23631 var v = (n-1)*S*S/(o.sd*o.sd);
23632 return R.pchisq(v, n-1);
23633 },
23634 // 信賴區間公式: (n-1)S^2/χ^2(1-q),參考 R 語言與統計分析 (湯銀才) 142 頁。
23635 q2p:function(q, o) {
23636 var x = o.x, n = x.length, S=R.sd(x);
23637 return (n-1)*S*S/R.qchisq(1-q, n-1);
23638 },
23639 df:function(o) {
23640 var x = o.x, n = x.length;
23641 return n-1;
23642 }
23643}
23644
23645R.chisqtest = function(o) {
23646 o.name = "chisqtest(X)";
23647 o.D = chisq1;
23648 return R.test(o);
23649}
23650
23651R.vartest = function(o) {
23652 if (typeof o.y === "undefined")
23653 return R.chisqtest(o);
23654 else
23655 return R.ftest(o);
23656}
23657
23658var z1 = { // 單樣本 Z 檢定
23659 h:function(o) { return "H0:mu"+o.op+o.mu+" when sd="+o.sd; },
23660 o2q:function(o) {
23661 var x = o.x, n = x.length;
23662 var z = (R.mean(x)-o.mu)/(o.sd/Math.sqrt(n)); // z=(X-mu)/(sd/sqrt(n))
23663 return R.pnorm(z, 0, 1);
23664 },
23665 q2p:function(q, o) {
23666 var x = o.x, n = x.length;
23667 return R.mean(x) + R.qnorm(q, 0, 1) * R.sd(x) / Math.sqrt(n);
23668 },
23669 df:function(o) { return o.x.length; }
23670}
23671
23672R.ztest = function(o) {
23673 o.name = "ztest(X)";
23674 o.D = z1;
23675 return R.test(o);
23676}
23677
23678var zprop1 = { // 比例的檢定, n 較大時的近似解 o={ x, n, p } // x 為數值,n 個中出現 x 個 1
23679 h:function(o) { return "H0:p"+o.op+o.p; },
23680 // Z = (p1-p)/sqrt(p(1-p)/n)
23681 o2q:function(o) {
23682 var x=o.x, n=o.n, p1=x/n, p=R.def(o.p, p1);
23683 var z = (p1-p)/Math.sqrt(p*(1-p)/n);
23684 return R.pnorm(z, 0, 1);
23685 },
23686 // 信賴區間公式: p1+z*sqrt(p1*(1-p1)/n),參考 R 語言與統計分析 (湯銀才) 149 頁。
23687 q2p:function(q, o) {
23688 var x=o.x, n=o.n, p1=x/n, p=p1;
23689 var z = R.qnorm(q, 0, 1);
23690 var z22n = z*z/(2*n);
23691 return (p1+z22n+z*Math.sqrt( p*(1-p)/n + z22n/(2*n) ))/(1+2*z22n); // R 的版本,比較複雜的估計公式
23692// return p1+z*Math.sqrt(p*(1-p)/n); // 語言與統計分析 (湯銀才) 149 頁的版本。
23693 },
23694 df:function(o) { return 1; }
23695}
23696
23697var zprop2 = { // 比例的檢定, n 較大時的近似解 o={ x, y, n1, n2 }
23698 h:function(o) { return "H0:p1-p2"+o.op+o.p; },
23699 // Z = (p1-p2)/sqrt(p*(1-p)*(1/n1+1/n2)), p = (n1p1+n2p2)/(n1+n2),參考 R 語言與統計分析 (湯銀才) 175 頁。
23700 o2q:function(o) {
23701 var x=o.x, y=o.y, n1=o.n1, n2=o.n2, p1=x/n1, p2=y/n2, p=(n1*p1+n2*p2)/(n1+n2);
23702 var z = (p1-p2)/Math.sqrt(p*(1-p)*(1/n1+1/n2));
23703 return R.pnorm(z, 0, 1);
23704 },
23705 // 信賴區間公式: p1-p2+z*sqrt(p*(1-p)*(1/n1+1/n2));
23706 q2p:function(q, o) {
23707 var x=o.x, y=o.y, n1=o.n1, n2=o.n2, p1=x/n1, p2=y/n2, p=(n1*p1+n2*p2)/(n1+n2);
23708 var z = R.qnorm(q, 0, 1);
23709 return p1-p2+z*Math.sqrt(p*(1-p)*(1/n1+1/n2));
23710 },
23711 df:function(o) { return 1; }
23712}
23713
23714/* 在 prop.test.R 當中,雙邊檢定的 pvalue 是用 pchisq, 單邊才是用 z ,為何呢? ( 但是信賴區間則是全部用 z)
23715 if (alternative == "two.sided")
23716 PVAL <- pchisq(STATISTIC, PARAMETER, lower.tail = FALSE)
23717 else {
23718 if (k == 1)
23719 z <- sign(ESTIMATE - p) * sqrt(STATISTIC)
23720 else
23721 z <- sign(DELTA) * sqrt(STATISTIC)
23722 PVAL <- pnorm(z, lower.tail = (alternative == "less"))
23723 }
23724*/
23725
23726R.proptest = function(o) {
23727 o.p = R.opt(o, "p", 0.5);
23728 o.name = "proptest("+R.str(o)+")";
23729 o.correct = R.opt(o.correct, false);
23730 if (o.correct) {
23731 o.name += ", binomtest";
23732 o.D += binom1;
23733 } else {
23734 if (typeof o.y === "undefined") {
23735 o.name += ", zprop1";
23736 o.D = zprop1;
23737 } else {
23738 o.p = 0; // p1-p2 = 0
23739 o.name += ", zprop2";
23740 o.D = zprop2;
23741 }
23742 }
23743 var t=R.test(o);
23744 if (typeof o.y === "undefined")
23745 t.p = o.x/o.n;
23746 else
23747 t.p = [o.x/o.n1, o.y/o.n2];
23748 return t;
23749}
23750
23751// 參考: https://github.com/SurajGupta/r-source/blob/master/src/library/stats/R/binom.test.R
23752var binom1 = { // 比例的檢定, n 較大時的近似解 o={ x, n, p } // x 為數值,n 個中出現 x 個 1
23753 h:function(o) { return "H0:p"+o.op+o.p; },
23754
23755 // Z = C(n, k)*p1^k*(1-p1)^(n-k), CDF(z: from 1 to x)
23756 o2q:function(o) {
23757 var x=o.x, n=o.n, p = o.p, q;
23758 var dx = R.dbinom(x, n, p);
23759 if (o.op === "=") { // 雙尾檢定,去雙尾後 / 2
23760 var q = 0;
23761 for (var i=0; i<=n; i++) {
23762 var di = R.dbinom(i, n, p);
23763 if (di > dx+1e-5) q += di; // 為何 x 本身不算,如果算應該用 di > dx-1e-5 才對。
23764 }
23765 q=1-((1-q)/2); // 因為 test 會 * 2 所進行的減半調整
23766 } else { // 單尾檢定
23767 if (Math.abs(x - n*p)<1e-5) // 正確預測, q=1
23768 q = 1;
23769 else {
23770 if (o.op === ">")
23771 q = R.pbinom(x, n, p); // 去右尾
23772 else // op=== "<"
23773 q = R.pbinom(x-1, n, p); // 去右尾
23774 }
23775 }
23776 return q;
23777 },
23778/* 注意上述 R 原始碼另一尾的計算方式,是用 < pbinom(最接近 x 者) 的算法,而不是直接 * 2。 問題是我們在 test 中是直接用*2 的方式。
23779 d <- dbinom(x, n, p)
23780 ...
23781 else if (x < m) {
23782 i <- seq.int(from = ceiling(m), to = n)
23783 y <- sum(dbinom(i, n, p) <= d * relErr)
23784 pbinom(x, n, p) 左尾 + pbinom(n - y, n, p, lower.tail = FALSE) 右尾
23785 } else {
23786 i <- seq.int(from = 0, to = floor(m))
23787 y <- sum(dbinom(i, n, p) <= d * relErr)
23788 pbinom(y - 1, n, p) 左尾 + pbinom(x - 1, n, p, lower.tail = FALSE) 右尾
23789 }
23790*/
23791 // 信賴區間公式: P(T>c) = Σ (n, i) C(n, i) p1^i (1-p1)^(n-i) for i>c < q
23792
23793 q2p:function(q, o, side) {
23794 var x=o.x, n=o.n, p=o.p, op=o.op;
23795 if (side === "L")
23796 return qbeta(q, x, n - x + 1); // 這裏採用 qbeta 是 R 的作法; 直覺上應該採用 R.qbinom(q, n, p);
23797 else
23798 return qbeta(q, x + 1, n - x);
23799 },
23800 df:function(o) { return 1; }
23801}
23802
23803R.binomtest = function(o) {
23804 o.p = R.opt(o, "p", 0.5);
23805 o.name = "binomtest("+R.str(o)+")";
23806 o.D = binom1;
23807 var t=R.test(o);
23808 t.p = o.x/o.n;
23809 t.ci[0]=(o.op === ">")?0:t.ci[0];
23810 t.ci[1]=(o.op === "<")?1:t.ci[1];
23811 return t;
23812}
23813
23814R.report = function(o) {
23815 console.log("=========== report ==========");
23816 for (var k in o) {
23817 if (typeof o[k] !== "function")
23818 console.log(k+"\t: "+str(o[k]));
23819 }
23820}
23821
23822// anova f-test : array1, array2, array3, ...
23823R.anovaftest = function() {
23824 return {
23825 h0 : "σ1=σ2=...=σ"+arguments.length,
23826 pvalue: J.anovaftest(),
23827 score: J.anovafscore(),
23828 };
23829}
23830
23831// ========================= MATRIX ===================
23832M.str = M.prettyPrint;
23833
23834module.exports = R;
23835
23836
23837/*
23838R.fx = function() {
23839 var args = Array.prototype.slice.call(arguments);
23840 var f = args[0];
23841 var fargs = args.slice(1, arguments.length);
23842 return function(x) {
23843 return f.apply(null, [x].concat(fargs));
23844 };
23845}
23846
23847*/
23848/*
23849// list(from, from+step, ..., to)
23850R.steps=function(from, to, step) {
23851 step = step || 1;
23852 var a=[];
23853 for (var i=0; from+i*step<=to; i++)
23854 a.push(from+i*step);
23855 return a;
23856}
23857*/
23858
23859/*
23860var calls=function(n,f) {
23861 return _.range(n).map(f);
23862}
23863*/
23864},{"jStat":1,"lodash":2,"numeric":3}],5:[function(require,module,exports){
23865R=require("../rlab");
23866},{"../rlab":4}]},{},[5]);