UNPKG

1.24 MBJavaScriptView 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){
2var O = require("./field");
3
4var acc = {
5 sum:{init:0,op:'+'},
6 product:{init:1,op:'*'},
7 min:{init:Number.MAX_VALUE,op:'min'},
8 max:{init:-Number.MAX_VALUE,op:'max'},
9}
10
11O.vfill=function(size, value) {
12 var v=[];
13 for (var i=0; i<size; i++)
14 v[i] = value;
15 return v;
16}
17
18O.vextend=function(a, size) {
19 var v = a.slice();
20 for (var i=a.length; i<size; i++) {
21 v.push(0);
22 }
23 return v;
24}
25
26O.vdot=function(x,y) {
27 var sum = 0;
28 for (var i=0; i<x.length; i++) {
29 sum = sum.add(x[i].mul(y[i]));
30 }
31 return sum;
32}
33
34O.vop=function(op,x,y) {
35 var c=[],result=(O.isUndefined(acc[op]))?undefined:acc[op].init;
36 if (O.isArray(x)) {
37 for (var i=0; i<x.length; i++) {
38 if (!O.isUndefined(result)) {
39 var xi = x[i];
40 if (O.isArray(x[i])) // x[i] is subArray
41 xi = O.op(op, x[i]);
42 else {
43 if (!O.isUndefined(y))
44 xi = y(x[i]); // y should be a function
45 }
46 result = O.op(acc[op].op, xi, result);
47// if (op==='min') console.log("xi=%d result=%d", xi, result);
48 }
49 else {
50 var yi = O.isArray(y)?y[i]:y;
51 c[i] = O.op(op, x[i], yi);
52 }
53 }
54 } else {
55 throw Error('vop fail:op,x,y=', op, x, y);
56 }
57 if (x.length === c.length)
58 return c;
59 else
60 return result;
61}
62
63O.op = function(op,x,y) {
64 if (O.isField(x)) {
65 if (!O.isUndefined(acc[op])) {
66 switch (op) {
67 case 'max': return Math.max(x,y);
68 case 'min': return Math.min(x,y);
69 default:return x;
70 }
71 } else if (x instanceof O.FieldObj ||
72 (O.isNumber(x) && y instanceof O.FieldObj)) {
73 x = O.Complex.toComplex(x);
74 y = O.isNumber(y)?O.Complex.toComplex(y):y;
75 switch (op) {
76 case 'eval': var exp = y; return exp(x);
77 case 'neg':return x.neg();
78 case 'inv':return x.inv();
79 case 'bnot':return x.bnot();
80 case '+':return x.add(y);
81 case '-':return x.sub(y);
82 case '*':return x.mul(y);
83 case '/':return x.div(y);
84 case 'power':return x.power(y);
85 case 'sqrt':return x.sqrt();
86 case 'eq':return x.eq(y);
87 case 'neq':return x.neq(y);
88 case 'geq':return x.geq(y);
89 case 'leq':return x.leq(y);
90 case 'gt':return x.gt(y);
91 case 'lt':return x.lt(y);
92 }
93 } else if (O.isBool(x) || O.isNumber(x)) {
94 switch (op) {
95 case 'eval': var exp = y; return exp(x);
96 case 'not':return !x;
97 case 'neg':return -x;
98 case 'inv':return 1/x;
99 case 'bnot':return ~x;
100 case 'and':return x&&y;
101 case 'or':return x||y;
102 case 'xor':return x!==y;
103 case '+':return x+y;
104 case '-':return x-y;
105 case '*':return x*y;
106 case '/':return x/y;
107 case '%':return x%y;
108 case 'eq':return x===y;
109 case 'neq':return x!==y;
110 case 'geq':return x>=y;
111 case 'leq':return x<=y;
112 case 'gt':return x>y;
113 case 'lt':return x<y;
114 case '&':return x&y;
115 case '|':return x|y;
116 case 'bxor':return x^y;
117 case '<<':return x<<y;
118 case '>>':return x>>y;
119 case 'and':return x&&y;
120 case 'or':return x||y;
121 case 'xor':return x!==y;
122 case 'sqrt':
123 if (x>=0) return Math.sqrt(x);
124 else {
125 var c = new O.Complex(x,0);
126 return c.sqrt();
127 }
128 case 'power':
129 if (x>=0 || O.isInteger(y))
130 return Math.pow(x,y);
131 else
132 return new O.Complex(x,0).power(y);
133 case 'log':return Math.log(x);
134 case 'exp':return Math.exp(x);
135 case 'abs':return Math.abs(x);;
136 case 'sin':return Math.sin(x);
137 case 'cos':return Math.cos(x);
138 case 'tan':return Math.tan(x);
139 case 'asin':return Math.asin(x);
140 case 'acos':return Math.acos(x);
141 case 'atan':return Math.atan(x);
142 case 'sinh':return Math.sinh(x);
143 case 'cosh':return Math.cosh(x);
144 case 'tanh':return Math.tanh(x);
145 case 'ceil':return Math.ceil(x);
146 case 'floor':return Math.floor(x);
147 case 'round':return Math.round(x);
148 case 'log1p':return Math.log1p(x);
149 case 'log10':return Math.log10(x);
150 case 'log2':return Math.log2(x);
151 case 'random':return Math.random();
152 case 'sign':return Math.sign(x);
153 case 'abs':return Math.abs(x);
154 case 'cbrt':return Math.cbrt(x); // cubic root
155 }
156 }
157 } else if (O.isFunction(x)) {
158 if (O.isFunction(y)) {
159 switch (op) {
160 case 'neg':return O.fneg(x);
161 case 'inv':return O.finv(x);
162 case '+':return O.fadd(x,y);
163 case '-':return O.fsub(x,y);
164 case '*':return O.fmul(x,y);
165 case '/':return O.fdiv(x,y);
166 case 'compose':return O.fcompose(x,y);
167 }
168 } else {
169 switch (op) {
170 case 'eval':return x(y);
171 }
172 }
173 } else if (O.isArray(x)) {
174 return O.vop(op,x,y);
175 }
176 throw Error('op fail:op,x,y=', op, x, y);
177}
178
179O.sum=function(x) { return O.vop('sum', x) }
180O.product=function(x) { return O.vop('product', x) }
181O.max=function(x) { return O.vop('max', x) }
182O.min=function(x) { return O.vop('min', x) }
183O.eval=function(x,y) { return O.op('eval', x,y) }
184O.norm=function(x) {
185 var norm2 = O.vop('sum', x, (x)=>x*x);
186 return Math.sqrt(norm2);
187}
188
189// +-*/%^
190O.add=function(x,y) { return O.op('+',x,y) }
191O.sub=function(x,y) { return O.op('-',x,y) }
192O.mul=function(x,y) { return O.op('*',x,y) }
193O.div=function(x,y) { return O.op('/',x,y) }
194O.mod=function(x,y) { return O.op('%',x,y) }
195O.power=function(x,y) { return O.op('power', x, y) }
196O.neg=function(x) { return O.op('neg', x) }
197O.inv=function(x) { return O.op('inv', x) }
198// logical
199O.not=function(x) { return O.op('not', x) }
200O.and=function(x,y) { return O.op('&&', x, y) }
201O.or=function(x,y) { return O.op('||', x, y) }
202O.xor=function(x,y) { return O.op('xor', x, y) }
203O.bnot=function(x) { return O.op('bnot', x) }
204O.band=function(x,y) { return O.op('&', x, y) }
205O.bor=function(x,y) { return O.op('|', x, y) }
206O.bxor=function(x,y) { return O.op('bxor', x, y) }
207O.lshift=function(x,y) { return O.op('<<', x, y) }
208O.rshift=function(x,y) { return O.op('>>', x, y) }
209// compare
210O.eq=function(x,y) { return O.op('eq', x, y) }
211O.neq=function(x,y) { return O.op('neq', x, y) }
212O.geq=function(x,y) { return O.op('geq', x, y) }
213O.leq=function(x,y) { return O.op('leq', x, y) }
214O.gt=function(x,y) { return O.op('gt', x, y) }
215O.lt=function(x,y) { return O.op('lt', x, y) }
216// number function
217O.sqrt=function(x) { return O.op('sqrt', x) }
218O.log=function(x) { return O.op('log', x) }
219O.exp=function(x) { return O.op('exp', x) }
220O.abs=function(x) { return O.op('abs', x) }
221O.sin=function(x) { return O.op('sin', x) }
222O.cos=function(x) { return O.op('cos', x) }
223O.tan=function(x) { return O.op('tan', x) }
224O.asin=function(x) { return O.op('asin', x) }
225O.acos=function(x) { return O.op('acos', x) }
226O.atan=function(x) { return O.op('atan', x) }
227O.atan2=function(x) { return O.op('atan2', x) }
228O.ceil=function(x) { return O.op('ceil', x) }
229O.floor=function(x) { return O.op('floor', x) }
230O.round=function(x) { return O.op('round', x) }
231
232O.parse = function(s) {
233 if (s.indexOf(';')>=0) {
234 var m = split(s, ";"), matrix;
235 for (var i=0; i<m.length; i++) {
236 matrix[i] = O.parse(m[i]);
237 }
238 return matrix;
239 } if (s.indexOf(',')>=0) {
240 var a = split(s, ","), array;
241 for (var i=0; i<a.length; i++) {
242 array[i] = O.parse(a[i]);
243 }
244 return array;
245 }
246 else if (s.indexOf('/')>=0)
247 return O.Ratio.parse(s);
248 else if (s.indexOf('i')>=0)
249 return O.Complex.parse(s);
250 else {
251 return parseFloat(s);
252 }
253}
254
255// =========== Polynomial Ring ==============
256O.PolynomialRing=extend({}, O.Field);
257
258class Polynomial extends O.FieldObj {
259 constructor(c) {
260 super(O.PolynomialRing);
261 this.c = c; // sum(ci x^i)
262 }
263
264 eval(x) {
265 var c = this.c, i=c.length-1, sum=c[i];
266 for (i--;i>=0; i--) {
267 sum = c[i].add(x.mul(sum));
268 }
269 return sum;
270 }
271
272 size() { return this.c.length }
273
274 toString() {
275 var s = [], c=this.c;
276 for (var i=c.length-1; i>=0; i--) {
277 s.push(c[i]+'x^'+i);
278 }
279 return s.join('+');
280 }
281
282 root() {
283 var p = this.normalize(); // 正規化
284 switch (this.size()) {
285 case 2:return p.c[0].neg();
286 case 3:return p.root2(p.c[1], p.c[0]);
287 case 4:return p.root3(p.c[2], p.c[1], p.c[0]);
288 default:throw Error('root() fail');
289 }
290
291 }
292
293 root2(b,c) { // x^2 + bx + c =0
294 var d = b.mul(b).sub(c.mul(4)).sqrt();
295 return [b.neg().add(d), b.neg().sub(d)];
296 }
297
298 root3(a,b,c) { // x^3+ax^2+bx+c=0
299 var q=((2*a*a*a/27)-(a*b/3)+c)/2;
300 var p=(b-a*a/3)/3;
301 var D=p*p*p+q*q;
302 var Dsqrt = D.sqrt(), _q=q.neg();
303 var u_p=_q.add(Dsqrt).power(1/3); // (-q+sqrt(D))^1/3
304 var u_m=_q.sub(Dsqrt).power(1/3); // (-q-sqrt(D))^1/3
305 console.log("q=%s p=%s D=%s u+=%s u-=%s", q, p, D, u_p, u_m);
306 var rho_p = (1/2).mul(O.parse('-1+3i'));
307 var rho_m = (1/2).mul(O.parse('-1-3i'));
308 console.log("rho_p=%s rho_m=%s", rho_p, rho_m);
309 var y1=u_p.add(u_m);
310 var y2=rho_p.add(u_p).add(rho_m.mul(u_m));
311 var y3=rho_p.sub(u_p).add(rho_p.mul(u_m));
312 return [y1, y2, y3];
313 }
314
315 normalize() {
316 var a = this.c[this.size()-1];
317 var nc = this.c.div(a);
318 return new Polynomial(nc);
319 }
320}
321
322O.Polynomial = Polynomial;
323/*
324
325function root3(a,b,c) { // x^3+ax^2+bx+c=0
326 var q=((2*a*a*a/27)-(a*b/3)+c/2);
327 var p=(b-a*a/3)/3;
328 var D=p*p*p+q*q;
329 var u_p=Math.sqrt(3, -q+Math.sqrt(D));
330 var u_m=Math.sqrt(3, -q-Math.sqrt(D));
331 var rho_p = 1/2*(-1+3i);
332 var rho_m = 1/2*(-1-3i);
333 var y1=u_p+u_m;
334 var y2=rho_p+u_p+ rho_m*u_m;
335 var y3=rho_p-u_p+ rho_p*u_m;
336}
337*/
338O.PolynomialAddGroup={
339 e:new Polynomial([0]), // 到底應該設幾個?
340 op:function(x,y) {
341 var size = Math.max(x.size(), y.size());
342 var a=O.vextend(x.c,size), b=O.vextend(y.c,size);
343 var c=O.add(a,b);
344 return new Polynomial(c);
345 },
346 inv:function(x) {
347 var c = O.neg(x.c);
348 return new Polynomial(c);
349 },
350}
351
352extend(O.PolynomialAddGroup, O.Group);
353
354O.PolynomialMulSemiGroup={
355 e:new Polynomial([1]),
356 op:function(x,y) {
357 var c=[];
358 for (var xi=0; xi<x.c.length; xi++) {
359 for (var yi=0; yi<y.c.length; yi++) {
360 var cxy = (typeof c[xi+yi]==='undefined')?0:c[xi+yi];
361 c[xi+yi] = cxy+x.c[xi]*y.c[yi];
362 }
363 }
364 return new Polynomial(c);
365 },
366 inv:function(x) { throw Error('PolynomialMulSemiGroup.inv not defined') },
367}
368
369extend(O.PolynomialMulSemiGroup, O.Group);
370
371O.PolynomialRing.init(O.PolynomialAddGroup, O.PolynomialMulSemiGroup);
372
373module.exports = O;
374
375},{"./field":4}],2:[function(require,module,exports){
376// http://blog.smartbear.com/testing/four-serious-math-libraries-for-javascript/
377
378// Four Serious Math Libraries for JavaScript
379
380var B = {};
381
382B.slice = function(a) {
383 return Array.prototype.slice.call(a);
384}
385
386B.bind=function(o, member) {
387 if (typeof o[member]==='Function')
388 return o[member].bind(o);
389 else
390 return o[member];
391}
392
393B.ncall = function() {
394 var args = B.slice(arguments);
395 var n = args[0];
396 var o = args[1];
397 var fname = args[2];
398 var params = args.slice(3);
399 var a=[];
400 for (var i=0; i<n; i++)
401 a.push(o[fname].apply(o, params));
402 return a;
403}
404
405B.mapFunctions=function(host, obj, pairs) {
406 for (var h in pairs) {
407 var o = pairs[h];
408 if (typeof host[h] !=='undefined')
409 console.log('mapBind: error!', h, ' has been defined!');
410 host[h]=B.bind(obj, o);
411 }
412}
413
414B.copyFunctions=function(host, obj, names) {
415 for (var name of names) {
416 if (typeof host[name] !=='undefined')
417 console.log('namesBind: error!', name, ' has been defined!');
418 host[name]=B.bind(obj, name);
419 }
420}
421
422B.mix=function(self, members) {
423 for (var name in members) {
424 var member = members[name];
425 if (typeof self[name] === 'undefined') {
426 Object.defineProperty(self, name, {
427 enumerable: true,
428 writable: true,
429 value: member,
430 });
431 } else {
432 console.log("B.mix fail:", name, " already exists!");
433 }
434 }
435}
436
437B.arg1this = function(f,obj) { // 傳回一個已經綁定 f, obj 的函數
438 return function() {
439 var args = B.slice(arguments);
440 return f.apply(obj, [this].concat(args)); // 效果相當於 obj.f(this, args)
441 }
442}
443
444B.mixThis=function(proto, obj, fmembers) {
445 for (var fname of fmembers) {
446 var f = obj[fname];
447 if (typeof proto[fname] === 'undefined') {
448 Object.defineProperty(proto, fname, {
449 enumerable: false,
450 writable: true,
451 value: B.arg1this(f,obj), // proto.f(args) => obj.f(this, args) , 這行盡量不要動,除非想得很清楚了!
452 });
453 } else {
454 console.log("B.mixThis:", fname, " fail!");
455 }
456 }
457}
458
459B.mixThisMap=function(proto, obj, poMap) {
460 for (var pname in poMap) {
461 var oname = poMap[pname];
462 var f = obj[oname];
463 if (typeof proto[pname] === 'undefined') {
464 Object.defineProperty(proto, pname, {
465 enumerable: false,
466 writable: true,
467 value: B.arg1this(f,obj), // proto.f(args) = f(this, args) , 這行盡量不要動,除非想得很清楚了!
468 });
469 } else {
470 console.log('pname=', pname, 'proto[pname]=', proto[pname]);
471 console.log("B.mixThisMap:", oname, " fail!");
472 }
473 }
474}
475
476B.ctrim=function(s, set, side) {
477 side = side||"both";
478 for (var b=0; b<s.length; b++)
479 if (set.indexOf(s[b])<0) break;
480 for (var e=s.length-1; e>=0; e--)
481 if (set.indexOf(s[e])<0) break;
482 if (side === "right") b=0;
483 if (side === "left") e=s.length-1;
484 return s.substring(b, e+1);
485}
486
487B.lpad=function(s, width, ch) {
488 return s.length >= width ? s : new Array(width - s.length + 1).join(ch) + s;
489}
490
491B.def = function(x, value) {
492 return (typeof x !== 'undefined')?x:value;
493}
494
495B.precision=2;
496
497B.nstr = function(n, precision=B.precision) {
498 if (n % 1 === 0) return n.toString();
499 return n.toFixed(precision);
500}
501
502B.astr = function(a, precision=B.precision) {
503 var s=[];
504 for (var i in a) {
505 s.push(a[i].str(precision));
506 }
507 return "["+s.join(', ')+"]";
508}
509
510B.sstr = function(s) { return s.toString(); }
511
512B.ostr = function(o, precision=B.precision) {
513 var s = [];
514 for (var k in o)
515 s.push(k+":"+B.str(o[k], precision));
516 return "{"+s.join(", ")+"}";
517}
518
519B.str = function(o, precision=B.precision) {
520 if (typeof o ==='undefined')
521 return 'undefined';
522 else
523 return o.str(precision);
524}
525
526module.exports = B;
527
528/*
529B.calls = function() {
530 var args = B.slice(arguments);
531 var n = args[0];
532 var f = args[1];
533 var params = args.slice(2);
534 var a=[];
535 for (var i=0; i<n; i++)
536 a.push(f.apply(null, params));
537 return a;
538}
539*/
540/*
541B.slice = function(a) {
542 return Array.prototype.slice.call(a);
543}
544
545B.curry = function(f,o) {
546 return function() {
547 var args = Array.prototype.slice.call(arguments);
548 return f.apply(null, [o].concat(args));
549 }
550}
551
552B.mixThis=function(proto, fmap) {
553 for (var name in fmap) {
554 var f = fmap[name];
555 if (typeof proto[name] === 'undefined') {
556 Object.defineProperty(proto, name, {
557 enumerable: false,
558 writable: true,
559 value: B.arg1this(f), // proto.f(args) = f(this, args)
560 });
561 } else {
562 console.log("B.mixThis:", name, " fail!");
563 }
564 }
565}
566B.thisAsArg1 = function(f) {
567 return function() {
568 var args = B.slice(arguments);
569 return f.apply(null, [this].concat(args));
570 }
571}
572
573*/
574
575/*
576B.mixThis=function(proto, obj, fmembers) {
577 for (var fname of fmembers) {
578// var f = B.bind(obj, fname);
579 var f = obj[fname];
580 if (typeof proto[fname] === 'undefined') {
581 Object.defineProperty(proto, fname, {
582 enumerable: false,
583 writable: true,
584 value: B.arg1this(f,obj), // proto.f(args) = f(this, args)
585 });
586 } else {
587 console.log("B.mixThis:", fname, " fail!");
588 }
589 }
590}
591*/
592},{}],3:[function(require,module,exports){
593module.exports = O = require("./matrix");
594
595// =========== Calculus =================
596O.dx = 0.01;
597
598// 微分 differential calculus
599O.fdiff = O.fdifferential = function(f, x, dx) {
600 dx = dx || O.dx;
601 var dy = f(x.add(dx)).sub(f(x.sub(dx)));
602 return dy.div(dx.mul(2));
603}
604
605// 積分 integral calculus
606O.fint = O.fintegral = function(f, a, b, dx) {
607 dx = dx || O.dx;
608 var area = 0.0;
609 for (var x=a; x<b; x=x+dx) {
610 area = area + f(x).mul(dx);
611 }
612 return area;
613}
614
615// 偏微分 partial differential calculus
616// f=[f1,f2,....] , x=[x1,x2,...] , dx=[dx1,dx2,....]
617O.pdiff = O.pdifferential = function(f, x, i) {
618 f = O.fa(f);
619 var dx = O.vfill(x.length, 0);
620 dx[i] = O.dx;
621// var df = f.apply(null, x.add(dx)).sub(f.apply(null, x.sub(dx)));
622 var df = f(x.add(dx)).sub(f(x.sub(dx)));
623 return df.div(dx.norm().mul(2));
624}
625
626// multidimensional integral calculus
627// f=[f1,f2,....] , a=[a1,a2,...] , b=[b1,b2,....]
628O.pint = O.pintegral = function(f, a, b) {
629
630}
631
632// 梯度 gradient : grad(f,x)=[pdiff(f,x,0), .., pdiff(f,x,n)]
633O.fgrad = O.fgradient = function(f, x) {
634 var gf = [];
635 for (var i=0; i<x.length; i++) {
636 gf[i] = O.pdiff(f, x, i);
637 }
638 return gf;
639}
640
641// 散度 divergence : div(F,x) = sum(pdiff(F[i],x,i))
642O.fdiv = O.fdivergence = function(F, x) {
643 var Fx = F(x);
644 var f=[], d=[];
645 for (var i=0; i<x.length; i++) {
646 f[i] = (xt)=>F(xt)[i];
647 d[i] = O.pdiff(f[i],x,i);
648 }
649 return d.sum();
650}
651
652// 旋度 curl : curl(F) = div(F)xF
653O.fcurl = O.fcurlance = function(F, x) {
654
655}
656
657// 線積分: int F●dr = int F(r(t))●r'(t) dt
658O.vint = O.vintegral = function(F, r, a, b, dt) {
659 dt = dt||O.dx;
660 var sum = 0;
661 for (var t=a; t<b; t+=dt) {
662 sum += F(r(t)).dot(r.diff(t));
663 }
664 return sum;
665}
666
667// 定理:int F●dr = int(sum(Qxi dxi))
668
669// 向量保守場: F=grad(f) ==> int F●dr = f(B)-f(A)
670
671// 定理: 向量保守場 F, pdiff(Qxi,xj) == pdiff(Qxj,xi) for any i, j
672// ex: F=[x^2y, x^3] 中, grad(F)=[x^2, 3x^2] 兩者不相等,所以不是保守場
673
674// 格林定理:保守場中 《線積分=微分後的區域積分》
675// int P dx + Q dy = int int pdiff(Q,x) - pdiff(P, y) dx dy
676
677// 散度定理:通量 = 散度的區域積分
678// 2D : int F●n ds = int int div F dx dy
679// 3D : int int F●n dS = int int int div F dV
680
681// 史托克定理: F 在曲面 S 上的旋度總和 = F 沿著邊界曲線 C 的線積分
682// int int_D curl(F)●n dS = int_C F●dr
683
684
685},{"./matrix":8}],4:[function(require,module,exports){
686// module : Field & Group Theory
687var F = require("./set");
688F.Integer=require("./integer");
689var eq = F.eq;
690// ========== Group =================
691// 注意: 箭頭函數會自動將 this 變數綁定到其定義時所在的物件,因此以下很多地方不能用箭頭函數。
692// 參考: https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Functions/Arrow_functions
693F.Group={
694 invOp:function(x,y) {
695 return this.op(x,this.inv(y));
696 },
697 power:function(x,n) {
698 var p=this.e;
699 for (var i=0;i<n;i++) {
700 p=this.op(p,x);
701 }
702 return p;
703 },
704 leftCoset:function(g, H) {
705 var set = new F.Set();
706 for (var i in H)
707 set.add(this.op(g,H[i]));
708 return set;
709 },
710 rightCoset:function(H, g) {
711 var set = new F.Set();
712 for (var i in H)
713 set.add(this.op(g,H[i]));
714 return set;
715 },
716 // ref:https://en.wikipedia.org/wiki/Group_(mathematics)
717 // 封閉性:For all a, b in G, a • b, is also in G
718 closability:function(a,b) {
719 var ab = this.op(a,b);
720 var close=this.has(ab);
721 return this.has(this.op(a,b));
722 },
723 // 結合性:For all a, b and c in G, (a • b) • c = a • (b • c).
724 associativity:function(a,b,c) {
725 var op = this.op.bind(this);
726 return eq(op(op(a,b),c), op(a,op(b,c)))
727 },
728 // 單位元素:Identity element
729 identity:function(a) {
730 return eq(this.op(this.e,a),a)
731 },
732 // 反元素:Inverse element
733 inversability:function(a) {
734 return eq(this.op(a,this.inv(a)),this.e);
735 },
736}
737
738// PermutationGroup
739F.PermutationGroup={
740 op:function(x,y) {
741 var z = [];
742 for (var i in x)
743 z[i] = y[x[i]];
744 return z;
745 },
746 inv:function(x) {
747 var nx = [];
748 for (var i in x) {
749 nx[x[i]] = i;
750 }
751 return nx;
752 },
753}
754
755extend(F.PermutationGroup, F.Group);
756
757// Cyclic Group : a group that is generated by a single element (g)
758F.CyclicGroup={
759 G:[],
760// g:g,
761 op:function(x,y) {
762 },
763 inv:function(x) {
764 },
765 create(g) {
766 var t = e;
767 for (var i=0; !t.eq(e); i++) {
768 G[i]=t;
769 t=op(g,G[i]);
770 }
771 }
772}
773
774extend(F.CyclicGroup, F.Group);
775
776// NormalSubGroup : 正規子群
777F.NormalSubGroup={
778 op:function(x,y) {
779 },
780 inv:function(x) {
781 },
782 normality(g,n) {
783 return this.has(g.op(n).op(g.inv()));
784 },
785}
786
787extend(F.NormalSubGroup, F.Group);
788
789// Quotent Group : aggregating similar elements of a larger group using an equivalence relation that preserves the group structure
790
791F.QuotentGroup={
792 eq:function(x,y) {
793
794 },
795 op:function(x,y) {
796 },
797 inv:function(x) {
798 },
799}
800
801extend(F.QuotentGroup, F.Group);
802
803// Normal SubGroup : gH = Hg
804// https://en.wikipedia.org/wiki/Normal_subgroup
805F.NormalSubGroup={
806 op:function(x,y) {
807 },
808 inv:function(x) {
809 },
810}
811
812extend(F.NormalSubGroup, F.Group);
813
814// 群同構第一定理: 給定 GG和 G ′ 兩個群,和 f : G → G ′ 群同態。則 Ker ⁡ f 是一個 G 的正規子群。
815// 群同構第二定理:給定群 G 、其正規子群 N、其子群 H,則 N ∩ H 是 H 的正規子群,且我們有群同構如下: H / ( H ∩ N ) ≃ H N / N
816// 群同構第三定理: 給定群 G, N 和 M,M 為 G 的正規子群,滿足 M 包含於 N ,則 N / M 是 G / M 的正規子群,且有如下的群同構: ( G / M ) / ( N / M ) ≃ G / N .
817
818// ========== Field =================
819F.Field={
820 sub:function(x,y) { return this.addGroup.invOp(x,y) },
821 div:function(x,y) { return this.mulGroup.invOp(x,y) },
822// mod:function(x,y) { return x.sub(x.div(y).mul(y)) },
823 power:function(x,n) { return this.mulGroup.power(x,n) },
824 init:function(addGroup, mulGroup) {
825 this.addGroup = addGroup;
826 this.mulGroup = mulGroup;
827 this.zero = addGroup.e;
828 this.add = function(x,y) { return this.addGroup.op(x,y) }
829 this.neg = function(x) { return this.addGroup.inv(x) }
830 this.one = mulGroup.e;
831 this.mul = function(x,y) { return this.mulGroup.op(x,y) }
832 this.inv = function(x) { return this.mulGroup.inv(x) }
833 this.power= function(x,n) { return this.mulGroup.power(x,n) }
834 this.eq = function(x,y) { return F.eq(x,y); }
835 this.neq = function(x,y) { return !this.eq(x,y); }
836 this.isZero = function(x) {
837 return this.field.eq(this, F.proto(this).zero)
838 }
839 this.isOne = function(x) {
840 return this.field.eq(this, F.proto(this).one)
841 }
842 this.gcd = function(x,y) {
843 if (y.isZero()) return x;
844 return gcd(y, mod(x,y));
845 }
846 },
847 ldistribute:function(a,b,c) {
848 return this.mul(a, this.add(b,c)).eq(this.add(this.mul(a,b), this.mul(a,c)));
849 },
850 rdistribute:function(a,b,c) {
851 return this.ldistribute(b,c,a);
852 },
853 associativity:function(a,b,c) {
854 return this.mul(a,this.mul(b,c)).eq(this.mul(this.mul(a,b),c));
855 },
856}
857
858F.Ring = F.Field; // Ring (環) : 可能沒有乘法單位元素和反元素的 Field
859F.Module = F.Field;// Module(模) : (R +) is Ring, (R × M → M)
860F.Ideal = F.Field; // Ideal (理想): 子環,且 i·r ∈ I (左理想), r·i ∈ I (右理想)
861
862// ref : https://en.wikipedia.org/wiki/Group_homomorphism
863// https://en.wikipedia.org/wiki/Fundamental_theorem_on_homomorphisms
864// 同態:h(a • b) = h(a) x h(b)
865F.homomorphism=function(h, g1, g2) {
866 var a=g1.random(), b=g2.random();
867 return eq(h(group1.op(a,b)), group2.op(h(a), h(b)))
868}
869
870// ref : https://en.wikipedia.org/wiki/Isomorphism
871// https://en.wikipedia.org/wiki/Isomorphism_theorem
872// 同構:h(a • b) = h(a) • h(b)
873F.isomorphism=function(h1, h2, g1, g2) {
874 var a1=g1.random(), b1=g2.random();
875 var a2=g1.random(), b2=g2.random();
876 return homorphism(h1,g1,g2)&&homorphism(h2,g2,g1);
877}
878
879// ========== Float Field =================
880F.FloatAddGroup={
881 e:0,
882 op:function(x,y) { return x+y },
883 inv:function(x) { return -x},
884}
885
886extend(F.FloatAddGroup, F.Group, F.Set.Float);
887
888F.FloatMulGroup={
889 e:1,
890 op:function(x,y) { return x*y },
891 inv:function(x) { return 1/x},
892}
893
894extend(F.FloatMulGroup, F.Group, F.Set.Float);
895
896F.FloatField=extend({}, F.Field, F.Set.Float);
897
898F.FloatField.init(F.FloatAddGroup, F.FloatMulGroup);
899
900// ========== Finite Field =================
901F.FiniteAddGroup={
902 e:0,
903 op:function(x,y) { return (x+y)%this.n },
904 inv:function(x) { return (this.n-x) }
905}
906
907extend(F.FiniteAddGroup, F.Group);
908
909F.FiniteMulGroup={
910 e:1,
911 op:function(x,y) { return (x*y)%this.n },
912 inv:function(x) { return this.invMap[x] },
913 setOrder:function(n) {
914 this.n = n;
915 let invMap = new Map();
916 for (var x=1; x<n; x++) {
917 var y = this.op(x,x);
918 invMap.set(x,y);
919 }
920 this.invMap = invMap;
921 }
922}
923
924extend(F.FiniteMulGroup, F.Group);
925
926F.FiniteField=extend({}, F.Field);
927
928F.FiniteField.create=function(n) {
929 var finiteField = extend(F.Finite(n), F.FiniteField);
930 var addGroup = extend(F.Finite(n), {n:n}, F.FiniteAddGroup);
931 var mulGroup = extend(F.Finite(n), {n:n}, F.FiniteMulGroup);
932 finiteField.init(addGroup, mulGroup);
933 mulGroup.setOrder(n);
934 return finiteField;
935}
936
937class MathObj {
938 constructor() {}
939 str() { return this.toString() }
940}
941
942F.MathObj = MathObj;
943
944// =========== Field Object ==============
945class FieldObj extends MathObj {
946 constructor(field) {
947 super();
948 this.field = field;
949 var p = Object.getPrototypeOf(this);
950 p.zero = field.zero;
951 p.one = field.one;
952 }
953
954 add(y) { return this.field.add(this,y) }
955 mul(y) { return this.field.mul(this,y) }
956 neg() { return this.field.neg(this) }
957 inv() { return this.field.inv(this) }
958 div(y) { return this.field.div(this,y) }
959 sub(y) { return this.field.sub(this,y) }
960 power(n) { return this.field.power(this,n) }
961 isZero(x) { return this.field.isZero(this) }
962 isOne(x) { return this.field.isOne(this) }
963 eq(y) { return this.field.eq(this, y) }
964 neq(y) { return this.field.neq(this, y) }
965 mod(y) { return this.field.mod(this, y) }
966 gcd(y) { return this.field.gcd(this, y) }
967}
968
969F.FieldObj = FieldObj;
970
971// =========== Complex Field ==============
972F.ComplexField=extend({}, F.Field);
973
974class Complex extends FieldObj {
975 constructor(a,b) {
976 super(F.ComplexField);
977 this.a = a; this.b = b;
978 }
979 conj() { return new Complex(this.a, -1*this.b); }
980
981 str() {
982 var op = (this.b<0)?'':'+';
983 return this.a.str()+op+this.b.str()+'i';
984 }
985 toString() { return this.str() }
986
987 toPolar() {
988 var a=this.a, b=this.b, r=Math.sqrt(a*a+b*b);
989 var theta = Math.acos(a/r);
990 return {r:r, theta:theta}
991 }
992
993 power(k) {
994 var p = this.toPolar();
995 return Complex.polarToComplex(Math.pow(p.r,k), k*p.theta);
996 }
997
998 sqrt() {
999 return this.power(1/2);
1000 }
1001
1002 static toComplex(o) {
1003 if (F.isFloat(o))
1004 return new Complex(o, 0);
1005 else if (o instanceof Complex)
1006 return o;
1007 console.log('o=', o);
1008 throw Error('toComplex fail');
1009 }
1010
1011 static polarToComplex(r,theta) {
1012 var a=r*Math.cos(theta), b=r*Math.sin(theta);
1013 return new Complex(a, b);
1014 }
1015
1016 static parse(s) {
1017 var m = s.match(/^([^\+]*)(\+(.*))?$/);
1018 var a = parseFloat(m[1]);
1019 var b = typeof m[3]==='undefined'?1:parseFloat(m[3]);
1020 return new Complex(a, b)
1021 }
1022}
1023
1024F.Complex = Complex;
1025var C = (a,b)=>new Complex(a,b);
1026var enumComplex=[C(1,0),C(0,1),C(0,0),C(2,3),C(-5,4),C(-10,-7)];
1027F.ComplexSet=new F.Set(enumComplex);
1028F.ComplexSet.has = (a)=>a instanceof Complex;
1029
1030F.ComplexAddGroup={
1031 e:new Complex(0,0),
1032 op:function(x,y) {
1033 x = Complex.toComplex(x), y=Complex.toComplex(y);
1034 return new Complex(x.a+y.a, x.b+y.b)
1035 },
1036 inv:function(x) {
1037 x = Complex.toComplex(x);
1038 return new Complex(-x.a, -x.b)
1039 }
1040}
1041
1042extend(F.ComplexAddGroup, F.Group, F.ComplexSet);
1043
1044F.ComplexMulGroup={
1045 e:new Complex(1,0),
1046 op:function(x,y) {
1047 x = Complex.toComplex(x), y=Complex.toComplex(y);
1048 return new Complex(x.a*y.a-x.b*y.b, x.a*y.b+x.b*y.a);
1049 },
1050 inv:function(x) {
1051 x = Complex.toComplex(x);
1052 var a=x.a,b=x.b, r=(a*a+b*b);
1053 return new Complex(a/r, -b/r);
1054 }
1055}
1056
1057extend(F.ComplexMulGroup, F.Group, F.ComplexSet);
1058
1059extend(F.ComplexField, F.ComplexSet);
1060
1061F.ComplexField.init(F.ComplexAddGroup, F.ComplexMulGroup);
1062
1063// =========== Ratio Field ==============
1064F.RatioField=extend({}, F.Field);
1065
1066class Ratio extends FieldObj {
1067 constructor(a,b) {
1068 super(F.RatioField);
1069 this.a = a; this.b = b;
1070 }
1071
1072 reduce() {
1073 var a = this.a, b=this.b;
1074 var c = F.Integer.gcd(a, b);
1075 return new Ratio(a/c, b/c);
1076 }
1077
1078 toString() { return this.a+'/'+this.b; }
1079
1080 static parse(s) {
1081 var m = s.match(/^(\d+)(\/(\d+))?$/);
1082 var a = parseInt(m[1]);
1083 var b = typeof m[3]==='undefined'?1:parseInt(m[3]);
1084 return new Ratio(a, b)
1085 }
1086}
1087
1088F.Ratio = Ratio;
1089
1090F.RatioAddGroup={
1091 e:new Ratio(0,1),
1092 op:function(x,y) { return new Ratio(x.a*y.b+x.b*y.a, x.b*y.b) },
1093 inv:function(x) { return new Ratio(-x.a, x.b); },
1094}
1095
1096extend(F.RatioAddGroup, F.Group);
1097
1098F.RatioMulGroup={
1099 e:new Ratio(1,1),
1100 op:function(x,y) { return new Ratio(x.a*y.a, x.b*y.b) },
1101 inv:function(x) { return new Ratio(x.b, x.a) },
1102}
1103
1104extend(F.RatioMulGroup, F.Group);
1105
1106F.RatioField.init(F.RatioAddGroup, F.RatioMulGroup);
1107
1108// =========== Function Operation ==============
1109F.fneg=function(fx) { return function(v) {
1110 return -1*fx(v);
1111}}
1112
1113F.finv=function(fx) { return function(v) {
1114 return 1/fx(v);
1115}}
1116
1117F.fadd=function(fx,fy) { return function(v) {
1118 return fx(v).add(fy(v));
1119}}
1120
1121F.fsub=function(fx,fy) { return function(v) {
1122 return fx(v).sub(fy(v));
1123}}
1124
1125F.fmul=function(fx,fy) { return function(v) {
1126 return fx(v).mul(fy(v));
1127}}
1128
1129F.fdiv=function(fx,fy) { return function(v) {
1130 return fx(v).div(fy(v));
1131}}
1132
1133F.fcompose=function(fx,fy) { return function(v) {
1134 return fx(fy(v));
1135}}
1136
1137F.feval=function(f,x) { return f(x) }
1138
1139// f=(x,y)=>x*y+x*x;
1140// f0=fa(f); f0([x,y]);
1141F.fa=function(f) {
1142 return function(x) {
1143 return f.apply(null, x);
1144 }
1145}
1146
1147// =========== Function Field ==============
1148F.FunctionField=extend({}, F.Field);
1149
1150F.FunctionAddGroup={
1151 e:function(x) { return 0 },
1152 op:function(x,y) { return F.fadd(x,y) },
1153 inv:function(x) { return F.fneg(x) },
1154}
1155
1156extend(F.FunctionAddGroup, F.Group);
1157
1158F.FunctionMulGroup={
1159 e:function(x) { return f(x) },
1160 op:function(x,y) { return F.fsub(x,y) },
1161 inv:function(x) { return F.finv(x) },
1162}
1163
1164extend(F.FunctionMulGroup, F.Group);
1165
1166F.FunctionField.init(F.FunctionAddGroup, F.FunctionMulGroup);
1167
1168// Function
1169F.isField=function(x) {
1170 return F.isBool(x) || F.isNumber(x) || x instanceof F.FieldObj;
1171}
1172
1173module.exports = F;
1174
1175
1176},{"./integer":6,"./set":9}],5:[function(require,module,exports){
1177var G = require("./statistics");
1178
1179// 各種 space : https://en.wikipedia.org/wiki/Space_(mathematics)#/media/File:Mathematical_implication_diagram_eng.jpg
1180
1181G.Space={} // Space = HllbertSpace + BanachSpace + Manifold (流形)
1182
1183G.HilbertSpace={} // HilbertSpace => InnerProductSpace => LocallyConvaxSpace => VectorSpace (LinearSpace)
1184
1185G.InnerProductSpace={}
1186
1187G.LocallyConvaxSpace={}
1188
1189G.LinearSpace=G.VectorSpace={} // (Algebraic)
1190
1191G.BanachSpace={} // BanachSpace => NormedVectorSpace => MetricSpace => TopologicalSpace
1192
1193G.NormedVectorSpace={}
1194
1195G.MetricSpace={}
1196
1197G.TopologicalSpace={} // (Analytic)
1198
1199G.Manifold={}
1200
1201G.Rn = {} // (R,R,....)
1202
1203G.steps = function(from, to, step) {
1204 step=step || 1;
1205 var a=[];
1206 for (var t=from; t<=to; t+=step)
1207 a.push(t);
1208 return a;
1209}
1210
1211G.curve=function(f, from=-10, to=10, step=0.1) {
1212 var x=G.steps(from, to, step);
1213 var y=x.map(f);
1214 return { type:"curve", x:x, y:y };
1215}
1216
1217G.hist=function(a, from, to, step=1) {
1218// console.log("from=%d to=%d step=%d", from, to, step);
1219 from = from||a.min();
1220 to = to||a.max();
1221 var n = Math.ceil((to-from+G.EPSILON)/step);
1222 var xc = G.steps(from+step/2.0, to, step);
1223// console.log("from=%d to=%d step=%d xc=%j", from, to, step, xc);
1224 var bins = G.newV(n, 0);
1225 for (var i in a) {
1226 var slot=Math.floor((a[i]-from)/step);
1227 if (slot>=0 && slot < n)
1228 bins[slot]++;
1229 }
1230 return { type:'histogram', xc:xc, bins:bins, from:from, to:to, step:step};
1231}
1232/*
1233G.ihist=function(a) {
1234 console.log("a.min()=%d a.max()=%d", a.min(), a.max());
1235 return G.hist(a, a.min()-0.5, a.max()+0.5, 1);
1236}
1237*/
1238module.exports=G;
1239},{"./statistics":10}],6:[function(require,module,exports){
1240var I = {};
1241
1242I.gcd = function(a, b) {
1243 if (!b) return a;
1244 return I.gcd(b, a % b);
1245}
1246
1247I.lcm = function(a, b) {
1248 return (a * b) / gcd(a, b);
1249}
1250
1251I.isPrime=function(n) {
1252 for (var i=2; i<=Math.sqrt(n); i++)
1253 if (n%i===0) return false;
1254 return n%1===0;
1255}
1256
1257module.exports = I;
1258},{}],7:[function(require,module,exports){
1259// var M = require("./calculus");
1260var M = require("./geometry");
1261
1262module.exports=M;
1263
1264},{"./geometry":5}],8:[function(require,module,exports){
1265var N = require("numeric");
1266var M = require("./algebra");
1267// var M = N;
1268// Advance mathematics
1269M.ode=N.dopri; // dopri(x0,x1,y0,f,tol,maxit,event) #Ordinary Diff Eq
1270M.minimize=N.uncmin; // uncmin(f,x0,tol,gradient,maxit,callback,options) # Unconstrained optimization
1271M.sparse=N.ccsSparse; // Matrix => Sparse
1272M.sparse2full=N.ccsFull; // Sparse => Matrix
1273// M.complex=N.t;
1274// matrix
1275M.svd = N.svd;
1276M.det = N.det;
1277M.inv = N.inv;
1278M.lu = N.cLU;
1279M.luSolve = N.cLUsolve;
1280M.dot = N.dot;
1281M.rep = N.rep;
1282M.tr = N.transpose;
1283M.diag = N.diag;
1284M.mstr = M.strM = N.prettyPrint;
1285// M.sumM = N.sum;
1286M.rows=function(m) { return m.length; }
1287M.cols=function(m) { return m[0].length; }
1288M.row =function(m,i) { return m[i]; }
1289M.col =function(m,j) {
1290 var cols = m.cols();
1291 var c = M.vnew(cols);
1292 for (var i=0;i<cols;i++) {
1293 c[i] = m[i][j];
1294 }
1295 return c;
1296}
1297
1298M.newV = function(n, value) {
1299 return M.rep([n], value||0);
1300}
1301
1302M.newM = function(rows, cols, value) {
1303 return M.rep([rows, cols], value||0);
1304}
1305
1306M.randomV = function(n, a, b) {
1307 return N.random([n]).mul(b-a).add(a);
1308}
1309
1310M.randomM = function(rows, cols, a, b) {
1311 return N.random([rows, cols]).mul(b-a).add(a);
1312}
1313
1314M.rowSum = function(m) {
1315 var rows = M.rows(m);
1316 var s=M.newV(rows, 0);
1317 for (var i=0; i<rows; i++) {
1318 s[i] = m[i].sum();
1319 }
1320 return s;
1321}
1322
1323M.colSum = function(m) {
1324 var mt = M.tr(m);
1325 return M.rowSum(mt);
1326}
1327
1328M.rowMean = function(m) {
1329 return M.rowSum(m).div(m.cols());
1330}
1331
1332M.colMean = function(m) {
1333 return M.colSum(m).div(m.rows());
1334}
1335
1336M.addMV = function(m,v) {
1337 var result = [];
1338 for(var i=0;i<m.length;i++) {
1339 result.push(m[i].add(v));
1340 }
1341 return result;
1342}
1343
1344M.mapM = function(m, f) {
1345 var fm = M.clone(m);
1346 var rows = M.rows(m), cols=M.cols(m);
1347 for(i=0;i<rows;i++) {
1348 for(j=0;j<cols;j++)
1349 fm[i][j]=f(m[i][j]);
1350 }
1351 return fm;
1352}
1353
1354M.mapMM = function(m1,m2,f) {
1355 var fm = M.clone(m1);
1356 var rows = m1.rows(), cols=m1.cols();
1357 for(i=0;i<rows;i++) {
1358 for(j=0;j<cols;j++)
1359 fm[i][j]=f(m1[i][j],m2[i][j]);
1360 }
1361 return fm;
1362}
1363
1364M.flatM=function(m) {
1365 var a=[];
1366 var ai = 0;
1367 for (var i=0; i<m.length;i++)
1368 for (var j=0; j<m[i].length; j++)
1369 a[ai++] = m[i][j];
1370 return a;
1371}
1372
1373M.fillVM=function(v,rows,cols) {
1374 var m = M.newM(rows,cols);
1375 for (var r=0; r<rows; r++) {
1376 for (var c=0; c<cols; c++) {
1377 m[r][c] = v[r*cols+c];
1378 }
1379 }
1380 return m;
1381}
1382
1383M.fillMM=function(m,rows,cols) {
1384 var v = M.flatM(m);
1385 return M.fillVM(m,rows,cols);
1386}
1387
1388M.eig=function(m) {
1389 var E = N.eig(m);
1390 return {lambda:E.lambda.x, E:E.E.x};
1391}
1392
1393module.exports = M;
1394},{"./algebra":1,"numeric":16}],9:[function(require,module,exports){
1395var S = {}
1396var I = require("./integer");
1397
1398S.PI = Math.PI;
1399S.E = Math.E;
1400
1401extend = S.extend = Object.assign;
1402// ================= Rule =====================
1403var check = S.check = S.assert = function(cond, msg) {
1404 if (cond)
1405 console.log("O:"+msg);
1406 else {
1407 console.log("X:"+msg);
1408 if (S.throwError) throw Error('check fail!');
1409 }
1410}
1411
1412be = S.be =function(msg,cond) { return check(cond, msg) }
1413
1414S.proto=function(o) { return Object.getPrototypeOf(o) }
1415
1416// relation
1417var eq=S.eq=function(a,b) {
1418 return (typeof a === typeof b) && a.toString()===b.toString()
1419}
1420S.neq=function(a,b) { return !S.eq(a,b) }
1421S.leq=function(a,b) { return a<=b }
1422S.geq=function(a,b) { return a>=b }
1423S.lt =function(a,b) { return a<b }
1424S.gt =function(a,b) { return a>b }
1425
1426// ========= type checking =================
1427S.yes=function(a) { return true }
1428S.no=function(a) {return false }
1429S.isBool=function(a) {
1430 return typeof a === 'boolean' || a instanceof Boolean
1431}
1432S.isFunction=function(a) {
1433 return typeof a==='function' || a instanceof Function
1434}
1435S.isString=function(a) {
1436 return typeof a==='string' || a instanceof String
1437}
1438S.isObject=function(a) {
1439 return typeof a==='object' || a instanceof Object
1440}
1441S.isArray=function(a) {
1442 return a instanceof Array
1443}
1444S.isUndefined=function(a) {
1445 return typeof a === 'undefined'
1446}
1447S.isSet=function(a) {
1448 return a instanceof Set
1449}
1450S.isFloat=S.isNumber=function(a) {
1451 return typeof a === 'number' || a instanceof Number
1452}
1453S.isInteger=function(a) { return S.isFloat(a) && a%1===0 }
1454S.isZero=function(a) { return a===0 }
1455S.isPositive=function(a) { return a>0 }
1456S.isNegative=function(a) { return a<0 }
1457S.isEven=function(a) { return (S.isInteger(a) && a%2===0) }
1458S.isOdd=function(a) { return (S.isInteger(a) && a%2===1) }
1459
1460// ========== Random ==============
1461S.random=function(a,b) {
1462 return a+Math.random()*(b-a);
1463}
1464
1465S.randomInt=function(a,b) {
1466 return Math.floor(S.random(a,b));
1467}
1468
1469S.sample=function(a) {
1470 return a[S.randomInt(0,a.length)];
1471}
1472
1473// ========= Set ===================
1474Set.prototype.union = function(setB) {
1475 var union = new Set(this);
1476 for (var elem of setB) {
1477 union.add(elem);
1478 }
1479 return union;
1480}
1481
1482Set.prototype.intersection = function(setB) {
1483 var intersection = new Set();
1484 for (var elem of setB) {
1485 if (this.has(elem)) {
1486 intersection.add(elem);
1487 }
1488 }
1489 return intersection;
1490}
1491
1492Set.prototype.difference = function(setB) {
1493 var difference = new Set(this);
1494 for (var elem of setB) {
1495 difference.delete(elem);
1496 }
1497 return difference;
1498}
1499
1500Set.prototype.enumerate = function(n) {
1501 var array=[], values = this.values();
1502 for (var i=0; i<n; i++) {
1503 array.push(values.next().value);
1504 }
1505 return array;
1506}
1507
1508class EnumSet {
1509 constructor(enumHead) {
1510 this.set = new Set(enumHead);
1511 this.enumHead = S.isUndefined(enumHead)?[]:enumHead;
1512 }
1513 add(e) { this.set.add(e) }
1514 has(e) { return this.set.has(e) }
1515 sample(n) {
1516 if (S.isUndefined(n))
1517 return S.sample(this.enumHead);
1518 else {
1519 var a=[];
1520 for (var i=0; i<n; i++) a.push(this.sample());
1521 return a;
1522 }
1523 }
1524 enumerate() { return this.enumHead }
1525 intersection(y) {
1526 var x=this, xy=new EnumSet();
1527 xy.has=function(e) { return x.has(e)&&y.has(e) }
1528 return xy;
1529 }
1530 union(y) {
1531 var x=this, xy=new EnumSet();
1532 xy.has=function(e) { return x.has(e)||y.has(e) }
1533 return xy;
1534 }
1535 difference(y) {
1536 var x=this, xy=new EnumSet();
1537 xy.has=function(e) { return x.has(e)&&!y.has(e) }
1538 return xy;
1539 }
1540 symmetricDifference(y) {
1541 var x=this;
1542 return x.union(y).difference(x.intersection(y));
1543 }
1544 cartesianProduct(y) {
1545 var x=this, xy=new EnumSet();
1546 xy.has=function(e) { return x.has(e[0]) && y.has(e[1]) }
1547 return xy;
1548 }
1549}
1550
1551S.Set = EnumSet
1552
1553function steps(a,b,step) {
1554 var array=[];
1555 for (var i=a; i<=b; i+=step)
1556 array.push(i);
1557 return array;
1558}
1559
1560var enumFloat = [-3.2,-1, 0, 1, 2.3, 4.7];
1561var enumInt = [-10,-5,-1,0,1,3,5,6];
1562var enumN0 = steps(0,10,1);
1563var enumN1 = steps(1,10,1);
1564var enumOdd = steps(1,15,2);
1565var enumEven = steps(2,15,2);
1566var enumPrime = [2,3,5,7,11,13,17,19,23,29,31,37];
1567var enumAll = ["hi", 5, Math.PI, EnumSet, S.isBool, enumPrime, new Set() ];
1568
1569// 全體集合
1570S.All = new EnumSet(enumAll);
1571S.All.has = S.yes;
1572
1573// 空集合
1574S.Empty = new EnumSet([]);
1575S.Empty.has = S.no;
1576
1577// 浮點數集合
1578S.Float=new EnumSet(enumFloat);
1579S.Float.has=S.isFloat;
1580
1581// 整數集合
1582S.Z=S.Integer=new EnumSet(enumInt);
1583S.Z.has=S.isInteger;
1584
1585// 自然數集合 N0
1586S.N0=new EnumSet(enumN0);
1587S.N0.has=(e)=>S.isInteger(e)&&e>=0;
1588
1589// 自然數集合 N1
1590S.N1=new EnumSet(enumN1);
1591S.N1.has=(e)=>S.isInteger(e)&&e>1;
1592
1593// 偶數集合
1594S.Even=new EnumSet(enumEven);
1595S.Even.has=S.isEven;
1596
1597// 奇數集合
1598S.Odd=new EnumSet(enumOdd);
1599S.Odd.has=S.isOdd;
1600
1601// 質數集合
1602S.Prime=new EnumSet(enumPrime)
1603S.Prime.has=I.isPrime;
1604
1605// 有限集合 0...n-1
1606S.Finite=(n)=>new EnumSet(steps(0,n-1,1));
1607
1608// 羅素集合悖論
1609S.RussellSet=new EnumSet(enumAll);
1610S.RussellSet.has=function(e) { return !e.has(e) }
1611
1612module.exports=S;
1613
1614},{"./integer":6}],10:[function(require,module,exports){
1615var B = require('./base');
1616var J = require('jStat').jStat;
1617var S = require('./calculus');
1618var ncall = B.ncall;
1619// var T, R;
1620
1621// ========== 離散分佈的 r, q 函數 ============
1622S.qcdf=function(cdf, q, N, p) {
1623 for (var i=0; i<=N; i++) {
1624 if (cdf(i, N, p) > q) return i;
1625 }
1626 return N;
1627}
1628
1629S.rcdf=function(cdf, n, N, p) {
1630 var a = [];
1631 for (var i=0; i<n; i++) {
1632 var q = Math.random();
1633 a.push(cdf(q, N, p));
1634 }
1635 return a;
1636}
1637
1638S.EPSILON=0.0000000001;
1639// 均等分布 : jStat.uniform( a, b )
1640S.dunif=(x,a=0,b=1)=>J.uniform.pdf(x,a,b);
1641S.punif=(q,a=0,b=1)=>J.uniform.cdf(q,a,b);
1642S.qunif=(p,a=0,b=1)=>J.uniform.inv(p,a,b);
1643S.runif=(n,a=0,b=1)=>ncall(n, J.uniform, 'sample', a, b);
1644// 常態分布 : jStat.normal( mean, sd )
1645S.dnorm=(x,mean=0,sd=1)=>J.normal.pdf(x,mean,sd);
1646S.pnorm=(q,mean=0,sd=1)=>J.normal.cdf(q,mean,sd);
1647S.qnorm=(p,mean=0,sd=1)=>J.normal.inv(p,mean,sd);
1648S.rnorm=(n,mean=0,sd=1)=>ncall(n, J.normal, 'sample', mean, sd);
1649// F 分布 : jStat.centralF( df1, df2 )
1650S.df=(x,df1,df2)=>J.centralF.pdf(x,df1,df2);
1651S.pf=(q,df1,df2)=>J.centralF.cdf(q,df1,df2);
1652S.qf=(p,df1,df2)=>J.centralF.inv(p,df1,df2);
1653S.rf=(n,df1,df2)=>ncall(n, J.centralF, 'sample', df1, df2);
1654// T 分布 : jStat.studentt( dof )
1655S.dt=(x,dof)=>J.studentt.pdf(x,dof);
1656S.pt=(q,dof)=>J.studentt.cdf(q,dof);
1657S.qt=(p,dof)=>J.studentt.inv(p,dof);
1658S.rt=(n,dof)=>ncall(n, J.studentt, 'sample', dof);
1659// Beta 分布 : jStat.beta( alpha, beta )
1660S.dbeta=(x,alpha,beta)=>J.beta.pdf(x,alpha,beta);
1661S.pbeta=(q,alpha,beta)=>J.beta.cdf(q,alpha,beta);
1662S.qbeta=(p,alpha,beta)=>J.beta.inv(p,alpha,beta);
1663S.rbeta=(n,alpha,beta)=>ncalls(n, J.beta, 'sample', alpha, beta);
1664// 柯西分布 : jStat.cauchy( local, scale )
1665S.dcauchy=(x,local,scale)=>J.cauchy.pdf(x,local,scale);
1666S.pcauchy=(q,local,scale)=>J.cauchy.cdf(q,local,scale);
1667S.qcauchy=(p,local,scale)=>J.cauchy.inv(q,local,scale);
1668S.rcauchy=(n,local,scale)=>ncall(n, J.cauchy, 'sample', local, scale);
1669// chisquare 分布 : jStat.chisquare( dof )
1670S.dchisq=(x,dof)=>J.chisquare.pdf(x,dof);
1671S.pchisq=(q,dof)=>J.chisquare.cdf(q,dof);
1672S.qchisq=(p,dof)=>J.chisquare.inv(p,dof);
1673S.rchisq=(n,dof)=>ncall(n, J.chisquare, 'sample', dof);
1674// 指數分布 : jStat.exponential( rate )
1675S.dexp=(x,rate)=>J.exponential.pdf(x,rate);
1676S.pexp=(q,rate)=>J.exponential.cdf(q,rate);
1677S.qexp=(p,rate)=>J.exponential.inv(p,rate);
1678S.rexp=(n,rate)=>ncall(n, J.exponential, 'sample', rate);
1679// Gamma 分布 : jStat.gamma( shape, scale )
1680S.dgamma=(x,shape,scale)=>J.gamma.pdf(x,shape,scale);
1681S.pgamma=(q,shape,scale)=>J.gamma.cdf(q,shape,scale);
1682S.qgamma=(p,shape,scale)=>J.gamma.inv(p,shape,scale);
1683S.rgamma=(n,shape,scale)=>ncall(n, J.gamma, 'sample', shape, scale);
1684// 反 Gamma 分布 : jStat.invgamma( shape, scale )
1685S.rinvgamma=(n,shape,scale)=>ncall(n, J.invgamma, 'sample', shape, scale);
1686S.dinvgamma=(x,shape,scale)=>J.invgamma.pdf(x,shape,scale);
1687S.pinvgamma=(q,shape,scale)=>J.invgamma.cdf(q,shape,scale);
1688S.qinvgamma=(p,shape,scale)=>J.invgamma.inv(p,shape,scale);
1689// 對數常態分布 : jStat.lognormal( mu, sigma )
1690S.dlognormal=(n, mu, sigma)=>J.lognormal.pdf(x,sigma);
1691S.plognormal=(n, mu, sigma)=>J.lognormal.cdf(q,sigma);
1692S.qlognormal=(n, mu, sigma)=>J.lognormal.inv(p,sigma);
1693S.rlognormal=(n, mu, sigma)=>ncall(n, J.dlognormal, 'sample', mu, sigma);
1694// Pareto 分布 : jStat.pareto( scale, shape )
1695S.dpareto=(n, scale, shape)=>J.pareto.pdf(x,scale,shape);
1696S.ppareto=(n, scale, shape)=>J.pareto.cdf(q,scale,shape);
1697S.qpareto=(n, scale, shape)=>J.pareto.inv(p,scale,shape);
1698S.rpareto=(n, scale, shape)=>ncall(n, J.pareto, 'sample', scale, shape);
1699// Weibull 分布 jStat.weibull(scale, shape)
1700S.dweibull=(n, scale, shape)=>J.weibull.pdf(x,scale,shape);
1701S.pweibull=(n, scale, shape)=>J.weibull.cdf(q,scale,shape);
1702S.qweibull=(n, scale, shape)=>J.weibull.inv(p,scale,shape);
1703S.rweibull=(n, scale, shape)=>ncall(n, J.weibull, 'sample', scale, shape);
1704// 三角分布 : jStat.triangular(a, b, c)
1705S.dtriangular=(n, a, b, c)=>J.triangular.pdf(x,a,b,c);
1706S.ptriangular=(n, a, b, c)=>J.triangular.cdf(q,a,b,c);
1707S.qtriangular=(n, a, b, c)=>J.triangular.inv(p,a,b,c);
1708S.rtriangular=(n, a, b, c)=>ncall(n, J.triangular, 'sample', a, b, c);
1709// 類似 Beta 分布,但計算更簡單 : jStat.kumaraswamy(alpha, beta)
1710S.dkumaraswamy=(n, alpha, beta)=>J.kumaraswamy.pdf(x,alpha,beta);
1711S.pkumaraswamy=(n, alpha, beta)=>J.kumaraswamy.cdf(q,alpha,beta);
1712S.qkumaraswamy=(n, alpha, beta)=>J.kumaraswamy.inv(p,alpha,beta);
1713S.rkumaraswamy=(n, alpha, beta)=>ncalls(n, J.kumaraswamy, 'sample', alpha, beta);
1714
1715// ========== 離散分佈的 r, q 函數 ============
1716// 二項分布 : jStat.binomial(n, p0)
1717S.dbinom=(x, size, prob)=>J.binomial.pdf(x, size, prob);
1718S.pbinom=(q, size, prob)=>J.binomial.cdf(q, size, prob);
1719S.qbinom=(p, size, prob)=>S.qcdf(S.pbinom, p, size, prob);
1720S.rbinom=(n, size, prob)=>S.rcdf(S.qbinom, n, size, prob);
1721// 負二項分布 : jStat.negbin(r, p)
1722S.dnbinom=(x, size, prob)=>J.negbin.pdf(x, size, prob);
1723S.pnbinom=(q, size, prob)=>J.negbin.cdf(q, size, prob);
1724S.qnbinom=(p, size, prob)=>S.qcdf(S.pnbinom, p, size, prob);
1725S.rnbinom=(n, size, prob)=>S.rcdf(S.qnbinom, n, size, prob);
1726// 超幾何分布 : jStat.hypgeom(N, m, n)
1727S.dhyper=(x, m, n, k)=>J.hypgeom.pdf(k, m, n, k);
1728S.phyper=(q, m, n, k)=>J.hypgeom.cdf(q, m, n, k);
1729S.qhyper=(p, m, n, k)=>S.qcdf(S.phyper, p, m, n, k);
1730S.rhyper=(nn,m, n, k)=>S.rcdf(S.qhyper, nn, m, n, k);
1731// 布瓦松分布 : jStat.poisson(l)
1732S.dpois=(x, lambda)=>J.poisson.pdf(x, lambda);
1733S.ppois=(q, lambda)=>J.poisson.cdf(q, lambda);
1734S.qpois=(p, lambda)=>S.qcdf(S.ppois, p, lambda);
1735S.rpois=(n, lambda)=>S.rcdf(S.qpois, n, lambda);
1736
1737// ====================== statistics =================================
1738// extend function
1739
1740S.normalize=function(a) {
1741 var sum = S.sum(a);
1742 return a.map(function(x) { return x/sum});
1743}
1744
1745// Vector Functionality
1746B.copyFunctions(S, J, "sumsqrt,sumsqerr,sumrow,mean,meansqerr,geomean,median,cumsum,cumprod,diff,mode,range,variance,stdev,meandev,meddev,skewness,kurtosis,coeffvar,quartiles,quantiles,percentile,percentileOfScore,histogram,covariance,corrcoeff,calcRdx,betafn,betacf,ibetainv,ibeta,gammafn,gammaln,gammap,lowRegGamma,gammapinv,factorialln,factorial,combination,combinationln,permutation,erf,erfc,erfcinv,randn,randg".split(","));
1747
1748B.mapFunctions(S, J, {
1749 C:'combination',// C(n,m)
1750 choose:'combination',// C(n,m)
1751 lchoose:'combinationln',// log C(n,m)
1752 P:'permutation', // P(n,m)
1753 sd:'stdev',
1754 cov:'covariance',
1755 cor:'corrcoeff',
1756});
1757
1758// =============== 檢定 ==============================
1759B.mix(S, B);
1760
1761var T = S;
1762
1763T.test = function(o) { // name, D, x, mu, sd, y, alpha, op
1764 Object.assign(o, {alpha:0.05, op:"="});
1765 var alpha = o.alpha;
1766 var pvalue, interval;
1767 var D = o.D;
1768 var q1 = D.o2q(o); // 單尾檢定的 pvalue
1769
1770 if (o.op === "=") {
1771 if (q1>0.5) q1 = 1-q1; // (q1>0.5) 取右尾,否則取左尾。
1772 pvalue= 2*q1; // 對稱情況:雙尾檢定的 p 值是單尾的兩倍。
1773 interval = [D.q2p(alpha/2, o, "L"), D.q2p(1-alpha/2, o, "R")];
1774 } else {
1775 if (o.op === "<") { // 右尾檢定 H0: q < 1-alpha,
1776 interval = [ D.q2p(alpha, o, "L"), Infinity ];
1777 pvalue = 1-q1;
1778 }
1779 if (o.op === ">") { // 左尾檢定 H0: q > alpha
1780 interval=[-Infinity, D.q2p(1-alpha, o, "R")];
1781 pvalue = q1;
1782 }
1783 }
1784 return {
1785 name: o.name,
1786 h: D.h(o),
1787 alpha: alpha,
1788 op: o.op,
1789 pvalue: pvalue,
1790 ci : interval,
1791 df : D.df(o),
1792 report: function() { S.report(this) }
1793 };
1794}
1795
1796T.report = function(o) {
1797 console.log("=========== report ==========");
1798 for (var k in o) {
1799 if (typeof o[k] !== "function")
1800 console.log(k+"\t: "+S.str(o[k]));
1801 }
1802}
1803
1804var t1 = { // 單樣本 T 檢定 t = (X-mu)/(S/sqrt(n))
1805 h:function(o) { return "H0:mu"+o.op+o.mu; },
1806 o2q:function(o) {
1807 var x = o.x, n = x.length;
1808 var t = (S.mean(x)-o.mu)/(S.sd(x)/Math.sqrt(n));
1809 return S.pt(t, n-1);
1810 },
1811 // P(X-mu/(S/sqrt(n))<t) = q ; 信賴區間 P(T<q)
1812 // P(mu > X-t*S/sqrt(n)) = q ; 這反而成了右尾檢定,所以左尾與右尾確實會反過來
1813 q2p:function(q, o) {
1814 var x = o.x, n = x.length;
1815 return S.mean(x) + S.qt(q, n-1) * S.sd(x) / Math.sqrt(n);
1816 },
1817 df:function(o) { return o.x.length-1; }
1818}
1819
1820var t2vareq = { // σ1=σ2, 合併 T 檢定 (雙樣本)
1821 h:function(o) { return "H0:mu1"+o.op+"mu2" },
1822 // S^2 = (n1-1)*S1^2+(n2-1)*S2^2)/(n1-1+n2-1)
1823 sd:function(o) {
1824 var x = o.x, n1 = x.length, y=o.y, n2=y.length;
1825 var S1= S.sd(x), S2 = S.sd(y);
1826 var S = Math.sqrt(((n1-1)*S1*S1+(n2-1)*S2*S2)/(n1-1+n2-1));
1827 return S;
1828 },
1829 // T = ((X-Y)-(mu1-mu2))/(sqrt(1/n1+1/n2)*S)
1830 o2q:function(o) {
1831 var x = o.x, n1 = x.length, y=o.y, n2=y.length;
1832 var S = this.sd(o);
1833 var t = (S.mean(x)-S.mean(y)-o.mu)/(Math.sqrt(1/n1+1/n2)*S);
1834 return S.pt(t, n1+n2-2);
1835 },
1836 // t=((X-Y)-mu)/(sqrt(1/n1+1/n2)*S), (X-Y)-t*sqrt(1/n1+1/n2)*S = mu
1837 q2p:function(q, o) {
1838 var x = o.x, n1 = x.length, y=o.y, n2=y.length;
1839 var S = this.sd(o);
1840 return S.mean(x)-S.mean(y)+ S.qt(q, n1+n2-2)*Math.sqrt(1/n1+1/n2)*S;
1841 },
1842 df:function(o) {
1843 var x = o.x, n1 = x.length, y=o.y, n2=y.length;
1844 return n1+n2-2;
1845 }
1846}
1847
1848var t2paired = { // 成對 T 檢定 T = (X-Y-mu)/(S/sqrt(n)) (雙樣本)
1849 h:function(o) { return "H0:mu1"+o.op+"mu2" },
1850 sd:function(o) { // S = sd(x-y)
1851 var x = o.x, n = x.length, y=o.y;
1852 var S= S.sd(S.sub(x,y));
1853 return S;
1854 },
1855 o2q:function(o) {
1856 var x = o.x, n = x.length, y=o.y;
1857 var S = this.sd(o);
1858 var t = (S.mean(S.sub(x,y))-o.mu)/(S/Math.sqrt(n));
1859 return S.pt(t, n-1);
1860 },
1861 // mean(x-y)+t*S/sqrt(n)
1862 q2p:function(q, o) {
1863 var x = o.x, n = x.length, y=o.y;
1864 var S = this.sd(o);
1865 return S.mean(S.sub(x,y))+ S.qt(q, n-1)*S/Math.sqrt(n);
1866 },
1867 df:function(o) {
1868 return o.x.length-1;
1869 }
1870}
1871
1872var t2varneq = { // σ1≠σ2, Welch's t test (雙樣本) (又稱 Smith-Satterwaite 程序)
1873// 參考:http://en.wikipedia.org/wiki/Welch's_t_test
1874 h:function(o) { return "H0:mu1"+o.op+"mu2" },
1875 // T = ((X-Y)-(mu1-mu2))/sqrt(S1^2/n1+S2^2/n2)
1876 o2q:function(o) {
1877 var x = o.x, n1 = x.length, y=o.y, n2=y.length;
1878 var S1 = S.sd(x), S2=S.sd(y);
1879 var t = (S.mean(x)-S.mean(y)-o.mu)/Math.sqrt(S1*S1/n1+S2*S2/n2);
1880 return S.pt(t, this.df(o));
1881 },
1882 // t=((X-Y)-mu)/sqrt(S1^2/n1+S2^2/n2), (X-Y)-t*sqrt(S1^2/n1+S2^2/n2) = mu
1883 q2p:function(q, o) {
1884 var x = o.x, n1 = x.length, y=o.y, n2=y.length;
1885 var S1 = S.sd(x), S2=S.sd(y);
1886 return S.mean(x)-S.mean(y)+ S.qt(q, this.df(o))*Math.sqrt(S1*S1/n1+S2*S2/n2);
1887 },
1888 df:function(o) {
1889 var x = o.x, n1 = x.length, y=o.y, n2=y.length;
1890 var S1 = S.sd(x), S2=S.sd(y);
1891 var Sn1 = S1*S1/n1, Sn2 = S2*S2/n2, Sn12 = Sn1+Sn2;
1892 var df = (Sn12*Sn12)/((Sn1*Sn1)/(n1-1)+(Sn2*Sn2)/(n2-1));
1893 return df;
1894 }
1895}
1896
1897T.ttest = function(o) {
1898 var t;
1899 if (typeof o.y === "undefined") {
1900 o.name = "ttest(X)";
1901 o.D = t1;
1902 t = T.test(o);
1903 t.mean = S.mean(o.x);
1904 t.sd = S.sd(o.x);
1905 } else {
1906 var varequal = o.varequal || false;
1907 var paired = o.paired || false;
1908 if (varequal) {
1909 o.name = "ttest(X,Y,mu="+o.mu+",varequal=true) (pooled)";
1910 o.D = t2vareq;
1911 t = T.test(o);
1912 } else if (paired) {
1913 o.name = "ttest(x,y,mu="+o.mu+",paired=true)";
1914 o.D = t2paired;
1915 t = T.test(o);
1916 t.mean = "mean(x-y)="+S.str(S.mean(S.sub(o.x, o.y)));
1917 t.sd = "sd(x-y)="+S.str(S.sd(S.sub(o.x, o.y)));
1918 } else {
1919 o.name = "ttest(x,y,mu="+o.mu+",varequal=false), Welch t-test";
1920 o.D = t2varneq;
1921 t = T.test(o);
1922 }
1923 if (typeof t.mean === "undefined") {
1924 t.mean = "mean(x)="+S.str(S.mean(o.x))+" mean(y)="+S.str(S.mean(o.y));
1925 t.sd = "sd(x)="+S.str(S.sd(o.x))+" sd(y)="+S.str(S.sd(o.y));
1926 }
1927 }
1928 return t;
1929}
1930
1931var f2 = { // 檢定 σ1/σ2 = 1?
1932 h:function(o) { return "H0:σ1/σ2"+o.op+"1"; },
1933 // F = S1^2/S2^2
1934 o2q:function(o) {
1935 var x = o.x, n1 = x.length, y=o.y, n2=y.length;
1936 var S1 = S.sd(x), S2=S.sd(y);
1937 var f = (S1*S1)/(S2*S2);
1938 var pf = S.pf(f, n1-1, n2-1);
1939 return pf;
1940 },
1941 // 信賴區間公式: S1^2/(S2^2*F(1-α/2), S1^2/(S2^2*F(α/2))
1942 // 也就是要用 S1^2/(S2^2*f(1-q)) ,參考 R 軟體、應用統計方法 (陳景祥) 389 頁。
1943 q2p:function(q, o) {
1944 var x = o.x, n1 = x.length, y=o.y, n2=y.length;
1945 var S1 = S.sd(x), S2=S.sd(y);
1946 var qf = S.qf(1-q, n1-1, n2-1);
1947 return (S1*S1)/(S2*S2*qf);
1948 },
1949 df:function(o) {
1950 var x = o.x, n1 = x.length, y=o.y, n2=y.length;
1951 return [n1-1, n2-1];
1952 }
1953}
1954
1955T.ftest = function(o) {
1956 o.name = "ftest(X, Y)";
1957 o.D = f2;
1958 var t = T.test(o);
1959 var rsd = S.sd(o.x)/S.sd(o.y);
1960 t.ratio = (rsd*rsd);
1961 return t;
1962}
1963
1964// R 軟體沒有此函數,測試請看湯銀才 143 頁
1965var chisq1 = { // 檢定 σ1 = σ ?
1966 h:function(o) { return "H0:σ1"+o.op+"σ"; },
1967 // χ(n-1) = (n-1)S^2/σ^2
1968 o2q:function(o) {
1969 var x = o.x, n = x.length, S=S.sd(x);
1970 var v = (n-1)*S*S/(o.sd*o.sd);
1971 return S.pchisq(v, n-1);
1972 },
1973 // 信賴區間公式: (n-1)S^2/χ^2(1-q),參考 R 語言與統計分析 (湯銀才) 142 頁。
1974 q2p:function(q, o) {
1975 var x = o.x, n = x.length, S=S.sd(x);
1976 return (n-1)*S*S/S.qchisq(1-q, n-1);
1977 },
1978 df:function(o) {
1979 var x = o.x, n = x.length;
1980 return n-1;
1981 }
1982}
1983
1984T.chisqtest = function(o) {
1985 o.name = "chisqtest(X)";
1986 o.D = chisq1;
1987 return T.test(o);
1988}
1989
1990T.vartest = function(o) {
1991 if (typeof o.y === "undefined")
1992 return S.chisqtest(o);
1993 else
1994 return S.ftest(o);
1995}
1996
1997var z1 = { // 單樣本 Z 檢定
1998 h:function(o) { return "H0:mu"+o.op+o.mu+" when sd="+o.sd; },
1999 o2q:function(o) {
2000 var x = o.x, n = x.length;
2001 var z = (S.mean(x)-o.mu)/(o.sd/Math.sqrt(n)); // z=(X-mu)/(sd/sqrt(n))
2002 return S.pnorm(z, 0, 1);
2003 },
2004 q2p:function(q, o) {
2005 var x = o.x, n = x.length;
2006 return S.mean(x) + S.qnorm(q, 0, 1) * S.sd(x) / Math.sqrt(n);
2007 },
2008 df:function(o) { return o.x.length; }
2009}
2010
2011T.ztest = function(o) {
2012 o.name = "ztest(X)";
2013 o.D = z1;
2014 return T.test(o);
2015}
2016
2017var zprop1 = { // 比例的檢定, n 較大時的近似解 o={ x, n, p } // x 為數值,n 個中出現 x 個 1
2018 h:function(o) { return "H0:p"+o.op+o.p; },
2019 // Z = (p1-p)/sqrt(p(1-p)/n)
2020 o2q:function(o) {
2021 var x=o.x, n=o.n, p1=x/n, p=o.p||p1;
2022 var z = (p1-p)/Math.sqrt(p*(1-p)/n);
2023 return S.pnorm(z, 0, 1);
2024 },
2025 // 信賴區間公式: p1+z*sqrt(p1*(1-p1)/n),參考 R 語言與統計分析 (湯銀才) 149 頁。
2026 q2p:function(q, o) {
2027 var x=o.x, n=o.n, p1=x/n, p=p1;
2028 var z = S.qnorm(q, 0, 1);
2029 var z22n = z*z/(2*n);
2030 return (p1+z22n+z*Math.sqrt( p*(1-p)/n + z22n/(2*n) ))/(1+2*z22n); // R 的版本,比較複雜的估計公式
2031// return p1+z*Math.sqrt(p*(1-p)/n); // 語言與統計分析 (湯銀才) 149 頁的版本。
2032 },
2033 df:function(o) { return 1; }
2034}
2035
2036var zprop2 = { // 比例的檢定, n 較大時的近似解 o={ x, y, n1, n2 }
2037 h:function(o) { return "H0:p1-p2"+o.op+o.p; },
2038 // Z = (p1-p2)/sqrt(p*(1-p)*(1/n1+1/n2)), p = (n1p1+n2p2)/(n1+n2),參考 R 語言與統計分析 (湯銀才) 175 頁。
2039 o2q:function(o) {
2040 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);
2041 var z = (p1-p2)/Math.sqrt(p*(1-p)*(1/n1+1/n2));
2042 return S.pnorm(z, 0, 1);
2043 },
2044 // 信賴區間公式: p1-p2+z*sqrt(p*(1-p)*(1/n1+1/n2));
2045 q2p:function(q, o) {
2046 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);
2047 var z = S.qnorm(q, 0, 1);
2048 return p1-p2+z*Math.sqrt(p*(1-p)*(1/n1+1/n2));
2049 },
2050 df:function(o) { return 1; }
2051}
2052
2053/* 在 prop.test.R 當中,雙邊檢定的 pvalue 是用 pchisq, 單邊才是用 z ,為何呢? ( 但是信賴區間則是全部用 z)
2054 if (alternative == "two.sided")
2055 PVAL <- pchisq(STATISTIC, PARAMETER, lower.tail = FALSE)
2056 else {
2057 if (k == 1)
2058 z <- sign(ESTIMATE - p) * sqrt(STATISTIC)
2059 else
2060 z <- sign(DELTA) * sqrt(STATISTIC)
2061 PVAL <- pnorm(z, lower.tail = (alternative == "less"))
2062 }
2063*/
2064
2065T.proptest = function(o) {
2066 o.p = o.p || 0.5;
2067 o.name = "proptest("+S.str(o)+")";
2068 o.correct = o.correct|| false;
2069 if (o.correct) {
2070 o.name += ", binomtest";
2071 o.D += binom1;
2072 } else {
2073 if (typeof o.y === "undefined") {
2074 o.name += ", zprop1";
2075 o.D = zprop1;
2076 } else {
2077 o.p = 0; // p1-p2 = 0
2078 o.name += ", zprop2";
2079 o.D = zprop2;
2080 }
2081 }
2082 var t=T.test(o);
2083 if (typeof o.y === "undefined")
2084 t.p = o.x/o.n;
2085 else
2086 t.p = [o.x/o.n1, o.y/o.n2];
2087 return t;
2088}
2089
2090// 參考: https://github.com/SurajGupta/r-source/blob/master/src/library/stats/R/binom.test.R
2091var binom1 = { // 比例的檢定, n 較大時的近似解 o={ x, n, p } // x 為數值,n 個中出現 x 個 1
2092 h:function(o) { return "H0:p"+o.op+o.p; },
2093
2094 // Z = C(n, k)*p1^k*(1-p1)^(n-k), CDF(z: from 1 to x)
2095 o2q:function(o) {
2096 var x=o.x, n=o.n, p = o.p, q;
2097 var dx = S.dbinom(x, n, p);
2098 if (o.op === "=") { // 雙尾檢定,去雙尾後 / 2
2099 var q = 0;
2100 for (var i=0; i<=n; i++) {
2101 var di = S.dbinom(i, n, p);
2102 if (di > dx+1e-5) q += di; // 為何 x 本身不算,如果算應該用 di > dx-1e-5 才對。
2103 }
2104 q=1-((1-q)/2); // 因為 test 會 * 2 所進行的減半調整
2105 } else { // 單尾檢定
2106 if (Math.abs(x - n*p)<1e-5) // 正確預測, q=1
2107 q = 1;
2108 else {
2109 if (o.op === ">")
2110 q = S.pbinom(x, n, p); // 去右尾
2111 else // op=== "<"
2112 q = S.pbinom(x-1, n, p); // 去右尾
2113 }
2114 }
2115 return q;
2116 },
2117/* 注意上述 R 原始碼另一尾的計算方式,是用 < pbinom(最接近 x 者) 的算法,而不是直接 * 2。 問題是我們在 test 中是直接用*2 的方式。
2118 d <- dbinom(x, n, p)
2119 ...
2120 else if (x < m) {
2121 i <- seq.int(from = ceiling(m), to = n)
2122 y <- sum(dbinom(i, n, p) <= d * relErr)
2123 pbinom(x, n, p) 左尾 + pbinom(n - y, n, p, lower.tail = FALSE) 右尾
2124 } else {
2125 i <- seq.int(from = 0, to = floor(m))
2126 y <- sum(dbinom(i, n, p) <= d * relErr)
2127 pbinom(y - 1, n, p) 左尾 + pbinom(x - 1, n, p, lower.tail = FALSE) 右尾
2128 }
2129*/
2130 // 信賴區間公式: P(T>c) = Σ (n, i) C(n, i) p1^i (1-p1)^(n-i) for i>c < q
2131
2132 q2p:function(q, o, side) {
2133 var x=o.x, n=o.n, p=o.p, op=o.op;
2134 if (side === "L")
2135 return S.qbeta(q, x, n - x + 1); // 這裏採用 qbeta 是 R 的作法; 直覺上應該採用 S.qbinom(q, n, p);
2136 else
2137 return S.qbeta(q, x + 1, n - x);
2138 },
2139 df:function(o) { return 1; }
2140}
2141
2142T.binomtest = function(o) {
2143 o.p = o.p || 0.5;
2144 o.name = "binomtest("+S.str(o)+")";
2145 o.D = binom1;
2146 var t=T.test(o);
2147 t.p = o.x/o.n;
2148 t.ci[0]=(o.op === ">")?0:t.ci[0];
2149 t.ci[1]=(o.op === "<")?1:t.ci[1];
2150 return t;
2151}
2152
2153// anova f-test : array1, array2, array3, ...
2154T.anovaftest = function() {
2155 return {
2156 h0 : "σ1=σ2=...=σ"+arguments.length,
2157 pvalue: J.anovaftest(),
2158 score: J.anovafscore(),
2159 };
2160}
2161
2162module.exports = S;
2163
2164},{"./base":2,"./calculus":3,"jStat":14}],11:[function(require,module,exports){
2165var Symbol = require('algebrite')
2166
2167module.exports = Symbol;
2168},{"algebrite":12}],12:[function(require,module,exports){
2169// Generated by CoffeeScript 1.10.0
2170(function() {
2171 var $, ABS, ADD, ADJ, AND, ARCCOS, ARCCOSH, ARCSIN, ARCSINH, ARCTAN, ARCTANH, ARG, ATOMIZE, AUTOEXPAND, BAKE, BESSELJ, BESSELY, BINDING, BINOMIAL, BINOM_check_args, BUF, C1, C2, C3, C4, C5, C6, CEILING, CHECK, CHOOSE, CIRCEXP, CLEAR, CLOCK, COEFF, COFACTOR, CONDENSE, CONJ, CONS, CONTRACT, COS, COSH, Condense, DEBUG, DECOMP, DEFINT, DEGREE, DENOMINATOR, DERIVATIVE, DET, DET_check_arg, DIM, DIRAC, DISPLAY, DIVISORS, DO, DOT, DOUBLE, DRAW, DRAWX, DSOLVE, E, EIGEN, EIGENVAL, EIGENVEC, EIG_N, EIG_check_arg, EIG_yydd, EIG_yyqq, ERF, ERFC, EVAL, EXP, EXPAND, EXPCOS, EXPSIN, Eval, Eval_Eval, Eval_abs, Eval_add, Eval_adj, Eval_and, Eval_arccos, Eval_arccosh, Eval_arcsin, Eval_arcsinh, Eval_arctan, Eval_arctanh, Eval_arg, Eval_besselj, Eval_bessely, Eval_binding, Eval_binomial, Eval_ceiling, Eval_check, Eval_choose, Eval_circexp, Eval_clear, Eval_clock, Eval_coeff, Eval_cofactor, Eval_condense, Eval_conj, Eval_cons, Eval_contract, Eval_cos, Eval_cosh, Eval_decomp, Eval_defint, Eval_degree, Eval_denominator, Eval_derivative, Eval_det, Eval_dim, Eval_dirac, Eval_divisors, Eval_do, Eval_dsolve, Eval_eigen, Eval_eigenval, Eval_eigenvec, Eval_erf, Eval_erfc, Eval_exp, Eval_expand, Eval_expcos, Eval_expsin, Eval_factor, Eval_factorial, Eval_factorpoly, Eval_filter, Eval_float, Eval_floor, Eval_for, Eval_gamma, Eval_gcd, Eval_hermite, Eval_hilbert, Eval_imag, Eval_index, Eval_inner, Eval_integral, Eval_inv, Eval_invg, Eval_isinteger, Eval_isprime, Eval_laguerre, Eval_lcm, Eval_leading, Eval_legendre, Eval_log, Eval_mag, Eval_mod, Eval_multiply, Eval_noexpand, Eval_not, Eval_nroots, Eval_number, Eval_numerator, Eval_operator, Eval_or, Eval_outer, Eval_polar, Eval_power, Eval_predicate, Eval_prime, Eval_print, Eval_product, Eval_quote, Eval_quotient, Eval_rank, Eval_rationalize, Eval_real, Eval_rect, Eval_roots, Eval_setq, Eval_sgn, Eval_shape, Eval_simfac, Eval_simplify, Eval_sin, Eval_sinh, Eval_sqrt, Eval_stop, Eval_subst, Eval_sym, Eval_tan, Eval_tanh, Eval_taylor, Eval_tensor, Eval_test, Eval_testeq, Eval_testge, Eval_testgt, Eval_testle, Eval_testlt, Eval_transpose, Eval_unit, Eval_user_function, Eval_zero, Evalpoly, FACTOR, FACTORIAL, FACTORPOLY, FILTER, FLOATF, FLOOR, FOR, Find, GAMMA, GCD, HERMITE, HILBERT, IMAG, INDEX, INNER, INTEGRAL, INV, INVG, INV_check_arg, INV_decomp, ISINTEGER, ISPRIME, LAGUERRE, LAST, LCM, LEADING, LEGENDRE, LOG, M, MAG, MAXDIM, MAXPRIMETAB, MAX_PROGRAM_SIZE, MEQUAL, METAA, METAB, METAX, MLENGTH, MOD, MP_MAX_FREE, MP_MIN_SIZE, MSIGN, MULTIPLY, MZERO, N, NIL, NOT, NROOTS, NROOTS_ABS, NROOTS_DELTA, NROOTS_EPSILON, NROOTS_RANDOM, NROOTS_YMAX, NROOTS_divpoly, NSYM, NUM, NUMBER, NUMERATOR, OPERATOR, OR, OUTER, PI, POLAR, POWER, PRIME, PRINT, PRINTOUTRESULT, PRODUCT, QUOTE, QUOTIENT, RANK, RATIONALIZE, REAL, ROOTS, SECRETX, SELFTEST, SETQ, SGN, SHAPE, SIMPLIFY, SIN, SINH, SPACE_BETWEEN_COLUMNS, SPACE_BETWEEN_ROWS, SQRT, STOP, STR, SUBST, SUM, SYM, SYMBOL_A, SYMBOL_B, SYMBOL_C, SYMBOL_D, SYMBOL_I, SYMBOL_J, SYMBOL_N, SYMBOL_R, SYMBOL_S, SYMBOL_T, SYMBOL_X, SYMBOL_Y, SYMBOL_Z, TAN, TANH, TAYLOR, TENSOR, TEST, TESTEQ, TESTGE, TESTGT, TESTLE, TESTLT, TOS, TRACE, TRANSPOSE, TTY, T_DOUBLE, T_EQ, T_FUNCTION, T_GTEQ, T_INTEGER, T_LTEQ, T_NEWLINE, T_STRING, T_SYMBOL, U, UNIT, USR_SYMBOLS, YMAX, YYE, YYRECT, ZERO, __emit_char, __emit_str, __factor_add, __factorial, __is_negative, __is_radical_number, __lcm, __legendre, __legendre2, __legendre3, __normalize_radical_factors, __rationalize_tensor, absval, absval_tensor, ac, ad, add, add_all, add_numbers, add_terms, addf, adj, alloc_tensor, allocatedId, any_denominators, arccos, arccosh, arcsin, arcsinh, arctan, arctanh, arg, arglist, bake, bake_poly, bake_poly_term, besselj, bessely, bigInt, bignum_factorial, bignum_float, bignum_power_number, bignum_scan_float, bignum_scan_integer, bignum_truncate, binding, binomial, buffer, build_tensor, caaddr, caadr, caar, cadaddr, cadadr, cadar, caddaddr, caddadr, caddar, caddddr, cadddr, caddr, cadr, car, cdaddr, cdadr, cdar, cddaddr, cddar, cdddaddr, cddddr, cdddr, cddr, cdr, ceiling, charTabIndex, chartab, check_esc_flag, check_stack, choose, choose_check_args, circexp, clear, clear_symbols, clear_term, clockform, cmpGlyphs, cmp_args, cmp_expr, cmp_terms, cmp_terms_count, coeff, cofactor, collectResultLine, combine_factors, combine_gammas, combine_terms, compare_numbers, compare_rationals, compare_tensors, compatible, compute_fa, conjugate, cons, consCount, contract, convert_bignum_to_double, convert_rational_to_double, copy_tensor, cosine, cosine_of_angle, cosine_of_angle_sum, count, count_denominators, counter, d_scalar_scalar, d_scalar_scalar_1, d_scalar_tensor, d_tensor_scalar, d_tensor_tensor, dabs, darccos, darccosh, darcsin, darcsinh, darctan, darctanh, dbesselj0, dbesseljn, dbessely0, dbesselyn, dcos, dcosh, dd, decomp, decomp_product, decomp_sum, define_user_function, defn, defn_str, degree, denominator, derf, derfc, derivative, derivative_of_integral, det, determinant, detg, dfunction, dhermite, dirac, display, display_flag, displaychar, divide, divide_numbers, divisors, divisors_onstack, divpoly, dlog, doubleToReasonableString, dpow, dpower, dproduct, draw_flag, draw_stop_return, dsgn, dsin, dsinh, dsum, dtan, dtanh, dupl, echo_input, eigen, elelmIndex, elem, emit_denominator, emit_denominators, emit_expr, emit_factor, emit_factorial_function, emit_flat_tensor, emit_fraction, emit_function, emit_index_function, emit_multiply, emit_number, emit_numerators, emit_numerical_fraction, emit_power, emit_string, emit_subexpr, emit_symbol, emit_tensor, emit_tensor_inner, emit_term, emit_top_expr, emit_unsigned_expr, emit_x, equal, equaln, equalq, erfc, errorMessage, esc_flag, exec, expand, expand_get_A, expand_get_AF, expand_get_B, expand_get_C, expand_get_CF, expand_tensor, expanding, expcos, exponential, expr_level, expsin, f1, f2, f3, f4, f5, f9, f_equals_a, factor, factor_a, factor_again, factor_b, factor_number, factor_small_number, factor_term, factorial, factorpoly, factors, factpoly_expo, fill_buf, filter, filter_main, filter_sum, filter_tensor, findroot, fixed_top_level_eval, fixup_fraction, fixup_power, flag, fmt_index, fmt_level, fmt_x, frame, free_stack, gamma, gamma_of_sum, gammaf, gcd, gcd_expr, gcd_expr_expr, gcd_factor_term, gcd_main, gcd_numbers, gcd_term_factor, gcd_term_term, gen, get_arglist, get_binding, get_factor, get_next_token, get_printname, get_size, get_token, getdisplaystr, glyph, gp, guess, hasImaginaryCoeff, hermite, hilbert, imag, imaginaryunit, index_function, init, initNRoots, inited, inner, inner_f, input_str, integral, integral_of_form, integral_of_product, integral_of_sum, inv, inverse, invert_number, invg, is_denominator, is_factor, is_small_integer, is_square_matrix, isadd, isalnum, isalpha, iscomplexnumber, iscons, isdenominator, isdigit, isdouble, iseveninteger, isfactor, isfactorial, isfloating, isfraction, isimaginarynumber, isimaginaryunit, isinteger, isintegerfactor, iskeyword, isminusone, isminusoneoversqrttwo, ismultiply, isnegative, isnegativenumber, isnegativeterm, isnonnegativeinteger, isnpi, isnum, isoneover, isoneoversqrttwo, isplusone, ispoly, ispoly_expr, ispoly_factor, ispoly_term, isposint, ispower, isquarterturn, isrational, isspace, isstr, issymbol, issymbolic, istensor, iszero, itab, laguerre, laguerre2, lcm, leading, legendre, length, lessp, level, list, logarithm, logbuf, lookupsTotal, lu_decomp, madd, mag, makePositive, makeSignSameAs, mask, mcmp, mcmpint, mdiv, mdivrem, meta_mode, mgcd, mini_solve, mint, mmod, mmul, mod, monic, move, mp_clr_bit, mp_denominator, mp_numerator, mp_set_bit, mpow, mprime, mroot, mshiftright, msub, mtotal, multinomial_sum, multiply, multiply_all, multiply_all_noexpand, multiply_denominators, multiply_denominators_factor, multiply_denominators_term, multiply_noexpand, multiply_numbers, n_factor_number, negate, negate_expand, negate_noexpand, negate_number, new_string, newline_flag, nil_symbols, normalize_angle, nroots_a, nroots_b, nroots_c, nroots_df, nroots_dx, nroots_fa, nroots_fb, nroots_x, nroots_y, nterms, numerator, numericRootOfPolynomial, o, one, oneElement, out_buf, out_count, out_of_memory, outer, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, parse, parse_internal, parse_p1, parse_p2, partition, peek, peek2, polar, polycoeff, polyform, pop, pop_double, pop_frame, pop_integer, power, power_str, power_sum, power_tensor, prime, primetab, print1, print_a_over_b, print_char, print_denom, print_double, print_expr, print_factor, print_factorial_function, print_it, print_multiply_sign, print_number, print_str, print_subexpr, print_tensor, print_tensor_inner, print_term, printchar, printchar_nowrap, printline, program_buf, promote_tensor, push, push_cars, push_double, push_factor, push_frame, push_identity_matrix, push_integer, push_rational, push_symbol, push_term_factors, push_terms, push_zero_matrix, qadd, qdiv, qmul, qpow, qpowf, quickfactor, quickpower, rational, rationalize, rationalize_coefficients, real, reciprocate, rect, ref, ref1, remove_negative_exponents, reset_after_error, restore, rewrite_args, rewrite_args_tensor, roots, roots2, roots3, run, save, scalar_times_tensor, scan, scan_error, scan_expression, scan_factor, scan_function_call, scan_meta, scan_power, scan_relation, scan_stmt, scan_str, scan_string, scan_subexpr, scan_symbol, scan_term, scanned, setM, setSignTo, set_binding, set_binding_and_arglist, set_component, setq_indexed, sfac_product, sfac_product_f, sgn, shape, sign, sign_of_term, simfac, simfac_term, simplify, simplify_main, simplify_polar, simplify_tensor, simplify_trig, simplifyfactorials, sine, sine_of_angle, sine_of_angle_sum, sort_stack, square, ssqrt, stack, stackAddsCount, std_symbol, step, step2, stop, strcmp, stringToBePrinted, subf, subst, subtract, subtract_numbers, swap, symbol, symnum, symtab, tangent, taylor, tensor, tensor_plus_tensor, tensor_times_scalar, test_flag, text_metric, theRandom, token, token_buf, token_str, top_level_eval, tos, transform, transpose, trigmode, trivial_divide, try_kth_prime, ucmp, unique, unique_f, update_token_buf, usr_symbol, verbosing, will_be_displayed_as_fraction, ybinomial, ycosh, ydirac, yerf, yerfc, yfloor, yindex, ysinh, yyarg, yybesselj, yybessely, yyceiling, yycondense, yycontract, yycosh, yydegree, yydetg, yydivpoly, yyerf, yyerfc, yyexpand, yyfactorpoly, yyfloat, yyfloor, yyhermite, yyhermite2, yyinvg, yylcm, yylog, yymag, yymultiply, yyouter, yypower, yyrationalize, yysgn, yysimfac, yysinh, yytangent, zero,
2172 slice = [].slice;
2173
2174 bigInt = require('big-integer');
2175
2176 SELFTEST = 1;
2177
2178 NSYM = 1000;
2179
2180 DEBUG = false;
2181
2182 PRINTOUTRESULT = false;
2183
2184 rational = (function() {
2185 function rational() {}
2186
2187 rational.prototype.a = null;
2188
2189 rational.prototype.b = null;
2190
2191 return rational;
2192
2193 })();
2194
2195 U = (function() {
2196 U.prototype.cons = null;
2197
2198 U.prototype.printname = "";
2199
2200 U.prototype.str = "";
2201
2202 U.prototype.tensor = null;
2203
2204 U.prototype.q = null;
2205
2206 U.prototype.d = 0.0;
2207
2208 U.prototype.k = 0;
2209
2210 U.prototype.tag = 0;
2211
2212 U.prototype.toString = function() {
2213 return collectResultLine(this);
2214 };
2215
2216 function U() {
2217 this.cons = {};
2218 this.cons.car = null;
2219 this.cons.cdr = null;
2220 this.q = new rational();
2221 }
2222
2223 return U;
2224
2225 })();
2226
2227 errorMessage = "";
2228
2229 CONS = 0;
2230
2231 NUM = 1;
2232
2233 DOUBLE = 2;
2234
2235 STR = 3;
2236
2237 TENSOR = 4;
2238
2239 SYM = 5;
2240
2241 counter = 0;
2242
2243 ABS = counter++;
2244
2245 ADD = counter++;
2246
2247 ADJ = counter++;
2248
2249 AND = counter++;
2250
2251 ARCCOS = counter++;
2252
2253 ARCCOSH = counter++;
2254
2255 ARCSIN = counter++;
2256
2257 ARCSINH = counter++;
2258
2259 ARCTAN = counter++;
2260
2261 ARCTANH = counter++;
2262
2263 ARG = counter++;
2264
2265 ATOMIZE = counter++;
2266
2267 BESSELJ = counter++;
2268
2269 BESSELY = counter++;
2270
2271 BINDING = counter++;
2272
2273 BINOMIAL = counter++;
2274
2275 CEILING = counter++;
2276
2277 CHECK = counter++;
2278
2279 CHOOSE = counter++;
2280
2281 CIRCEXP = counter++;
2282
2283 CLEAR = counter++;
2284
2285 CLOCK = counter++;
2286
2287 COEFF = counter++;
2288
2289 COFACTOR = counter++;
2290
2291 CONDENSE = counter++;
2292
2293 CONJ = counter++;
2294
2295 CONTRACT = counter++;
2296
2297 COS = counter++;
2298
2299 COSH = counter++;
2300
2301 DECOMP = counter++;
2302
2303 DEFINT = counter++;
2304
2305 DEGREE = counter++;
2306
2307 DENOMINATOR = counter++;
2308
2309 DERIVATIVE = counter++;
2310
2311 DET = counter++;
2312
2313 DIM = counter++;
2314
2315 DIRAC = counter++;
2316
2317 DISPLAY = counter++;
2318
2319 DIVISORS = counter++;
2320
2321 DO = counter++;
2322
2323 DOT = counter++;
2324
2325 DRAW = counter++;
2326
2327 DSOLVE = counter++;
2328
2329 EIGEN = counter++;
2330
2331 EIGENVAL = counter++;
2332
2333 EIGENVEC = counter++;
2334
2335 ERF = counter++;
2336
2337 ERFC = counter++;
2338
2339 EVAL = counter++;
2340
2341 EXP = counter++;
2342
2343 EXPAND = counter++;
2344
2345 EXPCOS = counter++;
2346
2347 EXPSIN = counter++;
2348
2349 FACTOR = counter++;
2350
2351 FACTORIAL = counter++;
2352
2353 FACTORPOLY = counter++;
2354
2355 FILTER = counter++;
2356
2357 FLOATF = counter++;
2358
2359 FLOOR = counter++;
2360
2361 FOR = counter++;
2362
2363 GAMMA = counter++;
2364
2365 GCD = counter++;
2366
2367 HERMITE = counter++;
2368
2369 HILBERT = counter++;
2370
2371 IMAG = counter++;
2372
2373 INDEX = counter++;
2374
2375 INNER = counter++;
2376
2377 INTEGRAL = counter++;
2378
2379 INV = counter++;
2380
2381 INVG = counter++;
2382
2383 ISINTEGER = counter++;
2384
2385 ISPRIME = counter++;
2386
2387 LAGUERRE = counter++;
2388
2389 LCM = counter++;
2390
2391 LEADING = counter++;
2392
2393 LEGENDRE = counter++;
2394
2395 LOG = counter++;
2396
2397 MAG = counter++;
2398
2399 MOD = counter++;
2400
2401 MULTIPLY = counter++;
2402
2403 NOT = counter++;
2404
2405 NROOTS = counter++;
2406
2407 NUMBER = counter++;
2408
2409 NUMERATOR = counter++;
2410
2411 OPERATOR = counter++;
2412
2413 OR = counter++;
2414
2415 OUTER = counter++;
2416
2417 POLAR = counter++;
2418
2419 POWER = counter++;
2420
2421 PRIME = counter++;
2422
2423 PRINT = counter++;
2424
2425 PRODUCT = counter++;
2426
2427 QUOTE = counter++;
2428
2429 QUOTIENT = counter++;
2430
2431 RANK = counter++;
2432
2433 RATIONALIZE = counter++;
2434
2435 REAL = counter++;
2436
2437 YYRECT = counter++;
2438
2439 ROOTS = counter++;
2440
2441 SETQ = counter++;
2442
2443 SGN = counter++;
2444
2445 SIMPLIFY = counter++;
2446
2447 SIN = counter++;
2448
2449 SINH = counter++;
2450
2451 SHAPE = counter++;
2452
2453 SQRT = counter++;
2454
2455 STOP = counter++;
2456
2457 SUBST = counter++;
2458
2459 SUM = counter++;
2460
2461 TAN = counter++;
2462
2463 TANH = counter++;
2464
2465 TAYLOR = counter++;
2466
2467 TEST = counter++;
2468
2469 TESTEQ = counter++;
2470
2471 TESTGE = counter++;
2472
2473 TESTGT = counter++;
2474
2475 TESTLE = counter++;
2476
2477 TESTLT = counter++;
2478
2479 TRANSPOSE = counter++;
2480
2481 UNIT = counter++;
2482
2483 ZERO = counter++;
2484
2485 NIL = counter++;
2486
2487 AUTOEXPAND = counter++;
2488
2489 BAKE = counter++;
2490
2491 LAST = counter++;
2492
2493 TRACE = counter++;
2494
2495 TTY = counter++;
2496
2497 YYE = counter++;
2498
2499 DRAWX = counter++;
2500
2501 METAA = counter++;
2502
2503 METAB = counter++;
2504
2505 METAX = counter++;
2506
2507 SECRETX = counter++;
2508
2509 PI = counter++;
2510
2511 SYMBOL_A = counter++;
2512
2513 SYMBOL_B = counter++;
2514
2515 SYMBOL_C = counter++;
2516
2517 SYMBOL_D = counter++;
2518
2519 SYMBOL_I = counter++;
2520
2521 SYMBOL_J = counter++;
2522
2523 SYMBOL_N = counter++;
2524
2525 SYMBOL_R = counter++;
2526
2527 SYMBOL_S = counter++;
2528
2529 SYMBOL_T = counter++;
2530
2531 SYMBOL_X = counter++;
2532
2533 SYMBOL_Y = counter++;
2534
2535 SYMBOL_Z = counter++;
2536
2537 C1 = counter++;
2538
2539 C2 = counter++;
2540
2541 C3 = counter++;
2542
2543 C4 = counter++;
2544
2545 C5 = counter++;
2546
2547 C6 = counter++;
2548
2549 USR_SYMBOLS = counter++;
2550
2551 E = YYE;
2552
2553 TOS = 100000;
2554
2555 BUF = 10000;
2556
2557 MAX_PROGRAM_SIZE = 100001;
2558
2559 MAXPRIMETAB = 10000;
2560
2561 MAXDIM = 24;
2562
2563 tensor = (function() {
2564 tensor.prototype.ndim = 0;
2565
2566 tensor.prototype.dim = null;
2567
2568 tensor.prototype.nelem = 0;
2569
2570 tensor.prototype.elem = null;
2571
2572 function tensor() {
2573 this.dim = (function() {
2574 var o, ref, results;
2575 results = [];
2576 for (o = 0, ref = MAXDIM; 0 <= ref ? o <= ref : o >= ref; 0 <= ref ? o++ : o--) {
2577 results.push(0);
2578 }
2579 return results;
2580 })();
2581 this.elem = [];
2582 }
2583
2584 return tensor;
2585
2586 })();
2587
2588 display = (function() {
2589 function display() {}
2590
2591 display.prototype.h = 0;
2592
2593 display.prototype.w = 0;
2594
2595 display.prototype.n = 0;
2596
2597 display.prototype.a = [];
2598
2599 return display;
2600
2601 })();
2602
2603 text_metric = (function() {
2604 function text_metric() {}
2605
2606 text_metric.prototype.ascent = 0;
2607
2608 text_metric.prototype.descent = 0;
2609
2610 text_metric.prototype.width = 0;
2611
2612 return text_metric;
2613
2614 })();
2615
2616 tos = 0;
2617
2618 expanding = 0;
2619
2620 fmt_x = 0;
2621
2622 fmt_index = 0;
2623
2624 fmt_level = 0;
2625
2626 verbosing = 0;
2627
2628 primetab = (function() {
2629 var ceil, i, j, primes;
2630 primes = [2];
2631 i = 3;
2632 while (primes.length < MAXPRIMETAB) {
2633 j = 0;
2634 ceil = Math.sqrt(i);
2635 while (j < primes.length && primes[j] <= ceil) {
2636 if (i % primes[j] === 0) {
2637 j = -1;
2638 break;
2639 }
2640 j++;
2641 }
2642 if (j !== -1) {
2643 primes.push(i);
2644 }
2645 i += 2;
2646 }
2647 primes[MAXPRIMETAB] = 0;
2648 return primes;
2649 })();
2650
2651 esc_flag = 0;
2652
2653 draw_flag = 0;
2654
2655 mtotal = 0;
2656
2657 trigmode = 0;
2658
2659 logbuf = "";
2660
2661 program_buf = "";
2662
2663 symtab = [];
2664
2665 binding = [];
2666
2667 arglist = [];
2668
2669 stack = [];
2670
2671 frame = 0;
2672
2673 p0 = null;
2674
2675 p1 = null;
2676
2677 p2 = null;
2678
2679 p3 = null;
2680
2681 p4 = null;
2682
2683 p5 = null;
2684
2685 p6 = null;
2686
2687 p7 = null;
2688
2689 p8 = null;
2690
2691 p9 = null;
2692
2693 zero = null;
2694
2695 one = null;
2696
2697 imaginaryunit = null;
2698
2699 symtab = [];
2700
2701 out_buf = "";
2702
2703 out_count = 0;
2704
2705 test_flag = 0;
2706
2707 draw_stop_return = null;
2708
2709 symbol = function(x) {
2710 return symtab[x];
2711 };
2712
2713 iscons = function(p) {
2714 return p.k === CONS;
2715 };
2716
2717 isrational = function(p) {
2718 return p.k === NUM;
2719 };
2720
2721 isdouble = function(p) {
2722 return p.k === DOUBLE;
2723 };
2724
2725 isnum = function(p) {
2726 return isrational(p) || isdouble(p);
2727 };
2728
2729 isstr = function(p) {
2730 return p.k === STR;
2731 };
2732
2733 istensor = function(p) {
2734 if (p == null) {
2735 debugger;
2736 } else {
2737 return p.k === TENSOR;
2738 }
2739 };
2740
2741 issymbol = function(p) {
2742 return p.k === SYM;
2743 };
2744
2745 iskeyword = function(p) {
2746 return issymbol(p) && symnum(p) < NIL;
2747 };
2748
2749 car = function(p) {
2750 if (iscons(p)) {
2751 return p.cons.car;
2752 } else {
2753 return symbol(NIL);
2754 }
2755 };
2756
2757 cdr = function(p) {
2758 if (iscons(p)) {
2759 return p.cons.cdr;
2760 } else {
2761 return symbol(NIL);
2762 }
2763 };
2764
2765 caar = function(p) {
2766 return car(car(p));
2767 };
2768
2769 cadr = function(p) {
2770 return car(cdr(p));
2771 };
2772
2773 cdar = function(p) {
2774 return cdr(car(p));
2775 };
2776
2777 cddr = function(p) {
2778 return cdr(cdr(p));
2779 };
2780
2781 caadr = function(p) {
2782 return car(car(cdr(p)));
2783 };
2784
2785 caddr = function(p) {
2786 return car(cdr(cdr(p)));
2787 };
2788
2789 cadar = function(p) {
2790 return car(cdr(car(p)));
2791 };
2792
2793 cdadr = function(p) {
2794 return cdr(car(cdr(p)));
2795 };
2796
2797 cddar = function(p) {
2798 return cdr(cdr(car(p)));
2799 };
2800
2801 cdddr = function(p) {
2802 return cdr(cdr(cdr(p)));
2803 };
2804
2805 caaddr = function(p) {
2806 return car(car(cdr(cdr(p))));
2807 };
2808
2809 cadadr = function(p) {
2810 return car(cdr(car(cdr(p))));
2811 };
2812
2813 caddar = function(p) {
2814 return car(cdr(cdr(car(p))));
2815 };
2816
2817 cdaddr = function(p) {
2818 return cdr(car(cdr(cdr(p))));
2819 };
2820
2821 cadddr = function(p) {
2822 return car(cdr(cdr(cdr(p))));
2823 };
2824
2825 cddddr = function(p) {
2826 return cdr(cdr(cdr(cdr(p))));
2827 };
2828
2829 caddddr = function(p) {
2830 return car(cdr(cdr(cdr(cdr(p)))));
2831 };
2832
2833 cadaddr = function(p) {
2834 return car(cdr(car(cdr(cdr(p)))));
2835 };
2836
2837 cddaddr = function(p) {
2838 return cdr(cdr(car(cdr(cdr(p)))));
2839 };
2840
2841 caddadr = function(p) {
2842 return car(cdr(cdr(car(cdr(p)))));
2843 };
2844
2845 cdddaddr = function(p) {
2846 return cdr(cdr(cdr(car(cdr(cdr(p))))));
2847 };
2848
2849 caddaddr = function(p) {
2850 return car(cdr(cdr(car(cdr(cdr(p))))));
2851 };
2852
2853 isadd = function(p) {
2854 return car(p) === symbol(ADD);
2855 };
2856
2857 ismultiply = function(p) {
2858 return car(p) === symbol(MULTIPLY);
2859 };
2860
2861 ispower = function(p) {
2862 return car(p) === symbol(POWER);
2863 };
2864
2865 isfactorial = function(p) {
2866 return car(p) === symbol(FACTORIAL);
2867 };
2868
2869 MSIGN = function(p) {
2870 if (p.isPositive()) {
2871 return 1;
2872 } else if (p.isZero()) {
2873 return 0;
2874 } else {
2875 return -1;
2876 }
2877 };
2878
2879 MLENGTH = function(p) {
2880 return p.toString().length;
2881 };
2882
2883 MZERO = function(p) {
2884 return p.isZero();
2885 };
2886
2887 MEQUAL = function(p, n) {
2888 if (p == null) {
2889 debugger;
2890 }
2891 return p.equals(n);
2892 };
2893
2894 $ = typeof exports !== "undefined" && exports !== null ? exports : this;
2895
2896 $.isadd = isadd;
2897
2898 $.ismultiply = ismultiply;
2899
2900 $.ispower = ispower;
2901
2902 $.isfactorial = isfactorial;
2903
2904 $.car = car;
2905
2906 $.cdr = cdr;
2907
2908 $.caar = caar;
2909
2910 $.cadr = cadr;
2911
2912 $.cdar = cdar;
2913
2914 $.cddr = cddr;
2915
2916 $.caadr = caadr;
2917
2918 $.caddr = caddr;
2919
2920 $.cadar = cadar;
2921
2922 $.cdadr = cdadr;
2923
2924 $.cddar = cddar;
2925
2926 $.cdddr = cdddr;
2927
2928 $.caaddr = caaddr;
2929
2930 $.cadadr = cadadr;
2931
2932 $.caddar = caddar;
2933
2934 $.cdaddr = cdaddr;
2935
2936 $.cadddr = cadddr;
2937
2938 $.cddddr = cddddr;
2939
2940 $.caddddr = caddddr;
2941
2942 $.cadaddr = cadaddr;
2943
2944 $.cddaddr = cddaddr;
2945
2946 $.caddadr = caddadr;
2947
2948 $.cdddaddr = cdddaddr;
2949
2950 $.caddaddr = caddaddr;
2951
2952 $.symbol = symbol;
2953
2954 $.iscons = iscons;
2955
2956 $.isrational = isrational;
2957
2958 $.isdouble = isdouble;
2959
2960 $.isnum = isnum;
2961
2962 $.isstr = isstr;
2963
2964 $.istensor = istensor;
2965
2966 $.issymbol = issymbol;
2967
2968 $.iskeyword = iskeyword;
2969
2970 $.CONS = CONS;
2971
2972 $.NUM = NUM;
2973
2974 $.DOUBLE = DOUBLE;
2975
2976 $.STR = STR;
2977
2978 $.TENSOR = TENSOR;
2979
2980 $.SYM = SYM;
2981
2982 Eval_abs = function() {
2983 push(cadr(p1));
2984 Eval();
2985 return absval();
2986 };
2987
2988 absval = function() {
2989 var h;
2990 h = 0;
2991 save();
2992 p1 = pop();
2993 if (istensor(p1)) {
2994 absval_tensor();
2995 restore();
2996 return;
2997 }
2998 if (isnum(p1)) {
2999 push(p1);
3000 if (isnegativenumber(p1)) {
3001 negate();
3002 }
3003 restore();
3004 return;
3005 }
3006 if (iscomplexnumber(p1)) {
3007 push(p1);
3008 push(p1);
3009 conjugate();
3010 multiply();
3011 push_rational(1, 2);
3012 power();
3013 restore();
3014 return;
3015 }
3016 if (car(p1) === symbol(POWER) && isnegativeterm(caddr(p1))) {
3017 push(p1);
3018 reciprocate();
3019 absval();
3020 reciprocate();
3021 restore();
3022 return;
3023 }
3024 if (car(p1) === symbol(MULTIPLY)) {
3025 h = tos;
3026 p1 = cdr(p1);
3027 while (iscons(p1)) {
3028 push(car(p1));
3029 absval();
3030 p1 = cdr(p1);
3031 }
3032 multiply_all(tos - h);
3033 restore();
3034 return;
3035 }
3036 if (isnegativeterm(p1) || (car(p1) === symbol(ADD) && isnegativeterm(cadr(p1)))) {
3037 push(p1);
3038 negate();
3039 p1 = pop();
3040 }
3041 push_symbol(ABS);
3042 push(p1);
3043 list(2);
3044 return restore();
3045 };
3046
3047 absval_tensor = function() {
3048 if (p1.tensor.ndim !== 1) {
3049 stop("abs(tensor) with tensor rank > 1");
3050 }
3051 push(p1);
3052 push(p1);
3053 conjugate();
3054 inner();
3055 push_rational(1, 2);
3056 power();
3057 simplify();
3058 return Eval();
3059 };
3060
3061
3062 /*
3063 Symbolic addition
3064
3065 Terms in a sum are combined if they are identical modulo rational
3066 coefficients.
3067
3068 For example, A + 2A becomes 3A.
3069
3070 However, the sum A + sqrt(2) A is not modified.
3071
3072 Combining terms can lead to second-order effects.
3073
3074 For example, consider the case of
3075
3076 1/sqrt(2) A + 3/sqrt(2) A + sqrt(2) A
3077
3078 The first two terms are combined to yield 2 sqrt(2) A.
3079
3080 This result can now be combined with the third term to yield
3081
3082 3 sqrt(2) A
3083 */
3084
3085 flag = 0;
3086
3087 Eval_add = function() {
3088 var h;
3089 h = tos;
3090 p1 = cdr(p1);
3091 while (iscons(p1)) {
3092 push(car(p1));
3093 Eval();
3094 p2 = pop();
3095 push_terms(p2);
3096 p1 = cdr(p1);
3097 }
3098 return add_terms(tos - h);
3099 };
3100
3101 stackAddsCount = 0;
3102
3103 add_terms = function(n) {
3104 var ac, ad, h, i, o, ref, ref1, results, s, subsetOfStack;
3105 stackAddsCount++;
3106 i = 0;
3107 h = tos - n;
3108 s = h;
3109 if (DEBUG) {
3110 console.log("stack before adding terms #" + stackAddsCount);
3111 }
3112 if (DEBUG) {
3113 for (i = o = 0, ref = tos; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
3114 print1(stack[i]);
3115 }
3116 }
3117 for (i = ac = 0; ac < 10; i = ++ac) {
3118 if (n < 2) {
3119 break;
3120 }
3121 flag = 0;
3122 subsetOfStack = stack.slice(h, h + n);
3123 subsetOfStack.sort(cmp_terms);
3124 stack = stack.slice(0, h).concat(subsetOfStack).concat(stack.slice(h + n));
3125 if (flag === 0) {
3126 break;
3127 }
3128 n = combine_terms(h, n);
3129 }
3130 tos = h + n;
3131 switch (n) {
3132 case 0:
3133 push_integer(0);
3134 break;
3135 case 1:
3136 break;
3137 default:
3138 list(n);
3139 p1 = pop();
3140 push_symbol(ADD);
3141 push(p1);
3142 cons();
3143 }
3144 if (DEBUG) {
3145 console.log("stack after adding terms #" + stackAddsCount);
3146 }
3147 if (DEBUG) {
3148 results = [];
3149 for (i = ad = 0, ref1 = tos; 0 <= ref1 ? ad < ref1 : ad > ref1; i = 0 <= ref1 ? ++ad : --ad) {
3150 results.push(print1(stack[i]));
3151 }
3152 return results;
3153 }
3154 };
3155
3156 cmp_terms_count = 0;
3157
3158 cmp_terms = function(p1, p2) {
3159 var i, o, ref, t;
3160 cmp_terms_count++;
3161 i = 0;
3162 if (isnum(p1) && isnum(p2)) {
3163 flag = 1;
3164 return 0;
3165 }
3166 if (istensor(p1) && istensor(p2)) {
3167 if (p1.tensor.ndim < p2.tensor.ndim) {
3168 return -1;
3169 }
3170 if (p1.tensor.ndim > p2.tensor.ndim) {
3171 return 1;
3172 }
3173 for (i = o = 0, ref = p1.tensor.ndim; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
3174 if (p1.tensor.dim[i] < p2.tensor.dim[i]) {
3175 return -1;
3176 }
3177 if (p1.tensor.dim[i] > p2.tensor.dim[i]) {
3178 return 1;
3179 }
3180 }
3181 flag = 1;
3182 return 0;
3183 }
3184 if (car(p1) === symbol(MULTIPLY)) {
3185 p1 = cdr(p1);
3186 if (isnum(car(p1))) {
3187 p1 = cdr(p1);
3188 if (cdr(p1) === symbol(NIL)) {
3189 p1 = car(p1);
3190 }
3191 }
3192 }
3193 if (car(p2) === symbol(MULTIPLY)) {
3194 p2 = cdr(p2);
3195 if (isnum(car(p2))) {
3196 p2 = cdr(p2);
3197 if (cdr(p2) === symbol(NIL)) {
3198 p2 = car(p2);
3199 }
3200 }
3201 }
3202 t = cmp_expr(p1, p2);
3203 if (t === 0) {
3204 flag = 1;
3205 }
3206 return t;
3207 };
3208
3209
3210 /*
3211 Compare adjacent terms in s[] and combine if possible.
3212
3213 Returns the number of terms remaining in s[].
3214
3215 n number of terms in s[] initially
3216 */
3217
3218 combine_terms = function(s, n) {
3219 var ac, ad, ae, af, i, j, o, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, t;
3220 i = 0;
3221 while (i < (n - 1)) {
3222 check_esc_flag();
3223 p3 = stack[s + i];
3224 p4 = stack[s + i + 1];
3225 if (istensor(p3) && istensor(p4)) {
3226 push(p3);
3227 push(p4);
3228 tensor_plus_tensor();
3229 p1 = pop();
3230 if (p1 !== symbol(NIL)) {
3231 stack[s + i] = p1;
3232 for (j = o = ref = i + 1, ref1 = n - 1; ref <= ref1 ? o < ref1 : o > ref1; j = ref <= ref1 ? ++o : --o) {
3233 stack[s + j] = stack[s + j + 1];
3234 }
3235 n--;
3236 i--;
3237 }
3238 i++;
3239 continue;
3240 }
3241 if (istensor(p3) || istensor(p4)) {
3242 i++;
3243 continue;
3244 }
3245 if (isnum(p3) && isnum(p4)) {
3246 push(p3);
3247 push(p4);
3248 add_numbers();
3249 p1 = pop();
3250 if (iszero(p1)) {
3251 for (j = ac = ref2 = i, ref3 = n - 2; ref2 <= ref3 ? ac < ref3 : ac > ref3; j = ref2 <= ref3 ? ++ac : --ac) {
3252 stack[s + j] = stack[s + j + 2];
3253 }
3254 n -= 2;
3255 } else {
3256 stack[s + i] = p1;
3257 for (j = ad = ref4 = i + 1, ref5 = n - 1; ref4 <= ref5 ? ad < ref5 : ad > ref5; j = ref4 <= ref5 ? ++ad : --ad) {
3258 stack[s + j] = stack[s + j + 1];
3259 }
3260 n--;
3261 }
3262 i--;
3263 i++;
3264 continue;
3265 }
3266 if (isnum(p3) || isnum(p4)) {
3267 i++;
3268 continue;
3269 }
3270 p1 = one;
3271 p2 = one;
3272 t = 0;
3273 if (car(p3) === symbol(MULTIPLY)) {
3274 p3 = cdr(p3);
3275 t = 1;
3276 if (isnum(car(p3))) {
3277 p1 = car(p3);
3278 p3 = cdr(p3);
3279 if (cdr(p3) === symbol(NIL)) {
3280 p3 = car(p3);
3281 t = 0;
3282 }
3283 }
3284 }
3285 if (car(p4) === symbol(MULTIPLY)) {
3286 p4 = cdr(p4);
3287 if (isnum(car(p4))) {
3288 p2 = car(p4);
3289 p4 = cdr(p4);
3290 if (cdr(p4) === symbol(NIL)) {
3291 p4 = car(p4);
3292 }
3293 }
3294 }
3295 if (!equal(p3, p4)) {
3296 i++;
3297 continue;
3298 }
3299 push(p1);
3300 push(p2);
3301 add_numbers();
3302 p1 = pop();
3303 if (iszero(p1)) {
3304 for (j = ae = ref6 = i, ref7 = n - 2; ref6 <= ref7 ? ae < ref7 : ae > ref7; j = ref6 <= ref7 ? ++ae : --ae) {
3305 stack[s + j] = stack[s + j + 2];
3306 }
3307 n -= 2;
3308 i--;
3309 i++;
3310 continue;
3311 }
3312 push(p1);
3313 if (t) {
3314 push(symbol(MULTIPLY));
3315 push(p3);
3316 cons();
3317 } else {
3318 push(p3);
3319 }
3320 multiply();
3321 stack[s + i] = pop();
3322 for (j = af = ref8 = i + 1, ref9 = n - 1; ref8 <= ref9 ? af < ref9 : af > ref9; j = ref8 <= ref9 ? ++af : --af) {
3323 stack[s + j] = stack[s + j + 1];
3324 }
3325 n--;
3326 i--;
3327 i++;
3328 }
3329 return n;
3330 };
3331
3332 push_terms = function(p) {
3333 var results;
3334 if (car(p) === symbol(ADD)) {
3335 p = cdr(p);
3336 results = [];
3337 while (iscons(p)) {
3338 push(car(p));
3339 results.push(p = cdr(p));
3340 }
3341 return results;
3342 } else if (!iszero(p)) {
3343 return push(p);
3344 }
3345 };
3346
3347 add = function() {
3348 var h;
3349 save();
3350 p2 = pop();
3351 p1 = pop();
3352 h = tos;
3353 push_terms(p1);
3354 push_terms(p2);
3355 add_terms(tos - h);
3356 return restore();
3357 };
3358
3359 add_all = function(k) {
3360 var h, i, o, ref, s;
3361 i = 0;
3362 save();
3363 s = tos - k;
3364 h = tos;
3365 for (i = o = 0, ref = k; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
3366 push_terms(stack[s + i]);
3367 }
3368 add_terms(tos - h);
3369 p1 = pop();
3370 tos -= k;
3371 push(p1);
3372 return restore();
3373 };
3374
3375 subtract = function() {
3376 negate();
3377 return add();
3378 };
3379
3380 Eval_adj = function() {
3381 push(cadr(p1));
3382 Eval();
3383 return adj();
3384 };
3385
3386 adj = function() {
3387 var ac, doNothing, i, j, n, o, ref, ref1;
3388 i = 0;
3389 j = 0;
3390 n = 0;
3391 save();
3392 p1 = pop();
3393 if (istensor(p1) && p1.tensor.ndim === 2 && p1.tensor.dim[0] === p1.tensor.dim[1]) {
3394 doNothing = 1;
3395 } else {
3396 stop("adj: square matrix expected");
3397 }
3398 n = p1.tensor.dim[0];
3399 p2 = alloc_tensor(n * n);
3400 p2.tensor.ndim = 2;
3401 p2.tensor.dim[0] = n;
3402 p2.tensor.dim[1] = n;
3403 for (i = o = 0, ref = n; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
3404 for (j = ac = 0, ref1 = n; 0 <= ref1 ? ac < ref1 : ac > ref1; j = 0 <= ref1 ? ++ac : --ac) {
3405 cofactor(p1, n, i, j);
3406 p2.tensor.elem[n * j + i] = pop();
3407 }
3408 }
3409 push(p2);
3410 return restore();
3411 };
3412
3413 Eval_arccos = function() {
3414 push(cadr(p1));
3415 Eval();
3416 return arccos();
3417 };
3418
3419 arccos = function() {
3420 var d, errno, n;
3421 n = 0;
3422 d = 0.0;
3423 save();
3424 p1 = pop();
3425 if (car(p1) === symbol(COS)) {
3426 push(cadr(p1));
3427 restore();
3428 return;
3429 }
3430 if (isdouble(p1)) {
3431 errno = 0;
3432 d = Math.acos(p1.d);
3433 if (errno) {
3434 stop("arccos function argument is not in the interval [-1,1]");
3435 }
3436 push_double(d);
3437 restore();
3438 return;
3439 }
3440 if (isoneoversqrttwo(p1)) {
3441 push_rational(1, 4);
3442 push_symbol(PI);
3443 multiply();
3444 restore();
3445 return;
3446 }
3447 if (isminusoneoversqrttwo(p1)) {
3448 push_rational(3, 4);
3449 push_symbol(PI);
3450 multiply();
3451 restore();
3452 return;
3453 }
3454 if (!isrational(p1)) {
3455 push_symbol(ARCCOS);
3456 push(p1);
3457 list(2);
3458 restore();
3459 return;
3460 }
3461 push(p1);
3462 push_integer(2);
3463 multiply();
3464 n = pop_integer();
3465 switch (n) {
3466 case -2:
3467 push_symbol(PI);
3468 break;
3469 case -1:
3470 push_rational(2, 3);
3471 push_symbol(PI);
3472 multiply();
3473 break;
3474 case 0:
3475 push_rational(1, 2);
3476 push_symbol(PI);
3477 multiply();
3478 break;
3479 case 1:
3480 push_rational(1, 3);
3481 push_symbol(PI);
3482 multiply();
3483 break;
3484 case 2:
3485 push(zero);
3486 break;
3487 default:
3488 push_symbol(ARCCOS);
3489 push(p1);
3490 list(2);
3491 }
3492 return restore();
3493 };
3494
3495 Eval_arccosh = function() {
3496 push(cadr(p1));
3497 Eval();
3498 return arccosh();
3499 };
3500
3501 arccosh = function() {
3502 var d;
3503 d = 0.0;
3504 save();
3505 p1 = pop();
3506 if (car(p1) === symbol(COSH)) {
3507 push(cadr(p1));
3508 restore();
3509 return;
3510 }
3511 if (isdouble(p1)) {
3512 d = p1.d;
3513 if (d < 1.0) {
3514 stop("arccosh function argument is less than 1.0");
3515 }
3516 d = Math.log(d + Math.sqrt(d * d - 1.0));
3517 push_double(d);
3518 restore();
3519 return;
3520 }
3521 if (isplusone(p1)) {
3522 push(zero);
3523 restore();
3524 return;
3525 }
3526 push_symbol(ARCCOSH);
3527 push(p1);
3528 list(2);
3529 return restore();
3530 };
3531
3532 Eval_arcsin = function() {
3533 push(cadr(p1));
3534 Eval();
3535 return arcsin();
3536 };
3537
3538 arcsin = function() {
3539 var d, errno, n;
3540 n = 0;
3541 d = 0;
3542 save();
3543 p1 = pop();
3544 if (car(p1) === symbol(SIN)) {
3545 push(cadr(p1));
3546 restore();
3547 return;
3548 }
3549 if (isdouble(p1)) {
3550 errno = 0;
3551 d = Math.asin(p1.d);
3552 if (errno) {
3553 stop("arcsin function argument is not in the interval [-1,1]");
3554 }
3555 push_double(d);
3556 restore();
3557 return;
3558 }
3559 if (isoneoversqrttwo(p1)) {
3560 push_rational(1, 4);
3561 push_symbol(PI);
3562 multiply();
3563 restore();
3564 return;
3565 }
3566 if (isminusoneoversqrttwo(p1)) {
3567 push_rational(-1, 4);
3568 push_symbol(PI);
3569 multiply();
3570 restore();
3571 return;
3572 }
3573 if (!isrational(p1)) {
3574 push_symbol(ARCSIN);
3575 push(p1);
3576 list(2);
3577 restore();
3578 return;
3579 }
3580 push(p1);
3581 push_integer(2);
3582 multiply();
3583 n = pop_integer();
3584 switch (n) {
3585 case -2:
3586 push_rational(-1, 2);
3587 push_symbol(PI);
3588 multiply();
3589 break;
3590 case -1:
3591 push_rational(-1, 6);
3592 push_symbol(PI);
3593 multiply();
3594 break;
3595 case 0:
3596 push(zero);
3597 break;
3598 case 1:
3599 push_rational(1, 6);
3600 push_symbol(PI);
3601 multiply();
3602 break;
3603 case 2:
3604 push_rational(1, 2);
3605 push_symbol(PI);
3606 multiply();
3607 break;
3608 default:
3609 push_symbol(ARCSIN);
3610 push(p1);
3611 list(2);
3612 }
3613 return restore();
3614 };
3615
3616 Eval_arcsinh = function() {
3617 push(cadr(p1));
3618 Eval();
3619 return arcsinh();
3620 };
3621
3622 arcsinh = function() {
3623 var d;
3624 d = 0.0;
3625 save();
3626 p1 = pop();
3627 if (car(p1) === symbol(SINH)) {
3628 push(cadr(p1));
3629 restore();
3630 return;
3631 }
3632 if (isdouble(p1)) {
3633 d = p1.d;
3634 d = Math.log(d + Math.sqrt(d * d + 1.0));
3635 push_double(d);
3636 restore();
3637 return;
3638 }
3639 if (iszero(p1)) {
3640 push(zero);
3641 restore();
3642 return;
3643 }
3644 push_symbol(ARCSINH);
3645 push(p1);
3646 list(2);
3647 return restore();
3648 };
3649
3650 Eval_arctan = function() {
3651 push(cadr(p1));
3652 Eval();
3653 return arctan();
3654 };
3655
3656 arctan = function() {
3657 var d, errno;
3658 d = 0;
3659 save();
3660 p1 = pop();
3661 if (car(p1) === symbol(TAN)) {
3662 push(cadr(p1));
3663 restore();
3664 return;
3665 }
3666 if (isdouble(p1)) {
3667 errno = 0;
3668 d = Math.atan(p1.d);
3669 if (errno) {
3670 stop("arctan function error");
3671 }
3672 push_double(d);
3673 restore();
3674 return;
3675 }
3676 if (iszero(p1)) {
3677 push(zero);
3678 restore();
3679 return;
3680 }
3681 if (isnegative(p1)) {
3682 push(p1);
3683 negate();
3684 arctan();
3685 negate();
3686 restore();
3687 return;
3688 }
3689 if (Find(p1, symbol(SIN)) && Find(p1, symbol(COS))) {
3690 push(p1);
3691 numerator();
3692 p2 = pop();
3693 push(p1);
3694 denominator();
3695 p3 = pop();
3696 if (car(p2) === symbol(SIN) && car(p3) === symbol(COS) && equal(cadr(p2), cadr(p3))) {
3697 push(cadr(p2));
3698 restore();
3699 return;
3700 }
3701 }
3702 if (car(p1) === symbol(POWER) && equaln(cadr(p1), 3) && equalq(caddr(p1), -1, 2)) {
3703 push_rational(1, 6);
3704 push(symbol(PI));
3705 multiply();
3706 restore();
3707 return;
3708 }
3709 if (equaln(p1, 1)) {
3710 push_rational(1, 4);
3711 push(symbol(PI));
3712 multiply();
3713 restore();
3714 return;
3715 }
3716 if (car(p1) === symbol(POWER) && equaln(cadr(p1), 3) && equalq(caddr(p1), 1, 2)) {
3717 push_rational(1, 3);
3718 push(symbol(PI));
3719 multiply();
3720 restore();
3721 return;
3722 }
3723 push_symbol(ARCTAN);
3724 push(p1);
3725 list(2);
3726 return restore();
3727 };
3728
3729 Eval_arctanh = function() {
3730 push(cadr(p1));
3731 Eval();
3732 return arctanh();
3733 };
3734
3735 arctanh = function() {
3736 var d;
3737 d = 0.0;
3738 save();
3739 p1 = pop();
3740 if (car(p1) === symbol(TANH)) {
3741 push(cadr(p1));
3742 restore();
3743 return;
3744 }
3745 if (isdouble(p1)) {
3746 d = p1.d;
3747 if (d < -1.0 || d > 1.0) {
3748 stop("arctanh function argument is not in the interval [-1,1]");
3749 }
3750 d = Math.log((1.0 + d) / (1.0 - d)) / 2.0;
3751 push_double(d);
3752 restore();
3753 return;
3754 }
3755 if (iszero(p1)) {
3756 push(zero);
3757 restore();
3758 return;
3759 }
3760 push_symbol(ARCTANH);
3761 push(p1);
3762 list(2);
3763 return restore();
3764 };
3765
3766
3767 /*
3768 Argument (angle) of complex z
3769
3770 z arg(z)
3771 - ------
3772
3773 a 0
3774
3775 -a -pi See note 3 below
3776
3777 (-1)^a a pi
3778
3779 exp(a + i b) b
3780
3781 a b arg(a) + arg(b)
3782
3783 a + i b arctan(b/a)
3784
3785 Result by quadrant
3786
3787 z arg(z)
3788 - ------
3789
3790 1 + i 1/4 pi
3791
3792 1 - i -1/4 pi
3793
3794 -1 + i 3/4 pi
3795
3796 -1 - i -3/4 pi
3797
3798 Notes
3799
3800 1. Handles mixed polar and rectangular forms, e.g. 1 + exp(i pi/3)
3801
3802 2. Symbols in z are assumed to be positive and real.
3803
3804 3. Negative direction adds -pi to angle.
3805
3806 Example: z = (-1)^(1/3), mag(z) = 1/3 pi, mag(-z) = -2/3 pi
3807
3808 4. jean-francois.debroux reports that when z=(a+i*b)/(c+i*d) then
3809
3810 arg(numerator(z)) - arg(denominator(z))
3811
3812 must be used to get the correct answer. Now the operation is
3813 automatic.
3814 */
3815
3816 Eval_arg = function() {
3817 push(cadr(p1));
3818 Eval();
3819 return arg();
3820 };
3821
3822 arg = function() {
3823 save();
3824 p1 = pop();
3825 push(p1);
3826 numerator();
3827 yyarg();
3828 push(p1);
3829 denominator();
3830 yyarg();
3831 subtract();
3832 return restore();
3833 };
3834
3835 yyarg = function() {
3836 save();
3837 p1 = pop();
3838 if (isnegativenumber(p1)) {
3839 push(symbol(PI));
3840 negate();
3841 } else if (car(p1) === symbol(POWER) && equaln(cadr(p1), -1)) {
3842 push(symbol(PI));
3843 push(caddr(p1));
3844 multiply();
3845 } else if (car(p1) === symbol(POWER) && cadr(p1) === symbol(E)) {
3846 push(caddr(p1));
3847 imag();
3848 } else if (car(p1) === symbol(MULTIPLY)) {
3849 push_integer(0);
3850 p1 = cdr(p1);
3851 while (iscons(p1)) {
3852 push(car(p1));
3853 arg();
3854 add();
3855 p1 = cdr(p1);
3856 }
3857 } else if (car(p1) === symbol(ADD)) {
3858 push(p1);
3859 rect();
3860 p1 = pop();
3861 push(p1);
3862 real();
3863 p2 = pop();
3864 push(p1);
3865 imag();
3866 p3 = pop();
3867 if (iszero(p2)) {
3868 push(symbol(PI));
3869 if (isnegative(p3)) {
3870 negate();
3871 }
3872 } else {
3873 push(p3);
3874 push(p2);
3875 divide();
3876 arctan();
3877 if (isnegative(p2)) {
3878 push_symbol(PI);
3879 if (isnegative(p3)) {
3880 subtract();
3881 } else {
3882 add();
3883 }
3884 }
3885 }
3886 } else {
3887 push_integer(0);
3888 }
3889 return restore();
3890 };
3891
3892 bake = function() {
3893 var h, s, t, x, y, z;
3894 h = 0;
3895 s = 0;
3896 t = 0;
3897 x = 0;
3898 y = 0;
3899 z = 0;
3900 expanding++;
3901 save();
3902 p1 = pop();
3903 s = ispoly(p1, symbol(SYMBOL_S));
3904 t = ispoly(p1, symbol(SYMBOL_T));
3905 x = ispoly(p1, symbol(SYMBOL_X));
3906 y = ispoly(p1, symbol(SYMBOL_Y));
3907 z = ispoly(p1, symbol(SYMBOL_Z));
3908 if (s === 1 && t === 0 && x === 0 && y === 0 && z === 0) {
3909 p2 = symbol(SYMBOL_S);
3910 bake_poly();
3911 } else if (s === 0 && t === 1 && x === 0 && y === 0 && z === 0) {
3912 p2 = symbol(SYMBOL_T);
3913 bake_poly();
3914 } else if (s === 0 && t === 0 && x === 1 && y === 0 && z === 0) {
3915 p2 = symbol(SYMBOL_X);
3916 bake_poly();
3917 } else if (s === 0 && t === 0 && x === 0 && y === 1 && z === 0) {
3918 p2 = symbol(SYMBOL_Y);
3919 bake_poly();
3920 } else if (s === 0 && t === 0 && x === 0 && y === 0 && z === 1) {
3921 p2 = symbol(SYMBOL_Z);
3922 bake_poly();
3923 } else if (iscons(p1)) {
3924 h = tos;
3925 push(car(p1));
3926 p1 = cdr(p1);
3927 while (iscons(p1)) {
3928 push(car(p1));
3929 bake();
3930 p1 = cdr(p1);
3931 }
3932 list(tos - h);
3933 } else {
3934 push(p1);
3935 }
3936 restore();
3937 return expanding--;
3938 };
3939
3940 polyform = function() {
3941 var h;
3942 h = 0;
3943 save();
3944 p2 = pop();
3945 p1 = pop();
3946 if (ispoly(p1, p2)) {
3947 bake_poly();
3948 } else if (iscons(p1)) {
3949 h = tos;
3950 push(car(p1));
3951 p1 = cdr(p1);
3952 while (iscons(p1)) {
3953 push(car(p1));
3954 push(p2);
3955 polyform();
3956 p1 = cdr(p1);
3957 }
3958 list(tos - h);
3959 } else {
3960 push(p1);
3961 }
3962 return restore();
3963 };
3964
3965 bake_poly = function() {
3966 var a, h, i, k, n, o, ref;
3967 h = 0;
3968 i = 0;
3969 k = 0;
3970 n = 0;
3971 a = tos;
3972 push(p1);
3973 push(p2);
3974 k = coeff();
3975 h = tos;
3976 for (i = o = ref = k - 1; o >= 0; i = o += -1) {
3977 p1 = stack[a + i];
3978 bake_poly_term(i);
3979 }
3980 n = tos - h;
3981 if (n > 1) {
3982 list(n);
3983 push(symbol(ADD));
3984 swap();
3985 cons();
3986 }
3987 p1 = pop();
3988 tos -= k;
3989 return push(p1);
3990 };
3991
3992 bake_poly_term = function(k) {
3993 var h, n;
3994 h = 0;
3995 n = 0;
3996 if (iszero(p1)) {
3997 return;
3998 }
3999 if (k === 0) {
4000 if (car(p1) === symbol(ADD)) {
4001 p1 = cdr(p1);
4002 while (iscons(p1)) {
4003 push(car(p1));
4004 p1 = cdr(p1);
4005 }
4006 } else {
4007 push(p1);
4008 }
4009 return;
4010 }
4011 h = tos;
4012 if (car(p1) === symbol(MULTIPLY)) {
4013 p1 = cdr(p1);
4014 while (iscons(p1)) {
4015 push(car(p1));
4016 p1 = cdr(p1);
4017 }
4018 } else if (!equaln(p1, 1)) {
4019 push(p1);
4020 }
4021 if (k === 1) {
4022 push(p2);
4023 } else {
4024 push(symbol(POWER));
4025 push(p2);
4026 push_integer(k);
4027 list(3);
4028 }
4029 n = tos - h;
4030 if (n > 1) {
4031 list(n);
4032 push(symbol(MULTIPLY));
4033 swap();
4034 return cons();
4035 }
4036 };
4037
4038
4039 /*
4040 Bessel J function
4041
4042 1st arg x
4043
4044 2nd arg n
4045
4046 Recurrence relation
4047
4048 besselj(x,n) = (2/x) (n-1) besselj(x,n-1) - besselj(x,n-2)
4049
4050 besselj(x,1/2) = sqrt(2/pi/x) sin(x)
4051
4052 besselj(x,-1/2) = sqrt(2/pi/x) cos(x)
4053
4054 For negative n, reorder the recurrence relation as
4055
4056 besselj(x,n-2) = (2/x) (n-1) besselj(x,n-1) - besselj(x,n)
4057
4058 Substitute n+2 for n to obtain
4059
4060 besselj(x,n) = (2/x) (n+1) besselj(x,n+1) - besselj(x,n+2)
4061
4062 Examples
4063
4064 besselj(x,3/2) = (1/x) besselj(x,1/2) - besselj(x,-1/2)
4065
4066 besselj(x,-3/2) = -(1/x) besselj(x,-1/2) - besselj(x,1/2)
4067 */
4068
4069 Eval_besselj = function() {
4070 push(cadr(p1));
4071 Eval();
4072 push(caddr(p1));
4073 Eval();
4074 return besselj();
4075 };
4076
4077 besselj = function() {
4078 save();
4079 yybesselj();
4080 return restore();
4081 };
4082
4083 yybesselj = function() {
4084 var d, n;
4085 d = 0.0;
4086 n = 0;
4087 p2 = pop();
4088 p1 = pop();
4089 push(p2);
4090 n = pop_integer();
4091 if (isdouble(p1) && n !== 0x80000000) {
4092 d = jn(n, p1.d);
4093 push_double(d);
4094 return;
4095 }
4096 if (iszero(p1) && iszero(p2)) {
4097 push_integer(1);
4098 return;
4099 }
4100 if (iszero(p1) && n !== 0x80000000) {
4101 push_integer(0);
4102 return;
4103 }
4104 if (p2.k === NUM && MEQUAL(p2.q.b, 2)) {
4105 if (MEQUAL(p2.q.a, 1)) {
4106 push_integer(2);
4107 push_symbol(PI);
4108 divide();
4109 push(p1);
4110 divide();
4111 push_rational(1, 2);
4112 power();
4113 push(p1);
4114 sine();
4115 multiply();
4116 return;
4117 }
4118 if (MEQUAL(p2.q.a, -1)) {
4119 push_integer(2);
4120 push_symbol(PI);
4121 divide();
4122 push(p1);
4123 divide();
4124 push_rational(1, 2);
4125 power();
4126 push(p1);
4127 cosine();
4128 multiply();
4129 return;
4130 }
4131 push_integer(MSIGN(p2.q.a));
4132 p3 = pop();
4133 push_integer(2);
4134 push(p1);
4135 divide();
4136 push(p2);
4137 push(p3);
4138 subtract();
4139 multiply();
4140 push(p1);
4141 push(p2);
4142 push(p3);
4143 subtract();
4144 besselj();
4145 multiply();
4146 push(p1);
4147 push(p2);
4148 push_integer(2);
4149 push(p3);
4150 multiply();
4151 subtract();
4152 besselj();
4153 subtract();
4154 return;
4155 }
4156 if (isnegativeterm(p1)) {
4157 push(p1);
4158 negate();
4159 push(p2);
4160 power();
4161 push(p1);
4162 push(p2);
4163 negate();
4164 power();
4165 multiply();
4166 push_symbol(BESSELJ);
4167 push(p1);
4168 negate();
4169 push(p2);
4170 list(3);
4171 multiply();
4172 return;
4173 }
4174 if (isnegativeterm(p2)) {
4175 push_integer(-1);
4176 push(p2);
4177 power();
4178 push_symbol(BESSELJ);
4179 push(p1);
4180 push(p2);
4181 negate();
4182 list(3);
4183 multiply();
4184 return;
4185 }
4186 push(symbol(BESSELJ));
4187 push(p1);
4188 push(p2);
4189 return list(3);
4190 };
4191
4192 Eval_bessely = function() {
4193 push(cadr(p1));
4194 Eval();
4195 push(caddr(p1));
4196 Eval();
4197 return bessely();
4198 };
4199
4200 bessely = function() {
4201 save();
4202 yybessely();
4203 return restore();
4204 };
4205
4206 yybessely = function() {
4207 var d, n;
4208 d = 0.0;
4209 n = 0;
4210 p2 = pop();
4211 p1 = pop();
4212 push(p2);
4213 n = pop_integer();
4214 if (isdouble(p1) && n !== 0x80000000) {
4215 d = yn(n, p1.d);
4216 push_double(d);
4217 return;
4218 }
4219 if (isnegativeterm(p2)) {
4220 push_integer(-1);
4221 push(p2);
4222 power();
4223 push_symbol(BESSELY);
4224 push(p1);
4225 push(p2);
4226 negate();
4227 list(3);
4228 multiply();
4229 return;
4230 }
4231 push_symbol(BESSELY);
4232 push(p1);
4233 push(p2);
4234 list(3);
4235 };
4236
4237 MP_MIN_SIZE = 2;
4238
4239 MP_MAX_FREE = 1000;
4240
4241 mtotal = 0;
4242
4243 free_stack = [];
4244
4245 mint = function(a) {
4246 return bigInt(a);
4247 };
4248
4249 setSignTo = function(a, b) {
4250 if (a.isPositive()) {
4251 if (b < 0) {
4252 return a.multiply(bigInt(-1));
4253 }
4254 } else {
4255 if (b > 0) {
4256 return a.multiply(bigInt(-1));
4257 }
4258 }
4259 return a;
4260 };
4261
4262 makeSignSameAs = function(a, b) {
4263 if (a.isPositive()) {
4264 if (b.isNegative()) {
4265 return a.multiply(bigInt(-1));
4266 }
4267 } else {
4268 if (b.isPositive()) {
4269 return a.multiply(bigInt(-1));
4270 }
4271 }
4272 return a;
4273 };
4274
4275 makePositive = function(a) {
4276 if (a.isNegative()) {
4277 return a.multiply(bigInt(-1));
4278 }
4279 return a;
4280 };
4281
4282
4283 /*
4284 mnew = (n) ->
4285 if (n < MP_MIN_SIZE)
4286 n = MP_MIN_SIZE
4287 if (n == MP_MIN_SIZE && mfreecount)
4288 p = free_stack[--mfreecount]
4289 else
4290 p = [] #(unsigned int *) malloc((n + 3) * sizeof (int))
4291 #if (p == 0)
4292 * stop("malloc failure")
4293 p[0] = n
4294 mtotal += n
4295 return p[3]
4296 */
4297
4298
4299 /*
4300 mfree = (array, p) ->
4301 p -= 3
4302 mtotal -= array[p]
4303 if (array[p] == MP_MIN_SIZE && mfreecount < MP_MAX_FREE)
4304 free_stack[mfreecount++] = p
4305 else
4306 free(p)
4307 */
4308
4309
4310 /*
4311 mint = (n) ->
4312 p = mnew(1)
4313 if (n < 0)
4314 * !!! this is FU
4315 * MSIGN(p) = -1
4316 fu = true
4317 else
4318 * !!! this is FU
4319 #MSIGN(p) = 1
4320 fu = true
4321 * !!! this is FU
4322 #MLENGTH(p) = 1
4323 p[0] = Math.abs(n)
4324 return p
4325 */
4326
4327
4328 /*
4329 mcopy = (a) ->
4330 #unsigned int *b
4331
4332 b = mnew(MLENGTH(a))
4333
4334 * !!! fu
4335 #MSIGN(b) = MSIGN(a)
4336 #MLENGTH(b) = MLENGTH(a)
4337
4338 for i in [0...MLENGTH(a)]
4339 b[i] = a[i]
4340
4341 return b
4342 */
4343
4344
4345 /*
4346 *
4347 * ge not invoked from anywhere - is you need ge
4348 * just use the bigNum's ge implementation
4349 * leaving it here just in case I decide to backport to C
4350 *
4351 * a >= b ?
4352 * and and b arrays of ints, len is an int
4353 ge = (a, b, len) ->
4354 i = 0
4355 for i in [0...len]
4356 if (a[i] == b[i])
4357 continue
4358 else
4359 break
4360 if (a[i] >= b[i])
4361 return 1
4362 else
4363 return 0
4364 */
4365
4366 add_numbers = function() {
4367 var a, b, theResult;
4368 a = 1.0;
4369 b = 1.0;
4370 if (isrational(stack[tos - 1]) && isrational(stack[tos - 2])) {
4371 qadd();
4372 return;
4373 }
4374 save();
4375 p2 = pop();
4376 p1 = pop();
4377 if (isdouble(p1)) {
4378 a = p1.d;
4379 } else {
4380 a = convert_rational_to_double(p1);
4381 }
4382 if (isdouble(p2)) {
4383 b = p2.d;
4384 } else {
4385 b = convert_rational_to_double(p2);
4386 }
4387 theResult = a + b;
4388 push_double(theResult);
4389 return restore();
4390 };
4391
4392 subtract_numbers = function() {
4393 var a, b;
4394 a = 0.0;
4395 b = 0.0;
4396 if (isrational(stack[tos - 1]) && isrational(stack[tos - 2])) {
4397 qsub();
4398 return;
4399 }
4400 save();
4401 p2 = pop();
4402 p1 = pop();
4403 if (isdouble(p1)) {
4404 a = p1.d;
4405 } else {
4406 a = convert_rational_to_double(p1);
4407 }
4408 if (isdouble(p2)) {
4409 b = p2.d;
4410 } else {
4411 b = convert_rational_to_double(p2);
4412 }
4413 push_double(a - b);
4414 return restore();
4415 };
4416
4417 multiply_numbers = function() {
4418 var a, b;
4419 a = 0.0;
4420 b = 0.0;
4421 if (isrational(stack[tos - 1]) && isrational(stack[tos - 2])) {
4422 qmul();
4423 return;
4424 }
4425 save();
4426 p2 = pop();
4427 p1 = pop();
4428 if (isdouble(p1)) {
4429 a = p1.d;
4430 } else {
4431 a = convert_rational_to_double(p1);
4432 }
4433 if (isdouble(p2)) {
4434 b = p2.d;
4435 } else {
4436 b = convert_rational_to_double(p2);
4437 }
4438 push_double(a * b);
4439 return restore();
4440 };
4441
4442 divide_numbers = function() {
4443 var a, b;
4444 a = 0.0;
4445 b = 0.0;
4446 if (isrational(stack[tos - 1]) && isrational(stack[tos - 2])) {
4447 qdiv();
4448 return;
4449 }
4450 save();
4451 p2 = pop();
4452 p1 = pop();
4453 if (iszero(p2)) {
4454 stop("divide by zero");
4455 }
4456 if (isdouble(p1)) {
4457 a = p1.d;
4458 } else {
4459 a = convert_rational_to_double(p1);
4460 }
4461 if (isdouble(p2)) {
4462 b = p2.d;
4463 } else {
4464 b = convert_rational_to_double(p2);
4465 }
4466 push_double(a / b);
4467 return restore();
4468 };
4469
4470 invert_number = function() {
4471 var a, b;
4472 save();
4473 p1 = pop();
4474 if (iszero(p1)) {
4475 stop("divide by zero");
4476 }
4477 if (isdouble(p1)) {
4478 push_double(1 / p1.d);
4479 restore();
4480 return;
4481 }
4482 a = bigInt(p1.q.a);
4483 b = bigInt(p1.q.b);
4484 b = makeSignSameAs(b, a);
4485 a = setSignTo(a, 1);
4486 p1 = new U();
4487 p1.k = NUM;
4488 p1.q.a = b;
4489 p1.q.b = a;
4490 push(p1);
4491 return restore();
4492 };
4493
4494 compare_rationals = function(a, b) {
4495 var ab, ba, t;
4496 t = 0;
4497 ab = mmul(a.q.a, b.q.b);
4498 ba = mmul(a.q.b, b.q.a);
4499 t = mcmp(ab, ba);
4500 return t;
4501 };
4502
4503 compare_numbers = function(a, b) {
4504 var x, y;
4505 x = 0.0;
4506 y = 0.0;
4507 if (isrational(a) && isrational(b)) {
4508 return compare_rationals(a, b);
4509 }
4510 if (isdouble(a)) {
4511 x = a.d;
4512 } else {
4513 x = convert_rational_to_double(a);
4514 }
4515 if (isdouble(b)) {
4516 y = b.d;
4517 } else {
4518 y = convert_rational_to_double(b);
4519 }
4520 if (x < y) {
4521 return -1;
4522 }
4523 if (x > y) {
4524 return 1;
4525 }
4526 return 0;
4527 };
4528
4529 negate_number = function() {
4530 save();
4531 p1 = pop();
4532 if (iszero(p1)) {
4533 push(p1);
4534 restore();
4535 return;
4536 }
4537 switch (p1.k) {
4538 case NUM:
4539 p2 = new U();
4540 p2.k = NUM;
4541 p2.q.a = bigInt(p1.q.a.multiply(bigInt.minusOne));
4542 p2.q.b = bigInt(p1.q.b);
4543 push(p2);
4544 break;
4545 case DOUBLE:
4546 push_double(-p1.d);
4547 break;
4548 default:
4549 stop("bug caught in mp_negate_number");
4550 }
4551 return restore();
4552 };
4553
4554 bignum_truncate = function() {
4555 var a;
4556 save();
4557 p1 = pop();
4558 a = mdiv(p1.q.a, p1.q.b);
4559 p1 = new U();
4560 p1.k = NUM;
4561 p1.q.a = a;
4562 p1.q.b = bigInt(1);
4563 push(p1);
4564 return restore();
4565 };
4566
4567 mp_numerator = function() {
4568 save();
4569 p1 = pop();
4570 if (p1.k !== NUM) {
4571 push(one);
4572 restore();
4573 return;
4574 }
4575 p2 = new U();
4576 p2.k = NUM;
4577 p2.q.a = bigInt(p1.q.a);
4578 p2.q.b = bigInt(1);
4579 push(p2);
4580 return restore();
4581 };
4582
4583 mp_denominator = function() {
4584 save();
4585 p1 = pop();
4586 if (p1.k !== NUM) {
4587 push(one);
4588 restore();
4589 return;
4590 }
4591 p2 = new U();
4592 p2.k = NUM;
4593 p2.q.a = bigInt(p1.q.b);
4594 p2.q.b = bigInt(1);
4595 push(p2);
4596 return restore();
4597 };
4598
4599 bignum_power_number = function(expo) {
4600 var a, b, t;
4601 save();
4602 p1 = pop();
4603 a = mpow(p1.q.a, Math.abs(expo));
4604 b = mpow(p1.q.b, Math.abs(expo));
4605 if (expo < 0) {
4606 t = a;
4607 a = b;
4608 b = t;
4609 a = makeSignSameAs(a, b);
4610 b = setSignTo(b, 1);
4611 }
4612 p1 = new U();
4613 p1.k = NUM;
4614 p1.q.a = a;
4615 p1.q.b = b;
4616 push(p1);
4617 return restore();
4618 };
4619
4620 convert_bignum_to_double = function(p) {
4621 return p.toJSNumber();
4622 };
4623
4624 convert_rational_to_double = function(p) {
4625 var quotientAndRemainder, result;
4626 if (p.q == null) {
4627 debugger;
4628 }
4629 quotientAndRemainder = p.q.a.divmod(p.q.b);
4630 result = quotientAndRemainder.quotient + quotientAndRemainder.remainder / p.q.b.toJSNumber();
4631 return result;
4632 };
4633
4634 push_integer = function(n) {
4635 if (DEBUG) {
4636 console.log("pushing integer " + n);
4637 }
4638 save();
4639 p1 = new U();
4640 p1.k = NUM;
4641 p1.q.a = bigInt(n);
4642 p1.q.b = bigInt(1);
4643 push(p1);
4644 return restore();
4645 };
4646
4647 push_double = function(d) {
4648 save();
4649 p1 = new U();
4650 p1.k = DOUBLE;
4651 p1.d = d;
4652 push(p1);
4653 return restore();
4654 };
4655
4656 push_rational = function(a, b) {
4657
4658 /*
4659 save()
4660 p1 = new U()
4661 p1.k = NUM
4662 p1.q.a = bigInt(a)
4663 p1.q.b = bigInt(b)
4664 ## FIXME -- normalize ##
4665 push(p1)
4666 restore()
4667 */
4668 var p;
4669 p = new U();
4670 p.k = NUM;
4671 p.q.a = bigInt(a);
4672 p.q.b = bigInt(b);
4673 return push(p);
4674 };
4675
4676 pop_integer = function() {
4677 var n;
4678 n = 0;
4679 save();
4680 p1 = pop();
4681 switch (p1.k) {
4682 case NUM:
4683 if (isinteger(p1) && p1.q.a.isSmall) {
4684 n = p1.q.a.toJSNumber();
4685 } else {
4686 n = 0x80000000;
4687 }
4688 break;
4689 case DOUBLE:
4690 n = Math.floor(p1.q.a);
4691 break;
4692 default:
4693 n = 0x80000000;
4694 }
4695 restore();
4696 return n;
4697 };
4698
4699 print_double = function(p, flag) {
4700 var buf;
4701 buf = "";
4702 buf = "" + doubleToReasonableString(p.d);
4703 if (flag === 1 && buf === '-') {
4704 return print_str(buf + 1);
4705 } else {
4706 return print_str(buf);
4707 }
4708 };
4709
4710 bignum_scan_integer = function(s) {
4711 var a, scounter, sign_;
4712 save();
4713 scounter = 0;
4714 sign_ = s[scounter];
4715 if (sign_ === '+' || sign_ === '-') {
4716 scounter++;
4717 }
4718 a = bigInt(s.substring(scounter));
4719 p1 = new U();
4720 p1.k = NUM;
4721 p1.q.a = a;
4722 p1.q.b = bigInt(1);
4723 push(p1);
4724 if (sign_ === '-') {
4725 negate();
4726 }
4727 return restore();
4728 };
4729
4730 bignum_scan_float = function(s) {
4731 return push_double(parseFloat(s));
4732 };
4733
4734 print_number = function(p, accumulator) {
4735 var aAsString, buf, denominatorString, topLevelCall;
4736 topLevelCall = false;
4737 if (accumulator == null) {
4738 topLevelCall = true;
4739 accumulator = "";
4740 }
4741 denominatorString = "";
4742 buf = "";
4743 switch (p.k) {
4744 case NUM:
4745 aAsString = p.q.a.toString();
4746 if (aAsString[0] === "-") {
4747 aAsString = aAsString.substring(1);
4748 }
4749 accumulator += aAsString;
4750 stringToBePrinted += aAsString;
4751 if (isfraction(p)) {
4752 accumulator += "/";
4753 stringToBePrinted += "/";
4754 denominatorString = p.q.b.toString();
4755 accumulator += denominatorString;
4756 stringToBePrinted += denominatorString;
4757 }
4758 break;
4759 case DOUBLE:
4760 aAsString = "" + doubleToReasonableString(p.d);
4761 if (aAsString[0] === "-") {
4762 aAsString = aAsString.substring(1);
4763 }
4764 accumulator += aAsString;
4765 stringToBePrinted += aAsString;
4766 }
4767 return accumulator;
4768 };
4769
4770 gcd_numbers = function() {
4771 save();
4772 p2 = pop();
4773 p1 = pop();
4774 p3 = new U();
4775 p3.k = NUM;
4776 p3.q.a = mgcd(p1.q.a, p2.q.a);
4777 p3.q.b = mgcd(p1.q.b, p2.q.b);
4778 p3.q.a = setSignTo(p3.q.a, 1);
4779 push(p3);
4780 return restore();
4781 };
4782
4783 pop_double = function() {
4784 var d;
4785 d = 0.0;
4786 save();
4787 p1 = pop();
4788 switch (p1.k) {
4789 case NUM:
4790 d = convert_rational_to_double(p1);
4791 break;
4792 case DOUBLE:
4793 d = p1.d;
4794 break;
4795 default:
4796 d = 0.0;
4797 }
4798 restore();
4799 return d;
4800 };
4801
4802 bignum_float = function() {
4803 var d;
4804 d = 0.0;
4805 d = convert_rational_to_double(pop());
4806 return push_double(d);
4807 };
4808
4809 bignum_factorial = function(n) {
4810 save();
4811 p1 = new U();
4812 p1.k = NUM;
4813 p1.q.a = __factorial(n);
4814 p1.q.b = bigInt(1);
4815 push(p1);
4816 return restore();
4817 };
4818
4819 __factorial = function(n) {
4820 var a, b, i, o, ref, t;
4821 i = 0;
4822 if (n === 0 || n === 1) {
4823 a = bigInt(1);
4824 return a;
4825 }
4826 a = bigInt(2);
4827 b = bigInt(0);
4828 if (3 <= n) {
4829 for (i = o = 3, ref = n; 3 <= ref ? o <= ref : o >= ref; i = 3 <= ref ? ++o : --o) {
4830 b = bigInt(i);
4831 t = mmul(a, b);
4832 a = t;
4833 }
4834 }
4835 return a;
4836 };
4837
4838 mask = [0x00000001, 0x00000002, 0x00000004, 0x00000008, 0x00000010, 0x00000020, 0x00000040, 0x00000080, 0x00000100, 0x00000200, 0x00000400, 0x00000800, 0x00001000, 0x00002000, 0x00004000, 0x00008000, 0x00010000, 0x00020000, 0x00040000, 0x00080000, 0x00100000, 0x00200000, 0x00400000, 0x00800000, 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000, 0x40000000, 0x80000000];
4839
4840 mp_set_bit = function(x, k) {
4841 console.log("not implemented yet");
4842 debugger;
4843 return x[k / 32] |= mask[k % 32];
4844 };
4845
4846 mp_clr_bit = function(x, k) {
4847 console.log("not implemented yet");
4848 debugger;
4849 return x[k / 32] &= ~mask[k % 32];
4850 };
4851
4852 mshiftright = function(a) {
4853 return a = a.shiftRight();
4854 };
4855
4856 Eval_binomial = function() {
4857 push(cadr(p1));
4858 Eval();
4859 push(caddr(p1));
4860 Eval();
4861 return binomial();
4862 };
4863
4864 binomial = function() {
4865 save();
4866 ybinomial();
4867 return restore();
4868 };
4869
4870 ybinomial = function() {
4871 p2 = pop();
4872 p1 = pop();
4873 if (BINOM_check_args() === 0) {
4874 push(zero);
4875 return;
4876 }
4877 push(p1);
4878 factorial();
4879 push(p2);
4880 factorial();
4881 divide();
4882 push(p1);
4883 push(p2);
4884 subtract();
4885 factorial();
4886 return divide();
4887 };
4888
4889 BINOM_check_args = function() {
4890 if (isnum(p1) && lessp(p1, zero)) {
4891 return 0;
4892 } else if (isnum(p2) && lessp(p2, zero)) {
4893 return 0;
4894 } else if (isnum(p1) && isnum(p2) && lessp(p1, p2)) {
4895 return 0;
4896 } else {
4897 return 1;
4898 }
4899 };
4900
4901 Eval_ceiling = function() {
4902 push(cadr(p1));
4903 Eval();
4904 return ceiling();
4905 };
4906
4907 ceiling = function() {
4908 save();
4909 yyceiling();
4910 return restore();
4911 };
4912
4913 yyceiling = function() {
4914 var d, doNothing;
4915 d = 0.0;
4916 p1 = pop();
4917 if (!isnum(p1)) {
4918 push_symbol(CEILING);
4919 push(p1);
4920 list(2);
4921 return;
4922 }
4923 if (isdouble(p1)) {
4924 d = Math.ceil(p1.d);
4925 push_double(d);
4926 return;
4927 }
4928 if (isinteger(p1)) {
4929 push(p1);
4930 return;
4931 }
4932 p3 = new U();
4933 p3.k = NUM;
4934 p3.q.a = mdiv(p1.q.a, p1.q.b);
4935 p3.q.b = mint(1);
4936 push(p3);
4937 if (isnegativenumber(p1)) {
4938 return doNothing = 1;
4939 } else {
4940 push_integer(1);
4941 return add();
4942 }
4943 };
4944
4945 Eval_choose = function() {
4946 push(cadr(p1));
4947 Eval();
4948 push(caddr(p1));
4949 Eval();
4950 return choose();
4951 };
4952
4953 choose = function() {
4954 save();
4955 p2 = pop();
4956 p1 = pop();
4957 if (choose_check_args() === 0) {
4958 push_integer(0);
4959 restore();
4960 return;
4961 }
4962 push(p1);
4963 factorial();
4964 push(p2);
4965 factorial();
4966 divide();
4967 push(p1);
4968 push(p2);
4969 subtract();
4970 factorial();
4971 divide();
4972 return restore();
4973 };
4974
4975 choose_check_args = function() {
4976 if (isnum(p1) && lessp(p1, zero)) {
4977 return 0;
4978 } else if (isnum(p2) && lessp(p2, zero)) {
4979 return 0;
4980 } else if (isnum(p1) && isnum(p2) && lessp(p1, p2)) {
4981 return 0;
4982 } else {
4983 return 1;
4984 }
4985 };
4986
4987 Eval_circexp = function() {
4988 push(cadr(p1));
4989 Eval();
4990 circexp();
4991 return Eval();
4992 };
4993
4994 circexp = function() {
4995 var h, i, o, ref;
4996 i = 0;
4997 h = 0;
4998 save();
4999 p1 = pop();
5000 if (car(p1) === symbol(COS)) {
5001 push(cadr(p1));
5002 expcos();
5003 restore();
5004 return;
5005 }
5006 if (car(p1) === symbol(SIN)) {
5007 push(cadr(p1));
5008 expsin();
5009 restore();
5010 return;
5011 }
5012 if (car(p1) === symbol(TAN)) {
5013 p1 = cadr(p1);
5014 push(imaginaryunit);
5015 push(p1);
5016 multiply();
5017 exponential();
5018 p2 = pop();
5019 push(imaginaryunit);
5020 push(p1);
5021 multiply();
5022 negate();
5023 exponential();
5024 p3 = pop();
5025 push(p3);
5026 push(p2);
5027 subtract();
5028 push(imaginaryunit);
5029 multiply();
5030 push(p2);
5031 push(p3);
5032 add();
5033 divide();
5034 restore();
5035 return;
5036 }
5037 if (car(p1) === symbol(COSH)) {
5038 p1 = cadr(p1);
5039 push(p1);
5040 exponential();
5041 push(p1);
5042 negate();
5043 exponential();
5044 add();
5045 push_rational(1, 2);
5046 multiply();
5047 restore();
5048 return;
5049 }
5050 if (car(p1) === symbol(SINH)) {
5051 p1 = cadr(p1);
5052 push(p1);
5053 exponential();
5054 push(p1);
5055 negate();
5056 exponential();
5057 subtract();
5058 push_rational(1, 2);
5059 multiply();
5060 restore();
5061 return;
5062 }
5063 if (car(p1) === symbol(TANH)) {
5064 p1 = cadr(p1);
5065 push(p1);
5066 push_integer(2);
5067 multiply();
5068 exponential();
5069 p1 = pop();
5070 push(p1);
5071 push_integer(1);
5072 subtract();
5073 push(p1);
5074 push_integer(1);
5075 add();
5076 divide();
5077 restore();
5078 return;
5079 }
5080 if (iscons(p1)) {
5081 h = tos;
5082 while (iscons(p1)) {
5083 push(car(p1));
5084 circexp();
5085 p1 = cdr(p1);
5086 }
5087 list(tos - h);
5088 restore();
5089 return;
5090 }
5091 if (p1.k === TENSOR) {
5092 push(p1);
5093 copy_tensor();
5094 p1 = pop();
5095 for (i = o = 0, ref = p1.tensor.nelem; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
5096 push(p1.tensor.elem[i]);
5097 circexp();
5098 p1.tensor.elem[i] = pop();
5099 }
5100 push(p1);
5101 restore();
5102 return;
5103 }
5104 push(p1);
5105 return restore();
5106 };
5107
5108 Eval_clear = function() {
5109 if (test_flag === 0) {
5110 clear_term();
5111 }
5112 clear_symbols();
5113 defn();
5114 return push(symbol(NIL));
5115 };
5116
5117 clear = function() {
5118 return run("clear");
5119 };
5120
5121
5122 /*
5123 Convert complex z to clock form
5124
5125 Input: push z
5126
5127 Output: Result on stack
5128
5129 clock(z) = mag(z) * (-1) ^ (arg(z) / pi)
5130
5131 For example, clock(exp(i pi/3)) gives the result (-1)^(1/3)
5132 */
5133
5134 Eval_clock = function() {
5135 push(cadr(p1));
5136 Eval();
5137 return clockform();
5138 };
5139
5140 clockform = function() {
5141 save();
5142 p1 = pop();
5143 push(p1);
5144 mag();
5145 push_integer(-1);
5146 push(p1);
5147 arg();
5148 push(symbol(PI));
5149 divide();
5150 power();
5151 multiply();
5152
5153 /*
5154 p1 = pop()
5155 push(p1)
5156 mag()
5157 push(symbol(E))
5158 push(p1)
5159 arg()
5160 push(imaginaryunit)
5161 multiply()
5162 power()
5163 multiply()
5164 */
5165 return restore();
5166 };
5167
5168 Eval_coeff = function() {
5169 push(cadr(p1));
5170 Eval();
5171 push(caddr(p1));
5172 Eval();
5173 push(cadddr(p1));
5174 Eval();
5175 p3 = pop();
5176 p2 = pop();
5177 p1 = pop();
5178 if (p3 === symbol(NIL)) {
5179 p3 = p2;
5180 p2 = symbol(SYMBOL_X);
5181 }
5182 push(p1);
5183 push(p2);
5184 push(p3);
5185 power();
5186 divide();
5187 push(p2);
5188 return filter();
5189 };
5190
5191 coeff = function() {
5192 var h, n;
5193 save();
5194 p2 = pop();
5195 p1 = pop();
5196 h = tos;
5197 while (1) {
5198 push(p1);
5199 push(p2);
5200 push(zero);
5201 subst();
5202 Eval();
5203 p3 = pop();
5204 push(p3);
5205 push(p1);
5206 push(p3);
5207 subtract();
5208 p1 = pop();
5209 if (equal(p1, zero)) {
5210 n = tos - h;
5211 restore();
5212 return n;
5213 }
5214 push(p1);
5215 push(p2);
5216 divide();
5217 p1 = pop();
5218 }
5219 };
5220
5221 Eval_cofactor = function() {
5222 var doNothing, i, j, n;
5223 i = 0;
5224 j = 0;
5225 n = 0;
5226 push(cadr(p1));
5227 Eval();
5228 p2 = pop();
5229 if (istensor(p2) && p2.tensor.ndim === 2 && p2.tensor.dim[0] === p2.tensor.dim[1]) {
5230 doNothing = 1;
5231 } else {
5232 stop("cofactor: 1st arg: square matrix expected");
5233 }
5234 n = p2.tensor.dim[0];
5235 push(caddr(p1));
5236 Eval();
5237 i = pop_integer();
5238 if (i < 1 || i > n) {
5239 stop("cofactor: 2nd arg: row index expected");
5240 }
5241 push(cadddr(p1));
5242 Eval();
5243 j = pop_integer();
5244 if (j < 1 || j > n) {
5245 stop("cofactor: 3rd arg: column index expected");
5246 }
5247 return cofactor(p2, n, i - 1, j - 1);
5248 };
5249
5250 cofactor = function(p, n, row, col) {
5251 var ac, i, j, o, ref, ref1;
5252 i = 0;
5253 j = 0;
5254 for (i = o = 0, ref = n; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
5255 for (j = ac = 0, ref1 = n; 0 <= ref1 ? ac < ref1 : ac > ref1; j = 0 <= ref1 ? ++ac : --ac) {
5256 if (i !== row && j !== col) {
5257 push(p.tensor.elem[n * i + j]);
5258 }
5259 }
5260 }
5261 determinant(n - 1);
5262 if ((row + col) % 2) {
5263 return negate();
5264 }
5265 };
5266
5267 Eval_condense = function() {
5268 push(cadr(p1));
5269 Eval();
5270 return Condense();
5271 };
5272
5273 Condense = function() {
5274 var tmp;
5275 tmp = 0;
5276 tmp = expanding;
5277 save();
5278 yycondense();
5279 restore();
5280 return expanding = tmp;
5281 };
5282
5283 yycondense = function() {
5284 expanding = 0;
5285 p1 = pop();
5286 if (car(p1) !== symbol(ADD)) {
5287 push(p1);
5288 return;
5289 }
5290 p3 = cdr(p1);
5291 push(car(p3));
5292 p3 = cdr(p3);
5293 while (iscons(p3)) {
5294 push(car(p3));
5295 gcd();
5296 p3 = cdr(p3);
5297 }
5298 inverse();
5299 p2 = pop();
5300 push(zero);
5301 p3 = cdr(p1);
5302 while (iscons(p3)) {
5303 push(p2);
5304 push(car(p3));
5305 multiply();
5306 add();
5307 p3 = cdr(p3);
5308 }
5309 yyexpand();
5310 push(p2);
5311 return divide();
5312 };
5313
5314 Eval_conj = function() {
5315 push(cadr(p1));
5316 Eval();
5317 p1 = pop();
5318 push(p1);
5319 if (!Find(p1, imaginaryunit)) {
5320 polar();
5321 conjugate();
5322 return clockform();
5323 } else {
5324 return conjugate();
5325 }
5326 };
5327
5328 conjugate = function() {
5329 push(imaginaryunit);
5330 push(imaginaryunit);
5331 negate();
5332 subst();
5333 return Eval();
5334 };
5335
5336 consCount = 0;
5337
5338 cons = function() {
5339 var p;
5340 consCount++;
5341 if (DEBUG) {
5342 console.log("cons tos: " + tos + " # " + consCount);
5343 }
5344 p = new U();
5345 p.k = CONS;
5346 p.cons.cdr = pop();
5347 if (p === p.cons.cdr) {
5348 debugger;
5349 console.log("something wrong p == its cdr");
5350 }
5351 p.cons.car = pop();
5352
5353 /*
5354 console.log "cons new cdr.k = " + p.cons.cdr.k + "\nor more in detail:"
5355 print1 p.cons.cdr
5356 console.log "cons new car.k = " + p.cons.car.k + "\nor more in detail:"
5357 print1 p.cons.car
5358 */
5359 return push(p);
5360 };
5361
5362 Eval_contract = function() {
5363 push(cadr(p1));
5364 Eval();
5365 if (cddr(p1) === symbol(NIL)) {
5366 push_integer(1);
5367 push_integer(2);
5368 } else {
5369 push(caddr(p1));
5370 Eval();
5371 push(cadddr(p1));
5372 Eval();
5373 }
5374 return contract();
5375 };
5376
5377 contract = function() {
5378 save();
5379 yycontract();
5380 return restore();
5381 };
5382
5383 yycontract = function() {
5384 var a, ac, ad, ae, af, ag, ah, ai, an, b, h, i, j, k, l, m, n, ndim, nelem, o, ref, ref1, ref2, ref3, ref4, ref5, ref6;
5385 h = 0;
5386 i = 0;
5387 j = 0;
5388 k = 0;
5389 l = 0;
5390 m = 0;
5391 n = 0;
5392 ndim = 0;
5393 nelem = 0;
5394 ai = [];
5395 an = [];
5396 p3 = pop();
5397 p2 = pop();
5398 p1 = pop();
5399 if (!istensor(p1)) {
5400 if (!iszero(p1)) {
5401 stop("contract: tensor expected, 1st arg is not a tensor");
5402 }
5403 push(zero);
5404 return;
5405 }
5406 push(p2);
5407 l = pop_integer();
5408 push(p3);
5409 m = pop_integer();
5410 ndim = p1.tensor.ndim;
5411 if (l < 1 || l > ndim || m < 1 || m > ndim || l === m || p1.tensor.dim[l - 1] !== p1.tensor.dim[m - 1]) {
5412 stop("contract: index out of range");
5413 }
5414 l--;
5415 m--;
5416 n = p1.tensor.dim[l];
5417 nelem = 1;
5418 for (i = o = 0, ref = ndim; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
5419 if (i !== l && i !== m) {
5420 nelem *= p1.tensor.dim[i];
5421 }
5422 }
5423 p2 = alloc_tensor(nelem);
5424 p2.tensor.ndim = ndim - 2;
5425 j = 0;
5426 for (i = ac = 0, ref1 = ndim; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
5427 if (i !== l && i !== m) {
5428 p2.tensor.dim[j++] = p1.tensor.dim[i];
5429 }
5430 }
5431 a = p1.tensor.elem;
5432 b = p2.tensor.elem;
5433 for (i = ad = 0, ref2 = ndim; 0 <= ref2 ? ad < ref2 : ad > ref2; i = 0 <= ref2 ? ++ad : --ad) {
5434 ai[i] = 0;
5435 an[i] = p1.tensor.dim[i];
5436 }
5437 for (i = ae = 0, ref3 = nelem; 0 <= ref3 ? ae < ref3 : ae > ref3; i = 0 <= ref3 ? ++ae : --ae) {
5438 push(zero);
5439 for (j = af = 0, ref4 = n; 0 <= ref4 ? af < ref4 : af > ref4; j = 0 <= ref4 ? ++af : --af) {
5440 ai[l] = j;
5441 ai[m] = j;
5442 h = 0;
5443 for (k = ag = 0, ref5 = ndim; 0 <= ref5 ? ag < ref5 : ag > ref5; k = 0 <= ref5 ? ++ag : --ag) {
5444 h = (h * an[k]) + ai[k];
5445 }
5446 push(a[h]);
5447 add();
5448 }
5449 b[i] = pop();
5450 for (j = ah = ref6 = ndim - 1; ref6 <= 0 ? ah <= 0 : ah >= 0; j = ref6 <= 0 ? ++ah : --ah) {
5451 if (j === l || j === m) {
5452 continue;
5453 }
5454 if (++ai[j] < an[j]) {
5455 break;
5456 }
5457 ai[j] = 0;
5458 }
5459 }
5460 if (nelem === 1) {
5461 return push(b[0]);
5462 } else {
5463 return push(p2);
5464 }
5465 };
5466
5467 Eval_cos = function() {
5468 push(cadr(p1));
5469 Eval();
5470 return cosine();
5471 };
5472
5473 cosine = function() {
5474 save();
5475 p1 = pop();
5476 if (car(p1) === symbol(ADD)) {
5477 cosine_of_angle_sum();
5478 } else {
5479 cosine_of_angle();
5480 }
5481 return restore();
5482 };
5483
5484 cosine_of_angle_sum = function() {
5485 p2 = cdr(p1);
5486 while (iscons(p2)) {
5487 p4 = car(p2);
5488 if (isnpi(p4)) {
5489 push(p1);
5490 push(p4);
5491 subtract();
5492 p3 = pop();
5493 push(p3);
5494 cosine();
5495 push(p4);
5496 cosine();
5497 multiply();
5498 push(p3);
5499 sine();
5500 push(p4);
5501 sine();
5502 multiply();
5503 subtract();
5504 return;
5505 }
5506 p2 = cdr(p2);
5507 }
5508 return cosine_of_angle();
5509 };
5510
5511 cosine_of_angle = function() {
5512 var d, n;
5513 if (car(p1) === symbol(ARCCOS)) {
5514 push(cadr(p1));
5515 return;
5516 }
5517 if (isdouble(p1)) {
5518 d = Math.cos(p1.d);
5519 if (Math.abs(d) < 1e-10) {
5520 d = 0.0;
5521 }
5522 push_double(d);
5523 return;
5524 }
5525 if (isnegative(p1)) {
5526 push(p1);
5527 negate();
5528 p1 = pop();
5529 }
5530 if (car(p1) === symbol(ARCTAN)) {
5531 push_integer(1);
5532 push(cadr(p1));
5533 push_integer(2);
5534 power();
5535 add();
5536 push_rational(-1, 2);
5537 power();
5538 return;
5539 }
5540 push(p1);
5541 push_integer(180);
5542 multiply();
5543 push_symbol(PI);
5544 divide();
5545 n = pop_integer();
5546 if (n < 0 || n === 0x80000000) {
5547 push(symbol(COS));
5548 push(p1);
5549 list(2);
5550 return;
5551 }
5552 switch (n % 360) {
5553 case 90:
5554 case 270:
5555 return push_integer(0);
5556 case 60:
5557 case 300:
5558 return push_rational(1, 2);
5559 case 120:
5560 case 240:
5561 return push_rational(-1, 2);
5562 case 45:
5563 case 315:
5564 push_rational(1, 2);
5565 push_integer(2);
5566 push_rational(1, 2);
5567 power();
5568 return multiply();
5569 case 135:
5570 case 225:
5571 push_rational(-1, 2);
5572 push_integer(2);
5573 push_rational(1, 2);
5574 power();
5575 return multiply();
5576 case 30:
5577 case 330:
5578 push_rational(1, 2);
5579 push_integer(3);
5580 push_rational(1, 2);
5581 power();
5582 return multiply();
5583 case 150:
5584 case 210:
5585 push_rational(-1, 2);
5586 push_integer(3);
5587 push_rational(1, 2);
5588 power();
5589 return multiply();
5590 case 0:
5591 return push_integer(1);
5592 case 180:
5593 return push_integer(-1);
5594 default:
5595 push(symbol(COS));
5596 push(p1);
5597 return list(2);
5598 }
5599 };
5600
5601 Eval_cosh = function() {
5602 push(cadr(p1));
5603 Eval();
5604 return ycosh();
5605 };
5606
5607 ycosh = function() {
5608 save();
5609 yycosh();
5610 return restore();
5611 };
5612
5613 yycosh = function() {
5614 var d;
5615 d = 0.0;
5616 p1 = pop();
5617 if (car(p1) === symbol(ARCCOSH)) {
5618 push(cadr(p1));
5619 return;
5620 }
5621 if (isdouble(p1)) {
5622 d = Math.cosh(p1.d);
5623 if (Math.abs(d) < 1e-10) {
5624 d = 0.0;
5625 }
5626 push_double(d);
5627 return;
5628 }
5629 if (iszero(p1)) {
5630 push(one);
5631 return;
5632 }
5633 push_symbol(COSH);
5634 push(p1);
5635 return list(2);
5636 };
5637
5638 Eval_decomp = function() {
5639 var h;
5640 h = tos;
5641 push(symbol(NIL));
5642 push(cadr(p1));
5643 Eval();
5644 push(caddr(p1));
5645 Eval();
5646 p1 = pop();
5647 if (p1 === symbol(NIL)) {
5648 guess();
5649 } else {
5650 push(p1);
5651 }
5652 decomp();
5653 return list(tos - h);
5654 };
5655
5656 decomp = function() {
5657 save();
5658 p2 = pop();
5659 p1 = pop();
5660 if (Find(p1, p2) === 0) {
5661 push(p1);
5662 restore();
5663 return;
5664 }
5665 if (isadd(p1)) {
5666 decomp_sum();
5667 restore();
5668 return;
5669 }
5670 if (car(p1) === symbol(MULTIPLY)) {
5671 decomp_product();
5672 restore();
5673 return;
5674 }
5675 p3 = cdr(p1);
5676 while (iscons(p3)) {
5677 push(car(p3));
5678 push(p2);
5679 decomp();
5680 p3 = cdr(p3);
5681 }
5682 return restore();
5683 };
5684
5685 decomp_sum = function() {
5686 var h;
5687 h = 0;
5688 p3 = cdr(p1);
5689 while (iscons(p3)) {
5690 if (Find(car(p3), p2)) {
5691 push(car(p3));
5692 push(p2);
5693 decomp();
5694 }
5695 p3 = cdr(p3);
5696 }
5697 h = tos;
5698 p3 = cdr(p1);
5699 while (iscons(p3)) {
5700 if (Find(car(p3), p2) === 0) {
5701 push(car(p3));
5702 }
5703 p3 = cdr(p3);
5704 }
5705 if (tos - h) {
5706 add_all(tos - h);
5707 p3 = pop();
5708 push(p3);
5709 push(p3);
5710 return negate();
5711 }
5712 };
5713
5714 decomp_product = function() {
5715 var h;
5716 h = 0;
5717 p3 = cdr(p1);
5718 while (iscons(p3)) {
5719 if (Find(car(p3), p2)) {
5720 push(car(p3));
5721 push(p2);
5722 decomp();
5723 }
5724 p3 = cdr(p3);
5725 }
5726 h = tos;
5727 p3 = cdr(p1);
5728 while (iscons(p3)) {
5729 if (Find(car(p3), p2) === 0) {
5730 push(car(p3));
5731 }
5732 p3 = cdr(p3);
5733 }
5734 if (tos - h) {
5735 return multiply_all(tos - h);
5736 }
5737 };
5738
5739 define_user_function = function() {
5740 p3 = caadr(p1);
5741 p4 = cdadr(p1);
5742 p5 = caddr(p1);
5743 if (!issymbol(p3)) {
5744 stop("function name?");
5745 }
5746 if (car(p5) === symbol(EVAL)) {
5747 push(cadr(p5));
5748 Eval();
5749 p5 = pop();
5750 }
5751 set_binding_and_arglist(p3, p5, p4);
5752 return push_symbol(NIL);
5753 };
5754
5755 Eval_defint = function() {
5756 push(cadr(p1));
5757 Eval();
5758 p2 = pop();
5759 p1 = cddr(p1);
5760 while (iscons(p1)) {
5761 push(car(p1));
5762 p1 = cdr(p1);
5763 Eval();
5764 p3 = pop();
5765 push(car(p1));
5766 p1 = cdr(p1);
5767 Eval();
5768 p4 = pop();
5769 push(car(p1));
5770 p1 = cdr(p1);
5771 Eval();
5772 p5 = pop();
5773 push(p2);
5774 push(p3);
5775 integral();
5776 p2 = pop();
5777 push(p2);
5778 push(p3);
5779 push(p5);
5780 subst();
5781 Eval();
5782 push(p2);
5783 push(p3);
5784 push(p4);
5785 subst();
5786 Eval();
5787 subtract();
5788 p2 = pop();
5789 }
5790 return push(p2);
5791 };
5792
5793 Eval_degree = function() {
5794 push(cadr(p1));
5795 Eval();
5796 push(caddr(p1));
5797 Eval();
5798 p1 = pop();
5799 if (p1 === symbol(NIL)) {
5800 guess();
5801 } else {
5802 push(p1);
5803 }
5804 return degree();
5805 };
5806
5807 degree = function() {
5808 save();
5809 p2 = pop();
5810 p1 = pop();
5811 p3 = zero;
5812 yydegree(p1);
5813 push(p3);
5814 return restore();
5815 };
5816
5817 yydegree = function(p) {
5818 var results;
5819 if (equal(p, p2)) {
5820 if (iszero(p3)) {
5821 return p3 = one;
5822 }
5823 } else if (car(p) === symbol(POWER)) {
5824 if (equal(cadr(p), p2) && isnum(caddr(p)) && lessp(p3, caddr(p))) {
5825 return p3 = caddr(p);
5826 }
5827 } else if (iscons(p)) {
5828 p = cdr(p);
5829 results = [];
5830 while (iscons(p)) {
5831 yydegree(car(p));
5832 results.push(p = cdr(p));
5833 }
5834 return results;
5835 }
5836 };
5837
5838 Eval_denominator = function() {
5839 push(cadr(p1));
5840 Eval();
5841 return denominator();
5842 };
5843
5844 denominator = function() {
5845 var h;
5846 h = 0;
5847 save();
5848 p1 = pop();
5849 if (car(p1) === symbol(ADD)) {
5850 push(p1);
5851 rationalize();
5852 p1 = pop();
5853 }
5854 if (car(p1) === symbol(MULTIPLY)) {
5855 h = tos;
5856 p1 = cdr(p1);
5857 while (iscons(p1)) {
5858 push(car(p1));
5859 denominator();
5860 p1 = cdr(p1);
5861 }
5862 multiply_all(tos - h);
5863 } else if (isrational(p1)) {
5864 push(p1);
5865 mp_denominator();
5866 } else if (car(p1) === symbol(POWER) && isnegativeterm(caddr(p1))) {
5867 push(p1);
5868 reciprocate();
5869 } else {
5870 push(one);
5871 }
5872 return restore();
5873 };
5874
5875 Eval_derivative = function() {
5876 var ac, doNothing, i, n, o, ref, ref1;
5877 i = 0;
5878 p1 = cdr(p1);
5879 push(car(p1));
5880 Eval();
5881 p1 = cdr(p1);
5882 push(car(p1));
5883 Eval();
5884 p2 = pop();
5885 if (p2 === symbol(NIL)) {
5886 guess();
5887 push(symbol(NIL));
5888 } else if (isnum(p2)) {
5889 guess();
5890 push(p2);
5891 } else {
5892 push(p2);
5893 p1 = cdr(p1);
5894 push(car(p1));
5895 Eval();
5896 }
5897 p5 = pop();
5898 p4 = pop();
5899 p3 = pop();
5900 while (1.) {
5901 if (isnum(p5)) {
5902 push(p5);
5903 n = pop_integer();
5904 if (n === 0x80000000) {
5905 stop("nth derivative: check n");
5906 }
5907 } else {
5908 n = 1;
5909 }
5910 push(p3);
5911 if (n >= 0) {
5912 for (i = o = 0, ref = n; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
5913 push(p4);
5914 derivative();
5915 }
5916 } else {
5917 n = -n;
5918 for (i = ac = 0, ref1 = n; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
5919 push(p4);
5920 integral();
5921 }
5922 }
5923 p3 = pop();
5924 if (p5 === symbol(NIL)) {
5925 break;
5926 }
5927 if (isnum(p5)) {
5928 p1 = cdr(p1);
5929 push(car(p1));
5930 Eval();
5931 p5 = pop();
5932 if (p5 === symbol(NIL)) {
5933 break;
5934 }
5935 if (isnum(p5)) {
5936 doNothing = 1;
5937 } else {
5938 p4 = p5;
5939 p1 = cdr(p1);
5940 push(car(p1));
5941 Eval();
5942 p5 = pop();
5943 }
5944 } else {
5945 p4 = p5;
5946 p1 = cdr(p1);
5947 push(car(p1));
5948 Eval();
5949 p5 = pop();
5950 }
5951 }
5952 return push(p3);
5953 };
5954
5955 derivative = function() {
5956 save();
5957 p2 = pop();
5958 p1 = pop();
5959 if (isnum(p2)) {
5960 stop("undefined function");
5961 }
5962 if (istensor(p1)) {
5963 if (istensor(p2)) {
5964 d_tensor_tensor();
5965 } else {
5966 d_tensor_scalar();
5967 }
5968 } else {
5969 if (istensor(p2)) {
5970 d_scalar_tensor();
5971 } else {
5972 d_scalar_scalar();
5973 }
5974 }
5975 return restore();
5976 };
5977
5978 d_scalar_scalar = function() {
5979 if (issymbol(p2)) {
5980 return d_scalar_scalar_1();
5981 } else {
5982 push(p1);
5983 push(p2);
5984 push(symbol(SECRETX));
5985 subst();
5986 push(symbol(SECRETX));
5987 derivative();
5988 push(symbol(SECRETX));
5989 push(p2);
5990 return subst();
5991 }
5992 };
5993
5994 d_scalar_scalar_1 = function() {
5995 if (equal(p1, p2)) {
5996 push(one);
5997 return;
5998 }
5999 if (!iscons(p1)) {
6000 push(zero);
6001 return;
6002 }
6003 if (isadd(p1)) {
6004 dsum();
6005 return;
6006 }
6007 if (car(p1) === symbol(MULTIPLY)) {
6008 dproduct();
6009 return;
6010 }
6011 if (car(p1) === symbol(POWER)) {
6012 dpower();
6013 return;
6014 }
6015 if (car(p1) === symbol(DERIVATIVE)) {
6016 dd();
6017 return;
6018 }
6019 if (car(p1) === symbol(LOG)) {
6020 dlog();
6021 return;
6022 }
6023 if (car(p1) === symbol(SIN)) {
6024 dsin();
6025 return;
6026 }
6027 if (car(p1) === symbol(COS)) {
6028 dcos();
6029 return;
6030 }
6031 if (car(p1) === symbol(TAN)) {
6032 dtan();
6033 return;
6034 }
6035 if (car(p1) === symbol(ARCSIN)) {
6036 darcsin();
6037 return;
6038 }
6039 if (car(p1) === symbol(ARCCOS)) {
6040 darccos();
6041 return;
6042 }
6043 if (car(p1) === symbol(ARCTAN)) {
6044 darctan();
6045 return;
6046 }
6047 if (car(p1) === symbol(SINH)) {
6048 dsinh();
6049 return;
6050 }
6051 if (car(p1) === symbol(COSH)) {
6052 dcosh();
6053 return;
6054 }
6055 if (car(p1) === symbol(TANH)) {
6056 dtanh();
6057 return;
6058 }
6059 if (car(p1) === symbol(ARCSINH)) {
6060 darcsinh();
6061 return;
6062 }
6063 if (car(p1) === symbol(ARCCOSH)) {
6064 darccosh();
6065 return;
6066 }
6067 if (car(p1) === symbol(ARCTANH)) {
6068 darctanh();
6069 return;
6070 }
6071 if (car(p1) === symbol(ABS)) {
6072 dabs();
6073 return;
6074 }
6075 if (car(p1) === symbol(SGN)) {
6076 dsgn();
6077 return;
6078 }
6079 if (car(p1) === symbol(HERMITE)) {
6080 dhermite();
6081 return;
6082 }
6083 if (car(p1) === symbol(ERF)) {
6084 derf();
6085 return;
6086 }
6087 if (car(p1) === symbol(ERFC)) {
6088 derfc();
6089 return;
6090 }
6091 if (car(p1) === symbol(BESSELJ)) {
6092 if (iszero(caddr(p1))) {
6093 dbesselj0();
6094 } else {
6095 dbesseljn();
6096 }
6097 return;
6098 }
6099 if (car(p1) === symbol(BESSELY)) {
6100 if (iszero(caddr(p1))) {
6101 dbessely0();
6102 } else {
6103 dbesselyn();
6104 }
6105 return;
6106 }
6107 if (car(p1) === symbol(INTEGRAL) && caddr(p1) === p2) {
6108 derivative_of_integral();
6109 return;
6110 }
6111 return dfunction();
6112 };
6113
6114 dsum = function() {
6115 var h;
6116 h = tos;
6117 p1 = cdr(p1);
6118 while (iscons(p1)) {
6119 push(car(p1));
6120 push(p2);
6121 derivative();
6122 p1 = cdr(p1);
6123 }
6124 return add_all(tos - h);
6125 };
6126
6127 dproduct = function() {
6128 var ac, i, j, n, o, ref, ref1;
6129 i = 0;
6130 j = 0;
6131 n = 0;
6132 n = length(p1) - 1;
6133 for (i = o = 0, ref = n; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
6134 p3 = cdr(p1);
6135 for (j = ac = 0, ref1 = n; 0 <= ref1 ? ac < ref1 : ac > ref1; j = 0 <= ref1 ? ++ac : --ac) {
6136 push(car(p3));
6137 if (i === j) {
6138 push(p2);
6139 derivative();
6140 }
6141 p3 = cdr(p3);
6142 }
6143 multiply_all(n);
6144 }
6145 return add_all(n);
6146 };
6147
6148 dpower = function() {
6149 push(caddr(p1));
6150 push(cadr(p1));
6151 divide();
6152 push(cadr(p1));
6153 push(p2);
6154 derivative();
6155 multiply();
6156 push(cadr(p1));
6157 logarithm();
6158 push(caddr(p1));
6159 push(p2);
6160 derivative();
6161 multiply();
6162 add();
6163 push(p1);
6164 return multiply();
6165 };
6166
6167 dlog = function() {
6168 push(cadr(p1));
6169 push(p2);
6170 derivative();
6171 push(cadr(p1));
6172 return divide();
6173 };
6174
6175 dd = function() {
6176 push(cadr(p1));
6177 push(p2);
6178 derivative();
6179 p3 = pop();
6180 if (car(p3) === symbol(DERIVATIVE)) {
6181 push_symbol(DERIVATIVE);
6182 push_symbol(DERIVATIVE);
6183 push(cadr(p3));
6184 if (lessp(caddr(p3), caddr(p1))) {
6185 push(caddr(p3));
6186 list(3);
6187 push(caddr(p1));
6188 } else {
6189 push(caddr(p1));
6190 list(3);
6191 push(caddr(p3));
6192 }
6193 return list(3);
6194 } else {
6195 push(p3);
6196 push(caddr(p1));
6197 return derivative();
6198 }
6199 };
6200
6201 dfunction = function() {
6202 p3 = cdr(p1);
6203 if (p3 === symbol(NIL) || Find(p3, p2)) {
6204 push_symbol(DERIVATIVE);
6205 push(p1);
6206 push(p2);
6207 return list(3);
6208 } else {
6209 return push(zero);
6210 }
6211 };
6212
6213 dsin = function() {
6214 push(cadr(p1));
6215 push(p2);
6216 derivative();
6217 push(cadr(p1));
6218 cosine();
6219 return multiply();
6220 };
6221
6222 dcos = function() {
6223 push(cadr(p1));
6224 push(p2);
6225 derivative();
6226 push(cadr(p1));
6227 sine();
6228 multiply();
6229 return negate();
6230 };
6231
6232 dtan = function() {
6233 push(cadr(p1));
6234 push(p2);
6235 derivative();
6236 push(cadr(p1));
6237 cosine();
6238 push_integer(-2);
6239 power();
6240 return multiply();
6241 };
6242
6243 darcsin = function() {
6244 push(cadr(p1));
6245 push(p2);
6246 derivative();
6247 push_integer(1);
6248 push(cadr(p1));
6249 push_integer(2);
6250 power();
6251 subtract();
6252 push_rational(-1, 2);
6253 power();
6254 return multiply();
6255 };
6256
6257 darccos = function() {
6258 push(cadr(p1));
6259 push(p2);
6260 derivative();
6261 push_integer(1);
6262 push(cadr(p1));
6263 push_integer(2);
6264 power();
6265 subtract();
6266 push_rational(-1, 2);
6267 power();
6268 multiply();
6269 return negate();
6270 };
6271
6272 darctan = function() {
6273 push(cadr(p1));
6274 push(p2);
6275 derivative();
6276 push_integer(1);
6277 push(cadr(p1));
6278 push_integer(2);
6279 power();
6280 add();
6281 inverse();
6282 multiply();
6283 return simplify();
6284 };
6285
6286 dsinh = function() {
6287 push(cadr(p1));
6288 push(p2);
6289 derivative();
6290 push(cadr(p1));
6291 ycosh();
6292 return multiply();
6293 };
6294
6295 dcosh = function() {
6296 push(cadr(p1));
6297 push(p2);
6298 derivative();
6299 push(cadr(p1));
6300 ysinh();
6301 return multiply();
6302 };
6303
6304 dtanh = function() {
6305 push(cadr(p1));
6306 push(p2);
6307 derivative();
6308 push(cadr(p1));
6309 ycosh();
6310 push_integer(-2);
6311 power();
6312 return multiply();
6313 };
6314
6315 darcsinh = function() {
6316 push(cadr(p1));
6317 push(p2);
6318 derivative();
6319 push(cadr(p1));
6320 push_integer(2);
6321 power();
6322 push_integer(1);
6323 add();
6324 push_rational(-1, 2);
6325 power();
6326 return multiply();
6327 };
6328
6329 darccosh = function() {
6330 push(cadr(p1));
6331 push(p2);
6332 derivative();
6333 push(cadr(p1));
6334 push_integer(2);
6335 power();
6336 push_integer(-1);
6337 add();
6338 push_rational(-1, 2);
6339 power();
6340 return multiply();
6341 };
6342
6343 darctanh = function() {
6344 push(cadr(p1));
6345 push(p2);
6346 derivative();
6347 push_integer(1);
6348 push(cadr(p1));
6349 push_integer(2);
6350 power();
6351 subtract();
6352 inverse();
6353 return multiply();
6354 };
6355
6356 dabs = function() {
6357 push(cadr(p1));
6358 push(p2);
6359 derivative();
6360 push(cadr(p1));
6361 sgn();
6362 return multiply();
6363 };
6364
6365 dsgn = function() {
6366 push(cadr(p1));
6367 push(p2);
6368 derivative();
6369 push(cadr(p1));
6370 dirac();
6371 multiply();
6372 push_integer(2);
6373 return multiply();
6374 };
6375
6376 dhermite = function() {
6377 push(cadr(p1));
6378 push(p2);
6379 derivative();
6380 push_integer(2);
6381 push(caddr(p1));
6382 multiply();
6383 multiply();
6384 push(cadr(p1));
6385 push(caddr(p1));
6386 push_integer(-1);
6387 add();
6388 hermite();
6389 return multiply();
6390 };
6391
6392 derf = function() {
6393 push(cadr(p1));
6394 push_integer(2);
6395 power();
6396 push_integer(-1);
6397 multiply();
6398 exponential();
6399 push_symbol(PI);
6400 push_rational(-1, 2);
6401 power();
6402 multiply();
6403 push_integer(2);
6404 multiply();
6405 push(cadr(p1));
6406 push(p2);
6407 derivative();
6408 return multiply();
6409 };
6410
6411 derfc = function() {
6412 push(cadr(p1));
6413 push_integer(2);
6414 power();
6415 push_integer(-1);
6416 multiply();
6417 exponential();
6418 push_symbol(PI);
6419 push_rational(-1, 2);
6420 power();
6421 multiply();
6422 push_integer(-2);
6423 multiply();
6424 push(cadr(p1));
6425 push(p2);
6426 derivative();
6427 return multiply();
6428 };
6429
6430 dbesselj0 = function() {
6431 push(cadr(p1));
6432 push(p2);
6433 derivative();
6434 push(cadr(p1));
6435 push_integer(1);
6436 besselj();
6437 multiply();
6438 push_integer(-1);
6439 return multiply();
6440 };
6441
6442 dbesseljn = function() {
6443 push(cadr(p1));
6444 push(p2);
6445 derivative();
6446 push(cadr(p1));
6447 push(caddr(p1));
6448 push_integer(-1);
6449 add();
6450 besselj();
6451 push(caddr(p1));
6452 push_integer(-1);
6453 multiply();
6454 push(cadr(p1));
6455 divide();
6456 push(cadr(p1));
6457 push(caddr(p1));
6458 besselj();
6459 multiply();
6460 add();
6461 return multiply();
6462 };
6463
6464 dbessely0 = function() {
6465 push(cadr(p1));
6466 push(p2);
6467 derivative();
6468 push(cadr(p1));
6469 push_integer(1);
6470 besselj();
6471 multiply();
6472 push_integer(-1);
6473 return multiply();
6474 };
6475
6476 dbesselyn = function() {
6477 push(cadr(p1));
6478 push(p2);
6479 derivative();
6480 push(cadr(p1));
6481 push(caddr(p1));
6482 push_integer(-1);
6483 add();
6484 bessely();
6485 push(caddr(p1));
6486 push_integer(-1);
6487 multiply();
6488 push(cadr(p1));
6489 divide();
6490 push(cadr(p1));
6491 push(caddr(p1));
6492 bessely();
6493 multiply();
6494 add();
6495 return multiply();
6496 };
6497
6498 derivative_of_integral = function() {
6499 return push(cadr(p1));
6500 };
6501
6502 DET_check_arg = function() {
6503 if (!istensor(p1)) {
6504 return 0;
6505 } else if (p1.tensor.ndim !== 2) {
6506 return 0;
6507 } else if (p1.tensor.dim[0] !== p1.tensor.dim[1]) {
6508 return 0;
6509 } else {
6510 return 1;
6511 }
6512 };
6513
6514 det = function() {
6515 var a, ac, i, n, o, ref, ref1;
6516 i = 0;
6517 n = 0;
6518 save();
6519 p1 = pop();
6520 if (DET_check_arg() === 0) {
6521 push_symbol(DET);
6522 push(p1);
6523 list(2);
6524 restore();
6525 return;
6526 }
6527 n = p1.tensor.nelem;
6528 a = p1.tensor.elem;
6529 for (i = o = 0, ref = n; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
6530 if (!isnum(a[i])) {
6531 break;
6532 }
6533 }
6534 if (i === n) {
6535 yydetg();
6536 } else {
6537 for (i = ac = 0, ref1 = p1.tensor.nelem; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
6538 push(p1.tensor.elem[i]);
6539 }
6540 determinant(p1.tensor.dim[0]);
6541 }
6542 return restore();
6543 };
6544
6545 determinant = function(n) {
6546 var a, ac, breakFromOutherWhile, h, i, j, k, o, q, ref, ref1, s, sign_, t;
6547 h = 0;
6548 i = 0;
6549 j = 0;
6550 k = 0;
6551 q = 0;
6552 s = 0;
6553 sign_ = 0;
6554 t = 0;
6555 a = [];
6556 h = tos - n * n;
6557 for (i = o = 0, ref = n; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
6558 a[i] = i;
6559 a[i + n] = 0;
6560 a[i + n + n] = 1;
6561 }
6562 sign_ = 1;
6563 push(zero);
6564 while (1) {
6565 if (sign_ === 1) {
6566 push_integer(1);
6567 } else {
6568 push_integer(-1);
6569 }
6570 for (i = ac = 0, ref1 = n; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
6571 k = n * a[i] + i;
6572 push(stack[h + k]);
6573 multiply();
6574 }
6575 add();
6576 j = n - 1;
6577 s = 0;
6578 breakFromOutherWhile = false;
6579 while (1) {
6580 q = a[n + j] + a[n + n + j];
6581 if (q < 0) {
6582 a[n + n + j] = -a[n + n + j];
6583 j--;
6584 continue;
6585 }
6586 if (q === j + 1) {
6587 if (j === 0) {
6588 breakFromOutherWhile = true;
6589 break;
6590 }
6591 s++;
6592 a[n + n + j] = -a[n + n + j];
6593 j--;
6594 continue;
6595 }
6596 break;
6597 }
6598 if (breakFromOutherWhile) {
6599 break;
6600 }
6601 t = a[j - a[n + j] + s];
6602 a[j - a[n + j] + s] = a[j - q + s];
6603 a[j - q + s] = t;
6604 a[n + j] = q;
6605 sign_ = -sign_;
6606 }
6607 stack[h] = stack[tos - 1];
6608 return tos = h + 1;
6609 };
6610
6611 detg = function() {
6612 save();
6613 p1 = pop();
6614 if (DET_check_arg() === 0) {
6615 push_symbol(DET);
6616 push(p1);
6617 list(2);
6618 restore();
6619 return;
6620 }
6621 yydetg();
6622 return restore();
6623 };
6624
6625 yydetg = function() {
6626 var i, n, o, ref;
6627 i = 0;
6628 n = 0;
6629 n = p1.tensor.dim[0];
6630 for (i = o = 0, ref = n * n; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
6631 push(p1.tensor.elem[i]);
6632 }
6633 lu_decomp(n);
6634 tos -= n * n;
6635 return push(p1);
6636 };
6637
6638 M = function(h, n, i, j) {
6639 return stack[h + n * i + j];
6640 };
6641
6642 setM = function(h, n, i, j, value) {
6643 return stack[h + n * i + j] = value;
6644 };
6645
6646 lu_decomp = function(n) {
6647 var ac, ad, ae, af, d, h, i, j, o, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8;
6648 d = 0;
6649 h = 0;
6650 i = 0;
6651 j = 0;
6652 h = tos - n * n;
6653 p1 = one;
6654 for (d = o = 0, ref = n - 1; 0 <= ref ? o < ref : o > ref; d = 0 <= ref ? ++o : --o) {
6655 if (equal(M(h, n, d, d), zero)) {
6656 for (i = ac = ref1 = d + 1, ref2 = n; ref1 <= ref2 ? ac < ref2 : ac > ref2; i = ref1 <= ref2 ? ++ac : --ac) {
6657 if (!equal(M(h, n, i, d), zero)) {
6658 break;
6659 }
6660 }
6661 if (i === n) {
6662 p1 = zero;
6663 break;
6664 }
6665 for (j = ad = ref3 = d, ref4 = n; ref3 <= ref4 ? ad < ref4 : ad > ref4; j = ref3 <= ref4 ? ++ad : --ad) {
6666 p2 = M(h, n, d, j);
6667 setM(h, n, d, j, M(h, n, i, j));
6668 setM(h, n, i, j, p2);
6669 }
6670 push(p1);
6671 negate();
6672 p1 = pop();
6673 }
6674 push(p1);
6675 push(M(h, n, d, d));
6676 multiply();
6677 p1 = pop();
6678 for (i = ae = ref5 = d + 1, ref6 = n; ref5 <= ref6 ? ae < ref6 : ae > ref6; i = ref5 <= ref6 ? ++ae : --ae) {
6679 push(M(h, n, i, d));
6680 push(M(h, n, d, d));
6681 divide();
6682 negate();
6683 p2 = pop();
6684 setM(h, n, i, d, zero);
6685 for (j = af = ref7 = d + 1, ref8 = n; ref7 <= ref8 ? af < ref8 : af > ref8; j = ref7 <= ref8 ? ++af : --af) {
6686 push(M(h, n, d, j));
6687 push(p2);
6688 multiply();
6689 push(M(h, n, i, j));
6690 add();
6691 setM(h, n, i, j, pop());
6692 }
6693 }
6694 }
6695 push(p1);
6696 push(M(h, n, n - 1, n - 1));
6697 multiply();
6698 return p1 = pop();
6699 };
6700
6701 Eval_dirac = function() {
6702 push(cadr(p1));
6703 Eval();
6704 return dirac();
6705 };
6706
6707 dirac = function() {
6708 save();
6709 ydirac();
6710 return restore();
6711 };
6712
6713 ydirac = function() {
6714 p1 = pop();
6715 if (isdouble(p1)) {
6716 if (p1.d === 0) {
6717 push_integer(1);
6718 return;
6719 } else {
6720 push_integer(0);
6721 return;
6722 }
6723 }
6724 if (isrational(p1)) {
6725 if (MZERO(mmul(p1.q.a, p1.q.b))) {
6726 push_integer(1);
6727 return;
6728 } else {
6729 push_integer(0);
6730 return;
6731 }
6732 }
6733 if (car(p1) === symbol(POWER)) {
6734 push_symbol(DIRAC);
6735 push(cadr(p1));
6736 list(2);
6737 return;
6738 }
6739 if (isnegativeterm(p1)) {
6740 push_symbol(DIRAC);
6741 push(p1);
6742 negate();
6743 list(2);
6744 return;
6745 }
6746 if (isnegativeterm(p1) || (car(p1) === symbol(ADD) && isnegativeterm(cadr(p1)))) {
6747 push(p1);
6748 negate();
6749 p1 = pop();
6750 }
6751 push_symbol(DIRAC);
6752 push(p1);
6753 return list(2);
6754 };
6755
6756 divisors = function() {
6757 var h, i, n, o, ref, subsetOfStack;
6758 i = 0;
6759 h = 0;
6760 n = 0;
6761 save();
6762 h = tos - 1;
6763 divisors_onstack();
6764 n = tos - h;
6765 subsetOfStack = stack.slice(h, h + n);
6766 subsetOfStack.sort(cmp_expr);
6767 stack = stack.slice(0, h).concat(subsetOfStack).concat(stack.slice(h + n));
6768 p1 = alloc_tensor(n);
6769 p1.tensor.ndim = 1;
6770 p1.tensor.dim[0] = n;
6771 for (i = o = 0, ref = n; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
6772 p1.tensor.elem[i] = stack[h + i];
6773 }
6774 tos = h;
6775 push(p1);
6776 return restore();
6777 };
6778
6779 divisors_onstack = function() {
6780 var h, i, k, n, o, ref;
6781 h = 0;
6782 i = 0;
6783 k = 0;
6784 n = 0;
6785 save();
6786 p1 = pop();
6787 h = tos;
6788 if (isnum(p1)) {
6789 push(p1);
6790 factor_small_number();
6791 } else if (car(p1) === symbol(ADD)) {
6792 push(p1);
6793 __factor_add();
6794 } else if (car(p1) === symbol(MULTIPLY)) {
6795 p1 = cdr(p1);
6796 if (isnum(car(p1))) {
6797 push(car(p1));
6798 factor_small_number();
6799 p1 = cdr(p1);
6800 }
6801 while (iscons(p1)) {
6802 p2 = car(p1);
6803 if (car(p2) === symbol(POWER)) {
6804 push(cadr(p2));
6805 push(caddr(p2));
6806 } else {
6807 push(p2);
6808 push(one);
6809 }
6810 p1 = cdr(p1);
6811 }
6812 } else if (car(p1) === symbol(POWER)) {
6813 push(cadr(p1));
6814 push(caddr(p1));
6815 } else {
6816 push(p1);
6817 push(one);
6818 }
6819 k = tos;
6820 push(one);
6821 gen(h, k);
6822 n = tos - k;
6823 for (i = o = 0, ref = n; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
6824 stack[h + i] = stack[k + i];
6825 }
6826 tos = h + n;
6827 return restore();
6828 };
6829
6830 gen = function(h, k) {
6831 var expo, i, o, ref;
6832 expo = 0;
6833 i = 0;
6834 save();
6835 p1 = pop();
6836 if (h === k) {
6837 push(p1);
6838 restore();
6839 return;
6840 }
6841 p2 = stack[h + 0];
6842 p3 = stack[h + 1];
6843 push(p3);
6844 expo = pop_integer();
6845 if (expo !== 0x80000000) {
6846 for (i = o = 0, ref = Math.abs(expo); 0 <= ref ? o <= ref : o >= ref; i = 0 <= ref ? ++o : --o) {
6847 push(p1);
6848 push(p2);
6849 push_integer(sign(expo) * i);
6850 power();
6851 multiply();
6852 gen(h + 2, k);
6853 }
6854 }
6855 return restore();
6856 };
6857
6858 __factor_add = function() {
6859 save();
6860 p1 = pop();
6861 p3 = cdr(p1);
6862 push(car(p3));
6863 p3 = cdr(p3);
6864 while (iscons(p3)) {
6865 push(car(p3));
6866 gcd();
6867 p3 = cdr(p3);
6868 }
6869 p2 = pop();
6870 if (isplusone(p2)) {
6871 push(p1);
6872 push(one);
6873 restore();
6874 return;
6875 }
6876 if (isnum(p2)) {
6877 push(p2);
6878 factor_small_number();
6879 } else if (car(p2) === symbol(MULTIPLY)) {
6880 p3 = cdr(p2);
6881 if (isnum(car(p3))) {
6882 push(car(p3));
6883 factor_small_number();
6884 } else {
6885 push(car(p3));
6886 push(one);
6887 }
6888 p3 = cdr(p3);
6889 while (iscons(p3)) {
6890 push(car(p3));
6891 push(one);
6892 p3 = cdr(p3);
6893 }
6894 } else {
6895 push(p2);
6896 push(one);
6897 }
6898 push(p2);
6899 inverse();
6900 p2 = pop();
6901 push(zero);
6902 p3 = cdr(p1);
6903 while (iscons(p3)) {
6904 push(p2);
6905 push(car(p3));
6906 multiply();
6907 add();
6908 p3 = cdr(p3);
6909 }
6910 push(one);
6911 return restore();
6912 };
6913
6914 dpow = function() {
6915 var a, b, base, expo, result, theta;
6916 a = 0.0;
6917 b = 0.0;
6918 base = 0.0;
6919 expo = 0.0;
6920 result = 0.0;
6921 theta = 0.0;
6922 expo = pop_double();
6923 base = pop_double();
6924 if (base === 0.0 && expo < 0.0) {
6925 stop("divide by zero");
6926 }
6927 if (base >= 0.0 || (expo % 1.0) === 0.0) {
6928 result = Math.pow(base, expo);
6929 push_double(result);
6930 return;
6931 }
6932 result = Math.pow(Math.abs(base), expo);
6933 theta = Math.PI * expo;
6934 if ((expo % 0.5) === 0.0) {
6935 a = 0.0;
6936 b = Math.sin(theta);
6937 } else {
6938 a = Math.cos(theta);
6939 b = Math.sin(theta);
6940 }
6941 push_double(a * result);
6942 push_double(b * result);
6943 push(imaginaryunit);
6944 multiply();
6945 return add();
6946 };
6947
6948 EIG_N = 0;
6949
6950 EIG_yydd = [];
6951
6952 EIG_yyqq = [];
6953
6954 Eval_eigen = function() {
6955 if (EIG_check_arg() === 0) {
6956 stop("eigen: argument is not a square matrix");
6957 }
6958 eigen(EIGEN);
6959 p1 = usr_symbol("D");
6960 set_binding(p1, p2);
6961 p1 = usr_symbol("Q");
6962 set_binding(p1, p3);
6963 return push(symbol(NIL));
6964 };
6965
6966 Eval_eigenval = function() {
6967 if (EIG_check_arg() === 0) {
6968 push_symbol(EIGENVAL);
6969 push(p1);
6970 list(2);
6971 return;
6972 }
6973 eigen(EIGENVAL);
6974 return push(p2);
6975 };
6976
6977 Eval_eigenvec = function() {
6978 if (EIG_check_arg() === 0) {
6979 push_symbol(EIGENVEC);
6980 push(p1);
6981 list(2);
6982 return;
6983 }
6984 eigen(EIGENVEC);
6985 return push(p3);
6986 };
6987
6988 EIG_check_arg = function() {
6989 var ac, ad, ae, i, j, o, ref, ref1, ref2, ref3, ref4;
6990 i = 0;
6991 j = 0;
6992 push(cadr(p1));
6993 Eval();
6994 yyfloat();
6995 Eval();
6996 p1 = pop();
6997 if (!istensor(p1)) {
6998 return 0;
6999 }
7000 if (p1.tensor.ndim !== 2 || p1.tensor.dim[0] !== p1.tensor.dim[1]) {
7001 stop("eigen: argument is not a square matrix");
7002 }
7003 EIG_N = p1.tensor.dim[0];
7004 for (i = o = 0, ref = EIG_N; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
7005 for (j = ac = 0, ref1 = EIG_N; 0 <= ref1 ? ac < ref1 : ac > ref1; j = 0 <= ref1 ? ++ac : --ac) {
7006 if (!isdouble(p1.tensor.elem[EIG_N * i + j])) {
7007 stop("eigen: matrix is not numerical");
7008 }
7009 }
7010 }
7011 for (i = ad = 0, ref2 = EIG_N - 1; 0 <= ref2 ? ad < ref2 : ad > ref2; i = 0 <= ref2 ? ++ad : --ad) {
7012 for (j = ae = ref3 = i + 1, ref4 = EIG_N; ref3 <= ref4 ? ae < ref4 : ae > ref4; j = ref3 <= ref4 ? ++ae : --ae) {
7013 if (Math.abs(p1.tensor.elem[EIG_N * i + j].d - p1.tensor.elem[EIG_N * j + i].d) > 1e-10) {
7014 stop("eigen: matrix is not symmetrical");
7015 }
7016 }
7017 }
7018 return 1;
7019 };
7020
7021 eigen = function(op) {
7022 var ac, ad, ae, af, ag, ah, aj, al, am, i, j, o, ref, ref1, ref10, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, results;
7023 i = 0;
7024 j = 0;
7025 for (i = o = 0, ref = EIG_N * EIG_N; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
7026 EIG_yydd[i] = 0.0;
7027 }
7028 for (i = ac = 0, ref1 = EIG_N * EIG_N; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
7029 EIG_yyqq[i] = 0.0;
7030 }
7031 for (i = ad = 0, ref2 = EIG_N; 0 <= ref2 ? ad < ref2 : ad > ref2; i = 0 <= ref2 ? ++ad : --ad) {
7032 EIG_yydd[EIG_N * i + i] = p1.tensor.elem[EIG_N * i + i].d;
7033 for (j = ae = ref3 = i + 1, ref4 = EIG_N; ref3 <= ref4 ? ae < ref4 : ae > ref4; j = ref3 <= ref4 ? ++ae : --ae) {
7034 EIG_yydd[EIG_N * i + j] = p1.tensor.elem[EIG_N * i + j].d;
7035 EIG_yydd[EIG_N * j + i] = p1.tensor.elem[EIG_N * i + j].d;
7036 }
7037 }
7038 for (i = af = 0, ref5 = EIG_N; 0 <= ref5 ? af < ref5 : af > ref5; i = 0 <= ref5 ? ++af : --af) {
7039 EIG_yyqq[EIG_N * i + i] = 1.0;
7040 for (j = ag = ref6 = i + 1, ref7 = EIG_N; ref6 <= ref7 ? ag < ref7 : ag > ref7; j = ref6 <= ref7 ? ++ag : --ag) {
7041 EIG_yyqq[EIG_N * i + j] = 0.0;
7042 EIG_yyqq[EIG_N * j + i] = 0.0;
7043 }
7044 }
7045 for (i = ah = 0; ah < 100; i = ++ah) {
7046 if (step() === 0) {
7047 break;
7048 }
7049 }
7050 if (i === 100) {
7051 printstr("\nnote: eigen did not converge\n");
7052 }
7053 if (op === EIGEN || op === EIGENVAL) {
7054 push(p1);
7055 copy_tensor();
7056 p2 = pop();
7057 for (i = aj = 0, ref8 = EIG_N; 0 <= ref8 ? aj < ref8 : aj > ref8; i = 0 <= ref8 ? ++aj : --aj) {
7058 for (j = al = 0, ref9 = EIG_N; 0 <= ref9 ? al < ref9 : al > ref9; j = 0 <= ref9 ? ++al : --al) {
7059 push_double(EIG_yydd[EIG_N * i + j]);
7060 p2.tensor.elem[EIG_N * i + j] = pop();
7061 }
7062 }
7063 }
7064 if (op === EIGEN || op === EIGENVEC) {
7065 push(p1);
7066 copy_tensor();
7067 p3 = pop();
7068 results = [];
7069 for (i = am = 0, ref10 = EIG_N; 0 <= ref10 ? am < ref10 : am > ref10; i = 0 <= ref10 ? ++am : --am) {
7070 results.push((function() {
7071 var ao, ref11, results1;
7072 results1 = [];
7073 for (j = ao = 0, ref11 = EIG_N; 0 <= ref11 ? ao < ref11 : ao > ref11; j = 0 <= ref11 ? ++ao : --ao) {
7074 push_double(EIG_yyqq[EIG_N * i + j]);
7075 results1.push(p3.tensor.elem[EIG_N * i + j] = pop());
7076 }
7077 return results1;
7078 })());
7079 }
7080 return results;
7081 }
7082 };
7083
7084 step = function() {
7085 var ac, count, i, j, o, ref, ref1, ref2;
7086 i = 0;
7087 j = 0;
7088 count = 0;
7089 for (i = o = 0, ref = EIG_N - 1; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
7090 for (j = ac = ref1 = i + 1, ref2 = EIG_N; ref1 <= ref2 ? ac < ref2 : ac > ref2; j = ref1 <= ref2 ? ++ac : --ac) {
7091 if (EIG_yydd[EIG_N * i + j] !== 0.0) {
7092 step2(i, j);
7093 count++;
7094 }
7095 }
7096 }
7097 return count;
7098 };
7099
7100 step2 = function(p, q) {
7101 var ac, ad, c, cc, k, o, ref, ref1, ref2, s, ss, t, theta;
7102 k = 0;
7103 t = 0.0;
7104 theta = 0.0;
7105 c = 0.0;
7106 cc = 0.0;
7107 s = 0.0;
7108 ss = 0.0;
7109 theta = 0.5 * (EIG_yydd[EIG_N * p + p] - EIG_yydd[EIG_N * q + q]) / EIG_yydd[EIG_N * p + q];
7110 t = 1.0 / (Math.abs(theta) + Math.sqrt(theta * theta + 1.0));
7111 if (theta < 0.0) {
7112 t = -t;
7113 }
7114 c = 1.0 / Math.sqrt(t * t + 1.0);
7115 s = t * c;
7116 for (k = o = 0, ref = EIG_N; 0 <= ref ? o < ref : o > ref; k = 0 <= ref ? ++o : --o) {
7117 cc = EIG_yydd[EIG_N * p + k];
7118 ss = EIG_yydd[EIG_N * q + k];
7119 EIG_yydd[EIG_N * p + k] = c * cc + s * ss;
7120 EIG_yydd[EIG_N * q + k] = c * ss - s * cc;
7121 }
7122 for (k = ac = 0, ref1 = EIG_N; 0 <= ref1 ? ac < ref1 : ac > ref1; k = 0 <= ref1 ? ++ac : --ac) {
7123 cc = EIG_yydd[EIG_N * k + p];
7124 ss = EIG_yydd[EIG_N * k + q];
7125 EIG_yydd[EIG_N * k + p] = c * cc + s * ss;
7126 EIG_yydd[EIG_N * k + q] = c * ss - s * cc;
7127 }
7128 for (k = ad = 0, ref2 = EIG_N; 0 <= ref2 ? ad < ref2 : ad > ref2; k = 0 <= ref2 ? ++ad : --ad) {
7129 cc = EIG_yyqq[EIG_N * p + k];
7130 ss = EIG_yyqq[EIG_N * q + k];
7131 EIG_yyqq[EIG_N * p + k] = c * cc + s * ss;
7132 EIG_yyqq[EIG_N * q + k] = c * ss - s * cc;
7133 }
7134 EIG_yydd[EIG_N * p + q] = 0.0;
7135 return EIG_yydd[EIG_N * q + p] = 0.0;
7136 };
7137
7138 Eval_erf = function() {
7139 push(cadr(p1));
7140 Eval();
7141 return yerf();
7142 };
7143
7144 yerf = function() {
7145 save();
7146 yyerf();
7147 return restore();
7148 };
7149
7150 yyerf = function() {
7151 var d;
7152 d = 0.0;
7153 p1 = pop();
7154 if (isdouble(p1)) {
7155 d = 1.0 - erfc(p1.d);
7156 push_double(d);
7157 return;
7158 }
7159 if (isnegativeterm(p1)) {
7160 push_symbol(ERF);
7161 push(p1);
7162 negate();
7163 list(2);
7164 negate();
7165 return;
7166 }
7167 push_symbol(ERF);
7168 push(p1);
7169 list(2);
7170 };
7171
7172 Eval_erfc = function() {
7173 push(cadr(p1));
7174 Eval();
7175 return yerfc();
7176 };
7177
7178 yerfc = function() {
7179 save();
7180 yyerfc();
7181 return restore();
7182 };
7183
7184 yyerfc = function() {
7185 var d;
7186 d = 0.0;
7187 p1 = pop();
7188 if (isdouble(p1)) {
7189 d = erfc(p1.d);
7190 push_double(d);
7191 return;
7192 }
7193 push_symbol(ERFC);
7194 push(p1);
7195 list(2);
7196 };
7197
7198 erfc = function(x) {
7199 var ans, t, z;
7200 t = 0.0;
7201 z = 0.0;
7202 ans = 0.0;
7203 z = Math.abs(x);
7204 t = 1.0 / (1.0 + 0.5 * z);
7205 ans = t * Math.exp(-z * z - 1.26551223 + t * (1.00002368 + t * (0.37409196 + t * (0.09678418 + t * (-0.18628806 + t * (0.27886807 + t * (-1.13520398 + t * (1.48851587 + t * (-0.82215223 + t * 0.17087277)))))))));
7206 if (x >= 0.0) {
7207 return ans;
7208 } else {
7209 return 2.0 - ans;
7210 }
7211 };
7212
7213
7214 /*
7215 * commented-out test
7216 "float(erfc(1))",
7217 "0.157299",
7218 */
7219
7220 Eval = function() {
7221 check_esc_flag();
7222 save();
7223 p1 = pop();
7224 if (p1 == null) {
7225 debugger;
7226 }
7227 switch (p1.k) {
7228 case CONS:
7229 Eval_cons();
7230 break;
7231 case NUM:
7232 push(p1);
7233 break;
7234 case DOUBLE:
7235 push(p1);
7236 break;
7237 case STR:
7238 push(p1);
7239 break;
7240 case TENSOR:
7241 Eval_tensor();
7242 break;
7243 case SYM:
7244 Eval_sym();
7245 break;
7246 default:
7247 stop("atom?");
7248 }
7249 return restore();
7250 };
7251
7252 Eval_sym = function() {
7253 if (iskeyword(p1)) {
7254 push(p1);
7255 push(symbol(LAST));
7256 list(2);
7257 Eval();
7258 return;
7259 }
7260 p2 = get_binding(p1);
7261 push(p2);
7262 if (p1 !== p2) {
7263 return Eval();
7264 }
7265 };
7266
7267 Eval_cons = function() {
7268 if (!issymbol(car(p1))) {
7269 stop("cons?");
7270 }
7271 switch (symnum(car(p1))) {
7272 case ABS:
7273 return Eval_abs();
7274 case ADD:
7275 return Eval_add();
7276 case ADJ:
7277 return Eval_adj();
7278 case AND:
7279 return Eval_and();
7280 case ARCCOS:
7281 return Eval_arccos();
7282 case ARCCOSH:
7283 return Eval_arccosh();
7284 case ARCSIN:
7285 return Eval_arcsin();
7286 case ARCSINH:
7287 return Eval_arcsinh();
7288 case ARCTAN:
7289 return Eval_arctan();
7290 case ARCTANH:
7291 return Eval_arctanh();
7292 case ARG:
7293 return Eval_arg();
7294 case ATOMIZE:
7295 return Eval_atomize();
7296 case BESSELJ:
7297 return Eval_besselj();
7298 case BESSELY:
7299 return Eval_bessely();
7300 case BINDING:
7301 return Eval_binding();
7302 case BINOMIAL:
7303 return Eval_binomial();
7304 case CEILING:
7305 return Eval_ceiling();
7306 case CHECK:
7307 return Eval_check();
7308 case CHOOSE:
7309 return Eval_choose();
7310 case CIRCEXP:
7311 return Eval_circexp();
7312 case CLEAR:
7313 return Eval_clear();
7314 case CLOCK:
7315 return Eval_clock();
7316 case COEFF:
7317 return Eval_coeff();
7318 case COFACTOR:
7319 return Eval_cofactor();
7320 case CONDENSE:
7321 return Eval_condense();
7322 case CONJ:
7323 return Eval_conj();
7324 case CONTRACT:
7325 return Eval_contract();
7326 case COS:
7327 return Eval_cos();
7328 case COSH:
7329 return Eval_cosh();
7330 case DECOMP:
7331 return Eval_decomp();
7332 case DEGREE:
7333 return Eval_degree();
7334 case DEFINT:
7335 return Eval_defint();
7336 case DENOMINATOR:
7337 return Eval_denominator();
7338 case DERIVATIVE:
7339 return Eval_derivative();
7340 case DET:
7341 return Eval_det();
7342 case DIM:
7343 return Eval_dim();
7344 case DIRAC:
7345 return Eval_dirac();
7346 case DISPLAY:
7347 return Eval_display();
7348 case DIVISORS:
7349 return Eval_divisors();
7350 case DO:
7351 return Eval_do();
7352 case DOT:
7353 return Eval_inner();
7354 case DRAW:
7355 return Eval_draw();
7356 case DSOLVE:
7357 return Eval_dsolve();
7358 case EIGEN:
7359 return Eval_eigen();
7360 case EIGENVAL:
7361 return Eval_eigenval();
7362 case EIGENVEC:
7363 return Eval_eigenvec();
7364 case ERF:
7365 return Eval_erf();
7366 case ERFC:
7367 return Eval_erfc();
7368 case EVAL:
7369 return Eval_Eval();
7370 case EXP:
7371 return Eval_exp();
7372 case EXPAND:
7373 return Eval_expand();
7374 case EXPCOS:
7375 return Eval_expcos();
7376 case EXPSIN:
7377 return Eval_expsin();
7378 case FACTOR:
7379 return Eval_factor();
7380 case FACTORIAL:
7381 return Eval_factorial();
7382 case FACTORPOLY:
7383 return Eval_factorpoly();
7384 case FILTER:
7385 return Eval_filter();
7386 case FLOATF:
7387 return Eval_float();
7388 case FLOOR:
7389 return Eval_floor();
7390 case FOR:
7391 return Eval_for();
7392 case GAMMA:
7393 return Eval_gamma();
7394 case GCD:
7395 return Eval_gcd();
7396 case HERMITE:
7397 return Eval_hermite();
7398 case HILBERT:
7399 return Eval_hilbert();
7400 case IMAG:
7401 return Eval_imag();
7402 case INDEX:
7403 return Eval_index();
7404 case INNER:
7405 return Eval_inner();
7406 case INTEGRAL:
7407 return Eval_integral();
7408 case INV:
7409 return Eval_inv();
7410 case INVG:
7411 return Eval_invg();
7412 case ISINTEGER:
7413 return Eval_isinteger();
7414 case ISPRIME:
7415 return Eval_isprime();
7416 case LAGUERRE:
7417 return Eval_laguerre();
7418 case LCM:
7419 return Eval_lcm();
7420 case LEADING:
7421 return Eval_leading();
7422 case LEGENDRE:
7423 return Eval_legendre();
7424 case LOG:
7425 return Eval_log();
7426 case MAG:
7427 return Eval_mag();
7428 case MOD:
7429 return Eval_mod();
7430 case MULTIPLY:
7431 return Eval_multiply();
7432 case NOT:
7433 return Eval_not();
7434 case NROOTS:
7435 return Eval_nroots();
7436 case NUMBER:
7437 return Eval_number();
7438 case NUMERATOR:
7439 return Eval_numerator();
7440 case OPERATOR:
7441 return Eval_operator();
7442 case OR:
7443 return Eval_or();
7444 case OUTER:
7445 return Eval_outer();
7446 case POLAR:
7447 return Eval_polar();
7448 case POWER:
7449 return Eval_power();
7450 case PRIME:
7451 return Eval_prime();
7452 case PRINT:
7453 return Eval_display();
7454 case PRODUCT:
7455 return Eval_product();
7456 case QUOTE:
7457 return Eval_quote();
7458 case QUOTIENT:
7459 return Eval_quotient();
7460 case RANK:
7461 return Eval_rank();
7462 case RATIONALIZE:
7463 return Eval_rationalize();
7464 case REAL:
7465 return Eval_real();
7466 case YYRECT:
7467 return Eval_rect();
7468 case ROOTS:
7469 return Eval_roots();
7470 case SETQ:
7471 return Eval_setq();
7472 case SGN:
7473 return Eval_sgn();
7474 case SIMPLIFY:
7475 return Eval_simplify();
7476 case SIN:
7477 return Eval_sin();
7478 case SINH:
7479 return Eval_sinh();
7480 case SHAPE:
7481 return Eval_shape();
7482 case SQRT:
7483 return Eval_sqrt();
7484 case STOP:
7485 return Eval_stop();
7486 case SUBST:
7487 return Eval_subst();
7488 case SUM:
7489 return Eval_sum();
7490 case TAN:
7491 return Eval_tan();
7492 case TANH:
7493 return Eval_tanh();
7494 case TAYLOR:
7495 return Eval_taylor();
7496 case TEST:
7497 return Eval_test();
7498 case TESTEQ:
7499 return Eval_testeq();
7500 case TESTGE:
7501 return Eval_testge();
7502 case TESTGT:
7503 return Eval_testgt();
7504 case TESTLE:
7505 return Eval_testle();
7506 case TESTLT:
7507 return Eval_testlt();
7508 case TRANSPOSE:
7509 return Eval_transpose();
7510 case UNIT:
7511 return Eval_unit();
7512 case ZERO:
7513 return Eval_zero();
7514 default:
7515 return Eval_user_function();
7516 }
7517 };
7518
7519 Eval_binding = function() {
7520 return push(get_binding(cadr(p1)));
7521 };
7522
7523 Eval_check = function() {
7524 push(cadr(p1));
7525 Eval_predicate();
7526 p1 = pop();
7527 if (iszero(p1)) {
7528 stop("check(arg): arg is zero");
7529 }
7530 return push(symbol(NIL));
7531 };
7532
7533 Eval_det = function() {
7534 push(cadr(p1));
7535 Eval();
7536 return det();
7537 };
7538
7539 Eval_dim = function() {
7540 var n;
7541 push(cadr(p1));
7542 Eval();
7543 p2 = pop();
7544 if (iscons(cddr(p1))) {
7545 push(caddr(p1));
7546 Eval();
7547 n = pop_integer();
7548 } else {
7549 n = 1;
7550 }
7551 if (!istensor(p2)) {
7552 return push_integer(1);
7553 } else if (n < 1 || n > p2.tensor.ndim) {
7554 return push(p1);
7555 } else {
7556 return push_integer(p2.tensor.dim[n - 1]);
7557 }
7558 };
7559
7560 Eval_divisors = function() {
7561 push(cadr(p1));
7562 Eval();
7563 return divisors();
7564 };
7565
7566 Eval_do = function() {
7567 var results;
7568 push(car(p1));
7569 p1 = cdr(p1);
7570 results = [];
7571 while (iscons(p1)) {
7572 pop();
7573 push(car(p1));
7574 Eval();
7575 results.push(p1 = cdr(p1));
7576 }
7577 return results;
7578 };
7579
7580 Eval_dsolve = function() {
7581 push(cadr(p1));
7582 Eval();
7583 push(caddr(p1));
7584 Eval();
7585 push(cadddr(p1));
7586 Eval();
7587 return dsolve();
7588 };
7589
7590 Eval_Eval = function() {
7591 push(cadr(p1));
7592 Eval();
7593 p1 = cddr(p1);
7594 while (iscons(p1)) {
7595 push(car(p1));
7596 Eval();
7597 push(cadr(p1));
7598 Eval();
7599 subst();
7600 p1 = cddr(p1);
7601 }
7602 return Eval();
7603 };
7604
7605 Eval_exp = function() {
7606 push(cadr(p1));
7607 Eval();
7608 return exponential();
7609 };
7610
7611 Eval_factorial = function() {
7612 push(cadr(p1));
7613 Eval();
7614 return factorial();
7615 };
7616
7617 Eval_factorpoly = function() {
7618 var results;
7619 p1 = cdr(p1);
7620 push(car(p1));
7621 Eval();
7622 p1 = cdr(p1);
7623 push(car(p1));
7624 Eval();
7625 factorpoly();
7626 p1 = cdr(p1);
7627 results = [];
7628 while (iscons(p1)) {
7629 push(car(p1));
7630 Eval();
7631 factorpoly();
7632 results.push(p1 = cdr(p1));
7633 }
7634 return results;
7635 };
7636
7637 Eval_hermite = function() {
7638 push(cadr(p1));
7639 Eval();
7640 push(caddr(p1));
7641 Eval();
7642 return hermite();
7643 };
7644
7645 Eval_hilbert = function() {
7646 push(cadr(p1));
7647 Eval();
7648 return hilbert();
7649 };
7650
7651 Eval_index = function() {
7652 var h;
7653 h = tos;
7654 p1 = cdr(p1);
7655 while (iscons(p1)) {
7656 push(car(p1));
7657 Eval();
7658 p1 = cdr(p1);
7659 }
7660 return index_function(tos - h);
7661 };
7662
7663 Eval_inv = function() {
7664 push(cadr(p1));
7665 Eval();
7666 return inv();
7667 };
7668
7669 Eval_invg = function() {
7670 push(cadr(p1));
7671 Eval();
7672 return invg();
7673 };
7674
7675 Eval_isinteger = function() {
7676 var n;
7677 push(cadr(p1));
7678 Eval();
7679 p1 = pop();
7680 if (isrational(p1)) {
7681 if (isinteger(p1)) {
7682 push(one);
7683 } else {
7684 push(zero);
7685 }
7686 return;
7687 }
7688 if (isdouble(p1)) {
7689 n = Math.floor(p1.d);
7690 if (n === p1.d) {
7691 push(one);
7692 } else {
7693 push(zero);
7694 }
7695 return;
7696 }
7697 push_symbol(ISINTEGER);
7698 push(p1);
7699 return list(2);
7700 };
7701
7702 Eval_multiply = function() {
7703 var results;
7704 push(cadr(p1));
7705 Eval();
7706 p1 = cddr(p1);
7707 results = [];
7708 while (iscons(p1)) {
7709 push(car(p1));
7710 Eval();
7711 multiply();
7712 results.push(p1 = cdr(p1));
7713 }
7714 return results;
7715 };
7716
7717 Eval_number = function() {
7718 push(cadr(p1));
7719 Eval();
7720 p1 = pop();
7721 if (p1.k === NUM || p1.k === DOUBLE) {
7722 return push_integer(1);
7723 } else {
7724 return push_integer(0);
7725 }
7726 };
7727
7728 Eval_operator = function() {
7729 var h;
7730 h = tos;
7731 push_symbol(OPERATOR);
7732 p1 = cdr(p1);
7733 while (iscons(p1)) {
7734 push(car(p1));
7735 Eval();
7736 p1 = cdr(p1);
7737 }
7738 return list(tos - h);
7739 };
7740
7741 Eval_print = function() {
7742 p1 = cdr(p1);
7743 while (iscons(p1)) {
7744 push(car(p1));
7745 Eval();
7746 if (equaln(get_binding(symbol(TTY)), 1)) {
7747 printline(pop());
7748 } else {
7749 display(pop());
7750 }
7751 p1 = cdr(p1);
7752 }
7753 return push(symbol(NIL));
7754 };
7755
7756 Eval_quote = function() {
7757 return push(cadr(p1));
7758 };
7759
7760 Eval_rank = function() {
7761 push(cadr(p1));
7762 Eval();
7763 p1 = pop();
7764 if (istensor(p1)) {
7765 return push_integer(p1.tensor.ndim);
7766 } else {
7767 return push(zero);
7768 }
7769 };
7770
7771 setq_indexed = function() {
7772 var h;
7773 p4 = cadadr(p1);
7774 if (!issymbol(p4)) {
7775 stop("indexed assignment: error in symbol");
7776 }
7777 h = tos;
7778 push(caddr(p1));
7779 Eval();
7780 p2 = cdadr(p1);
7781 while (iscons(p2)) {
7782 push(car(p2));
7783 Eval();
7784 p2 = cdr(p2);
7785 }
7786 set_component(tos - h);
7787 p3 = pop();
7788 set_binding(p4, p3);
7789 return push(symbol(NIL));
7790 };
7791
7792 Eval_setq = function() {
7793 if (caadr(p1) === symbol(INDEX)) {
7794 setq_indexed();
7795 return;
7796 }
7797 if (iscons(cadr(p1))) {
7798 define_user_function();
7799 return;
7800 }
7801 if (!issymbol(cadr(p1))) {
7802 stop("symbol assignment: error in symbol");
7803 }
7804 push(caddr(p1));
7805 Eval();
7806 p2 = pop();
7807 set_binding(cadr(p1), p2);
7808 return push(symbol(NIL));
7809 };
7810
7811 Eval_sqrt = function() {
7812 push(cadr(p1));
7813 Eval();
7814 push_rational(1, 2);
7815 return power();
7816 };
7817
7818 Eval_stop = function() {
7819 return stop("user stop");
7820 };
7821
7822 Eval_subst = function() {
7823 push(cadddr(p1));
7824 Eval();
7825 push(caddr(p1));
7826 Eval();
7827 push(cadr(p1));
7828 Eval();
7829 subst();
7830 return Eval();
7831 };
7832
7833 Eval_unit = function() {
7834 var i, n, o, ref;
7835 i = 0;
7836 n = 0;
7837 push(cadr(p1));
7838 Eval();
7839 n = pop_integer();
7840 if (n < 2) {
7841 push(p1);
7842 return;
7843 }
7844 p1 = alloc_tensor(n * n);
7845 p1.tensor.ndim = 2;
7846 p1.tensor.dim[0] = n;
7847 p1.tensor.dim[1] = n;
7848 for (i = o = 0, ref = n; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
7849 p1.tensor.elem[n * i + i] = one;
7850 }
7851 if (p1.tensor.nelem !== p1.tensor.elem.length) {
7852 console.log("something wrong in tensor dimensions");
7853 debugger;
7854 }
7855 return push(p1);
7856 };
7857
7858 Eval_noexpand = function() {
7859 var x;
7860 x = expanding;
7861 expanding = 0;
7862 Eval();
7863 return expanding = x;
7864 };
7865
7866 Eval_predicate = function() {
7867 save();
7868 p1 = pop();
7869 if (car(p1) === symbol(SETQ)) {
7870 Eval_testeq();
7871 } else {
7872 push(p1);
7873 Eval();
7874 }
7875 return restore();
7876 };
7877
7878 Eval_expand = function() {
7879 push(cadr(p1));
7880 Eval();
7881 push(caddr(p1));
7882 Eval();
7883 p2 = pop();
7884 if (p2 === symbol(NIL)) {
7885 guess();
7886 } else {
7887 push(p2);
7888 }
7889 return expand();
7890 };
7891
7892 expand = function() {
7893 save();
7894 p9 = pop();
7895 p5 = pop();
7896 if (istensor(p5)) {
7897 expand_tensor();
7898 restore();
7899 return;
7900 }
7901 if (car(p5) === symbol(ADD)) {
7902 push_integer(0);
7903 p1 = cdr(p5);
7904 while (iscons(p1)) {
7905 push(car(p1));
7906 push(p9);
7907 expand();
7908 add();
7909 p1 = cdr(p1);
7910 }
7911 restore();
7912 return;
7913 }
7914 push(p5);
7915 numerator();
7916 p3 = pop();
7917 push(p5);
7918 denominator();
7919 p2 = pop();
7920 remove_negative_exponents();
7921 push(p3);
7922 push(p2);
7923 push(p9);
7924 if (isone(p3) || isone(p2)) {
7925 if (!ispoly(p2, p9) || isone(p2)) {
7926 pop();
7927 pop();
7928 pop();
7929 push(p5);
7930 restore();
7931 return;
7932 }
7933 }
7934 divpoly();
7935 p7 = pop();
7936 push(p3);
7937 push(p2);
7938 push(p7);
7939 multiply();
7940 subtract();
7941 p3 = pop();
7942 if (iszero(p3)) {
7943 push(p7);
7944 restore();
7945 return;
7946 }
7947 push(p2);
7948 push(p9);
7949 factorpoly();
7950 p2 = pop();
7951 expand_get_C();
7952 expand_get_B();
7953 expand_get_A();
7954 if (istensor(p4)) {
7955 push(p4);
7956 inv();
7957 push(p3);
7958 inner();
7959 push(p2);
7960 inner();
7961 } else {
7962 push(p3);
7963 push(p4);
7964 divide();
7965 push(p2);
7966 multiply();
7967 }
7968 push(p7);
7969 add();
7970 return restore();
7971 };
7972
7973 expand_tensor = function() {
7974 var i, o, ref;
7975 i = 0;
7976 push(p5);
7977 copy_tensor();
7978 p5 = pop();
7979 for (i = o = 0, ref = p5.tensor.nelem; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
7980 push(p5.tensor.elem[i]);
7981 push(p9);
7982 expand();
7983 p5.tensor.elem[i] = pop();
7984 }
7985 return push(p5);
7986 };
7987
7988 remove_negative_exponents = function() {
7989 var h, i, j, k, n, o, ref;
7990 h = 0;
7991 i = 0;
7992 j = 0;
7993 k = 0;
7994 n = 0;
7995 h = tos;
7996 factors(p2);
7997 factors(p3);
7998 n = tos - h;
7999 j = 0;
8000 for (i = o = 0, ref = n; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
8001 p1 = stack[h + i];
8002 if (car(p1) !== symbol(POWER)) {
8003 continue;
8004 }
8005 if (cadr(p1) !== p9) {
8006 continue;
8007 }
8008 push(caddr(p1));
8009 k = pop_integer();
8010 if (k === 0x80000000) {
8011 continue;
8012 }
8013 if (k < j) {
8014 j = k;
8015 }
8016 }
8017 tos = h;
8018 if (j === 0) {
8019 return;
8020 }
8021 push(p2);
8022 push(p9);
8023 push_integer(-j);
8024 power();
8025 multiply();
8026 p2 = pop();
8027 push(p3);
8028 push(p9);
8029 push_integer(-j);
8030 power();
8031 multiply();
8032 return p3 = pop();
8033 };
8034
8035 expand_get_C = function() {
8036 var a, ac, h, i, j, n, o, ref, ref1;
8037 h = 0;
8038 i = 0;
8039 j = 0;
8040 n = 0;
8041 h = tos;
8042 if (car(p2) === symbol(MULTIPLY)) {
8043 p1 = cdr(p2);
8044 while (iscons(p1)) {
8045 p5 = car(p1);
8046 expand_get_CF();
8047 p1 = cdr(p1);
8048 }
8049 } else {
8050 p5 = p2;
8051 expand_get_CF();
8052 }
8053 n = tos - h;
8054 if (n === 1) {
8055 p4 = pop();
8056 return;
8057 }
8058 p4 = alloc_tensor(n * n);
8059 p4.tensor.ndim = 2;
8060 p4.tensor.dim[0] = n;
8061 p4.tensor.dim[1] = n;
8062 a = h;
8063 for (i = o = 0, ref = n; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
8064 for (j = ac = 0, ref1 = n; 0 <= ref1 ? ac < ref1 : ac > ref1; j = 0 <= ref1 ? ++ac : --ac) {
8065 push(stack[a + j]);
8066 push(p9);
8067 push_integer(i);
8068 power();
8069 divide();
8070 push(p9);
8071 filter();
8072 p4.tensor.elem[n * i + j] = pop();
8073 }
8074 }
8075 return tos -= n;
8076 };
8077
8078 expand_get_CF = function() {
8079 var d, i, j, n, o, ref, results;
8080 d = 0;
8081 i = 0;
8082 j = 0;
8083 n = 0;
8084 if (!Find(p5, p9)) {
8085 return;
8086 }
8087 trivial_divide();
8088 if (car(p5) === symbol(POWER)) {
8089 push(caddr(p5));
8090 n = pop_integer();
8091 p6 = cadr(p5);
8092 } else {
8093 n = 1;
8094 p6 = p5;
8095 }
8096 push(p6);
8097 push(p9);
8098 degree();
8099 d = pop_integer();
8100 results = [];
8101 for (i = o = 0, ref = n; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
8102 results.push((function() {
8103 var ac, ref1, results1;
8104 results1 = [];
8105 for (j = ac = 0, ref1 = d; 0 <= ref1 ? ac < ref1 : ac > ref1; j = 0 <= ref1 ? ++ac : --ac) {
8106 push(p8);
8107 push(p6);
8108 push_integer(i);
8109 power();
8110 multiply();
8111 push(p9);
8112 push_integer(j);
8113 power();
8114 results1.push(multiply());
8115 }
8116 return results1;
8117 })());
8118 }
8119 return results;
8120 };
8121
8122 trivial_divide = function() {
8123 var h;
8124 h = 0;
8125 if (car(p2) === symbol(MULTIPLY)) {
8126 h = tos;
8127 p0 = cdr(p2);
8128 while (iscons(p0)) {
8129 if (!equal(car(p0), p5)) {
8130 push(car(p0));
8131 Eval();
8132 }
8133 p0 = cdr(p0);
8134 }
8135 multiply_all(tos - h);
8136 } else {
8137 push_integer(1);
8138 }
8139 return p8 = pop();
8140 };
8141
8142 expand_get_B = function() {
8143 var i, n, o, ref;
8144 i = 0;
8145 n = 0;
8146 if (!istensor(p4)) {
8147 return;
8148 }
8149 n = p4.tensor.dim[0];
8150 p8 = alloc_tensor(n);
8151 p8.tensor.ndim = 1;
8152 p8.tensor.dim[0] = n;
8153 for (i = o = 0, ref = n; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
8154 push(p3);
8155 push(p9);
8156 push_integer(i);
8157 power();
8158 divide();
8159 push(p9);
8160 filter();
8161 p8.tensor.elem[i] = pop();
8162 }
8163 return p3 = p8;
8164 };
8165
8166 expand_get_A = function() {
8167 var h, i, n, o, ref;
8168 h = 0;
8169 i = 0;
8170 n = 0;
8171 if (!istensor(p4)) {
8172 push(p2);
8173 reciprocate();
8174 p2 = pop();
8175 return;
8176 }
8177 h = tos;
8178 if (car(p2) === symbol(MULTIPLY)) {
8179 p8 = cdr(p2);
8180 while (iscons(p8)) {
8181 p5 = car(p8);
8182 expand_get_AF();
8183 p8 = cdr(p8);
8184 }
8185 } else {
8186 p5 = p2;
8187 expand_get_AF();
8188 }
8189 n = tos - h;
8190 p8 = alloc_tensor(n);
8191 p8.tensor.ndim = 1;
8192 p8.tensor.dim[0] = n;
8193 for (i = o = 0, ref = n; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
8194 p8.tensor.elem[i] = stack[h + i];
8195 }
8196 tos = h;
8197 return p2 = p8;
8198 };
8199
8200 expand_get_AF = function() {
8201 var d, i, j, n, o, ref, results;
8202 d = 0;
8203 i = 0;
8204 j = 0;
8205 n = 1;
8206 if (!Find(p5, p9)) {
8207 return;
8208 }
8209 if (car(p5) === symbol(POWER)) {
8210 push(caddr(p5));
8211 n = pop_integer();
8212 p5 = cadr(p5);
8213 }
8214 push(p5);
8215 push(p9);
8216 degree();
8217 d = pop_integer();
8218 results = [];
8219 for (i = o = ref = n; ref <= 0 ? o < 0 : o > 0; i = ref <= 0 ? ++o : --o) {
8220 results.push((function() {
8221 var ac, ref1, results1;
8222 results1 = [];
8223 for (j = ac = 0, ref1 = d; 0 <= ref1 ? ac < ref1 : ac > ref1; j = 0 <= ref1 ? ++ac : --ac) {
8224 push(p5);
8225 push_integer(i);
8226 power();
8227 reciprocate();
8228 push(p9);
8229 push_integer(j);
8230 power();
8231 results1.push(multiply());
8232 }
8233 return results1;
8234 })());
8235 }
8236 return results;
8237 };
8238
8239 Eval_expcos = function() {
8240 push(cadr(p1));
8241 Eval();
8242 return expcos();
8243 };
8244
8245 expcos = function() {
8246 save();
8247 p1 = pop();
8248 push(imaginaryunit);
8249 push(p1);
8250 multiply();
8251 exponential();
8252 push_rational(1, 2);
8253 multiply();
8254 push(imaginaryunit);
8255 negate();
8256 push(p1);
8257 multiply();
8258 exponential();
8259 push_rational(1, 2);
8260 multiply();
8261 add();
8262 return restore();
8263 };
8264
8265 Eval_expsin = function() {
8266 push(cadr(p1));
8267 Eval();
8268 return expsin();
8269 };
8270
8271 expsin = function() {
8272 save();
8273 p1 = pop();
8274 push(imaginaryunit);
8275 push(p1);
8276 multiply();
8277 exponential();
8278 push(imaginaryunit);
8279 divide();
8280 push_rational(1, 2);
8281 multiply();
8282 push(imaginaryunit);
8283 negate();
8284 push(p1);
8285 multiply();
8286 exponential();
8287 push(imaginaryunit);
8288 divide();
8289 push_rational(1, 2);
8290 multiply();
8291 subtract();
8292 return restore();
8293 };
8294
8295 Eval_factor = function() {
8296 var results;
8297 push(cadr(p1));
8298 Eval();
8299 push(caddr(p1));
8300 Eval();
8301 p2 = pop();
8302 if (p2 === symbol(NIL)) {
8303 guess();
8304 } else {
8305 push(p2);
8306 }
8307 factor();
8308 p1 = cdddr(p1);
8309 results = [];
8310 while (iscons(p1)) {
8311 push(car(p1));
8312 Eval();
8313 factor_again();
8314 results.push(p1 = cdr(p1));
8315 }
8316 return results;
8317 };
8318
8319 factor_again = function() {
8320 var h, n;
8321 save();
8322 p2 = pop();
8323 p1 = pop();
8324 h = tos;
8325 if (car(p1) === symbol(MULTIPLY)) {
8326 p1 = cdr(p1);
8327 while (iscons(p1)) {
8328 push(car(p1));
8329 push(p2);
8330 factor_term();
8331 p1 = cdr(p1);
8332 }
8333 } else {
8334 push(p1);
8335 push(p2);
8336 factor_term();
8337 }
8338 n = tos - h;
8339 if (n > 1) {
8340 multiply_all_noexpand(n);
8341 }
8342 return restore();
8343 };
8344
8345 factor_term = function() {
8346 save();
8347 factorpoly();
8348 p1 = pop();
8349 if (car(p1) === symbol(MULTIPLY)) {
8350 p1 = cdr(p1);
8351 while (iscons(p1)) {
8352 push(car(p1));
8353 p1 = cdr(p1);
8354 }
8355 } else {
8356 push(p1);
8357 }
8358 return restore();
8359 };
8360
8361 factor = function() {
8362 save();
8363 p2 = pop();
8364 p1 = pop();
8365 if (isinteger(p1)) {
8366 push(p1);
8367 factor_number();
8368 } else {
8369 push(p1);
8370 push(p2);
8371 factorpoly();
8372 }
8373 return restore();
8374 };
8375
8376 factor_small_number = function() {
8377 var d, expo, i, n, o, ref;
8378 i = 0;
8379 save();
8380 n = pop_integer();
8381 if (n === 0x80000000) {
8382 stop("number too big to factor");
8383 }
8384 if (n < 0) {
8385 n = -n;
8386 }
8387 for (i = o = 0, ref = MAXPRIMETAB; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
8388 d = primetab[i];
8389 if (d > n / d) {
8390 break;
8391 }
8392 expo = 0;
8393 while (n % d === 0) {
8394 n /= d;
8395 expo++;
8396 }
8397 if (expo) {
8398 push_integer(d);
8399 push_integer(expo);
8400 }
8401 }
8402 if (n > 1) {
8403 push_integer(n);
8404 push_integer(1);
8405 }
8406 return restore();
8407 };
8408
8409 factorial = function() {
8410 var n;
8411 n = 0;
8412 save();
8413 p1 = pop();
8414 push(p1);
8415 n = pop_integer();
8416 if (n < 0 || n === 0x80000000) {
8417 push_symbol(FACTORIAL);
8418 push(p1);
8419 list(2);
8420 restore();
8421 return;
8422 }
8423 bignum_factorial(n);
8424 return restore();
8425 };
8426
8427 simplifyfactorials = function() {
8428 var x;
8429 x = 0;
8430 save();
8431 x = expanding;
8432 expanding = 0;
8433 p1 = pop();
8434 if (car(p1) === symbol(ADD)) {
8435 push(zero);
8436 p1 = cdr(p1);
8437 while (iscons(p1)) {
8438 push(car(p1));
8439 simplifyfactorials();
8440 add();
8441 p1 = cdr(p1);
8442 }
8443 expanding = x;
8444 restore();
8445 return;
8446 }
8447 if (car(p1) === symbol(MULTIPLY)) {
8448 sfac_product();
8449 expanding = x;
8450 restore();
8451 return;
8452 }
8453 push(p1);
8454 expanding = x;
8455 return restore();
8456 };
8457
8458 sfac_product = function() {
8459 var ac, ad, i, j, n, o, ref, ref1, ref2, ref3, s;
8460 i = 0;
8461 j = 0;
8462 n = 0;
8463 s = tos;
8464 p1 = cdr(p1);
8465 n = 0;
8466 while (iscons(p1)) {
8467 push(car(p1));
8468 p1 = cdr(p1);
8469 n++;
8470 }
8471 for (i = o = 0, ref = n - 1; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
8472 if (stack[s + i] === symbol(NIL)) {
8473 continue;
8474 }
8475 for (j = ac = ref1 = i + 1, ref2 = n; ref1 <= ref2 ? ac < ref2 : ac > ref2; j = ref1 <= ref2 ? ++ac : --ac) {
8476 if (stack[s + j] === symbol(NIL)) {
8477 continue;
8478 }
8479 sfac_product_f(s, i, j);
8480 }
8481 }
8482 push(one);
8483 for (i = ad = 0, ref3 = n; 0 <= ref3 ? ad < ref3 : ad > ref3; i = 0 <= ref3 ? ++ad : --ad) {
8484 if (stack[s + i] === symbol(NIL)) {
8485 continue;
8486 }
8487 push(stack[s + i]);
8488 multiply();
8489 }
8490 p1 = pop();
8491 tos -= n;
8492 return push(p1);
8493 };
8494
8495 sfac_product_f = function(s, a, b) {
8496 var i, n, o, ref;
8497 i = 0;
8498 n = 0;
8499 p1 = stack[s + a];
8500 p2 = stack[s + b];
8501 if (ispower(p1)) {
8502 p3 = caddr(p1);
8503 p1 = cadr(p1);
8504 } else {
8505 p3 = one;
8506 }
8507 if (ispower(p2)) {
8508 p4 = caddr(p2);
8509 p2 = cadr(p2);
8510 } else {
8511 p4 = one;
8512 }
8513 if (isfactorial(p1) && isfactorial(p2)) {
8514 push(p3);
8515 push(p4);
8516 add();
8517 yyexpand();
8518 n = pop_integer();
8519 if (n !== 0) {
8520 return;
8521 }
8522 push(cadr(p1));
8523 push(cadr(p2));
8524 subtract();
8525 yyexpand();
8526 n = pop_integer();
8527 if (n === 0 || n === 0x80000000) {
8528 return;
8529 }
8530 if (n < 0) {
8531 n = -n;
8532 p5 = p1;
8533 p1 = p2;
8534 p2 = p5;
8535 p5 = p3;
8536 p3 = p4;
8537 p4 = p5;
8538 }
8539 push(one);
8540 for (i = o = 1, ref = n; 1 <= ref ? o <= ref : o >= ref; i = 1 <= ref ? ++o : --o) {
8541 push(cadr(p2));
8542 push_integer(i);
8543 add();
8544 push(p3);
8545 power();
8546 multiply();
8547 }
8548 stack[s + a] = pop();
8549 return stack[s + b] = symbol(NIL);
8550 }
8551 };
8552
8553 polycoeff = 0;
8554
8555 factpoly_expo = 0;
8556
8557 factorpoly = function() {
8558 save();
8559 p2 = pop();
8560 p1 = pop();
8561 if (!Find(p1, p2)) {
8562 push(p1);
8563 restore();
8564 return;
8565 }
8566 if (!ispoly(p1, p2)) {
8567 push(p1);
8568 restore();
8569 return;
8570 }
8571 if (!issymbol(p2)) {
8572 push(p1);
8573 restore();
8574 return;
8575 }
8576 push(p1);
8577 push(p2);
8578 yyfactorpoly();
8579 return restore();
8580 };
8581
8582 yyfactorpoly = function() {
8583 var h, i, o, ref;
8584 h = 0;
8585 i = 0;
8586 save();
8587 p2 = pop();
8588 p1 = pop();
8589 h = tos;
8590 if (isfloating(p1)) {
8591 stop("floating point numbers in polynomial");
8592 }
8593 polycoeff = tos;
8594 push(p1);
8595 push(p2);
8596 factpoly_expo = coeff() - 1;
8597 rationalize_coefficients(h);
8598 while (factpoly_expo > 0) {
8599 if (iszero(stack[polycoeff + 0])) {
8600 push_integer(1);
8601 p4 = pop();
8602 push_integer(0);
8603 p5 = pop();
8604 } else if (get_factor() === 0) {
8605 if (verbosing) {
8606 printf("no factor found\n");
8607 }
8608 break;
8609 }
8610 push(p4);
8611 push(p2);
8612 multiply();
8613 push(p5);
8614 add();
8615 p8 = pop();
8616 if (verbosing) {
8617 printf("success\nFACTOR=");
8618 print(p8);
8619 printf("\n");
8620 }
8621
8622 /*
8623 if (isnegativeterm(p4))
8624 push(p8)
8625 negate()
8626 p8 = pop()
8627 push(p7)
8628 negate_noexpand()
8629 p7 = pop()
8630 */
8631 push(p7);
8632 push(p8);
8633 multiply_noexpand();
8634 p7 = pop();
8635 yydivpoly();
8636 while (factpoly_expo && iszero(stack[polycoeff + factpoly_expo])) {
8637 factpoly_expo--;
8638 }
8639 }
8640 push(zero);
8641 for (i = o = 0, ref = factpoly_expo; 0 <= ref ? o <= ref : o >= ref; i = 0 <= ref ? ++o : --o) {
8642 push(stack[polycoeff + i]);
8643 push(p2);
8644 push_integer(i);
8645 power();
8646 multiply();
8647 add();
8648 }
8649 p1 = pop();
8650 if (verbosing) {
8651 printf("POLY=");
8652 print(p1);
8653 printf("\n");
8654 }
8655 if (factpoly_expo > 0 && isnegativeterm(stack[polycoeff + factpoly_expo])) {
8656 push(p1);
8657 negate();
8658 p1 = pop();
8659 push(p7);
8660 negate_noexpand();
8661 p7 = pop();
8662 }
8663 push(p7);
8664 push(p1);
8665 multiply_noexpand();
8666 p7 = pop();
8667 if (verbosing) {
8668 printf("RESULT=");
8669 print(p7);
8670 printf("\n");
8671 }
8672 stack[h] = p7;
8673 tos = h + 1;
8674 return restore();
8675 };
8676
8677 rationalize_coefficients = function(h) {
8678 var ac, i, o, ref, ref1, ref2, ref3;
8679 i = 0;
8680 p7 = one;
8681 for (i = o = ref = h, ref1 = tos; ref <= ref1 ? o < ref1 : o > ref1; i = ref <= ref1 ? ++o : --o) {
8682 push(stack[i]);
8683 denominator();
8684 push(p7);
8685 lcm();
8686 p7 = pop();
8687 }
8688 for (i = ac = ref2 = h, ref3 = tos; ref2 <= ref3 ? ac < ref3 : ac > ref3; i = ref2 <= ref3 ? ++ac : --ac) {
8689 push(p7);
8690 push(stack[i]);
8691 multiply();
8692 stack[i] = pop();
8693 }
8694 push(p7);
8695 reciprocate();
8696 p7 = pop();
8697 if (DEBUG) {
8698 return console.log("rationalize_coefficients result");
8699 }
8700 };
8701
8702 get_factor = function() {
8703 var a0, ac, ad, ae, af, an, h, i, j, na0, nan, o, ref, ref1, ref2, ref3, ref4, rootsTries_i, rootsTries_j;
8704 i = 0;
8705 j = 0;
8706 h = 0;
8707 a0 = 0;
8708 an = 0;
8709 na0 = 0;
8710 nan = 0;
8711 if (verbosing) {
8712 push(zero);
8713 for (i = o = 0, ref = factpoly_expo; 0 <= ref ? o <= ref : o >= ref; i = 0 <= ref ? ++o : --o) {
8714 push(stack[polycoeff + i]);
8715 push(p2);
8716 push_integer(i);
8717 power();
8718 multiply();
8719 add();
8720 }
8721 p1 = pop();
8722 printf("POLY=");
8723 print(p1);
8724 printf("\n");
8725 }
8726 h = tos;
8727 an = tos;
8728 push(stack[polycoeff + factpoly_expo]);
8729 divisors_onstack();
8730 nan = tos - an;
8731 a0 = tos;
8732 push(stack[polycoeff + 0]);
8733 divisors_onstack();
8734 na0 = tos - a0;
8735 if (verbosing) {
8736 printf("divisors of base term");
8737 for (i = ac = 0, ref1 = na0; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
8738 printf(", ");
8739 print(stack[a0 + i]);
8740 }
8741 printf("\n");
8742 printf("divisors of leading term");
8743 for (i = ad = 0, ref2 = nan; 0 <= ref2 ? ad < ref2 : ad > ref2; i = 0 <= ref2 ? ++ad : --ad) {
8744 printf(", ");
8745 print(stack[an + i]);
8746 }
8747 printf("\n");
8748 }
8749 for (rootsTries_i = ae = 0, ref3 = nan; 0 <= ref3 ? ae < ref3 : ae > ref3; rootsTries_i = 0 <= ref3 ? ++ae : --ae) {
8750 for (rootsTries_j = af = 0, ref4 = na0; 0 <= ref4 ? af < ref4 : af > ref4; rootsTries_j = 0 <= ref4 ? ++af : --af) {
8751 p4 = stack[an + rootsTries_i];
8752 p5 = stack[a0 + rootsTries_j];
8753 push(p5);
8754 push(p4);
8755 divide();
8756 negate();
8757 p3 = pop();
8758 Evalpoly();
8759 if (verbosing) {
8760 printf("try A=");
8761 print(p4);
8762 printf(", B=");
8763 print(p5);
8764 printf(", root ");
8765 print(p2);
8766 printf("=-B/A=");
8767 print(p3);
8768 printf(", POLY(");
8769 print(p3);
8770 printf(")=");
8771 print(p6);
8772 printf("\n");
8773 }
8774 if (iszero(p6)) {
8775 tos = h;
8776 if (DEBUG) {
8777 console.log("get_factor returning 1");
8778 }
8779 return 1;
8780 }
8781 push(p5);
8782 negate();
8783 p5 = pop();
8784 push(p3);
8785 negate();
8786 p3 = pop();
8787 Evalpoly();
8788 if (verbosing) {
8789 printf("try A=");
8790 print(p4);
8791 printf(", B=");
8792 print(p5);
8793 printf(", root ");
8794 print(p2);
8795 printf("=-B/A=");
8796 print(p3);
8797 printf(", POLY(");
8798 print(p3);
8799 printf(")=");
8800 print(p6);
8801 printf("\n");
8802 }
8803 if (iszero(p6)) {
8804 tos = h;
8805 if (DEBUG) {
8806 console.log("get_factor returning 1");
8807 }
8808 return 1;
8809 }
8810 }
8811 }
8812 tos = h;
8813 if (DEBUG) {
8814 console.log("get_factor returning 0");
8815 }
8816 return 0;
8817 };
8818
8819 yydivpoly = function() {
8820 var i, o, ref;
8821 i = 0;
8822 p6 = zero;
8823 for (i = o = ref = factpoly_expo; ref <= 0 ? o < 0 : o > 0; i = ref <= 0 ? ++o : --o) {
8824 push(stack[polycoeff + i]);
8825 stack[polycoeff + i] = p6;
8826 push(p4);
8827 divide();
8828 p6 = pop();
8829 push(stack[polycoeff + i - 1]);
8830 push(p6);
8831 push(p5);
8832 multiply();
8833 subtract();
8834 stack[polycoeff + i - 1] = pop();
8835 }
8836 stack[polycoeff + 0] = p6;
8837 if (DEBUG) {
8838 return console.log("yydivpoly Q:");
8839 }
8840 };
8841
8842 Evalpoly = function() {
8843 var i, o, ref;
8844 i = 0;
8845 push(zero);
8846 for (i = o = ref = factpoly_expo; ref <= 0 ? o <= 0 : o >= 0; i = ref <= 0 ? ++o : --o) {
8847 push(p3);
8848 multiply();
8849 push(stack[polycoeff + i]);
8850 if (DEBUG) {
8851 console.log("Evalpoly top of stack:");
8852 print1(stack[tos - i]);
8853 }
8854 add();
8855 }
8856 return p6 = pop();
8857 };
8858
8859 factors = function(p) {
8860 var h;
8861 h = tos;
8862 if (car(p) === symbol(ADD)) {
8863 p = cdr(p);
8864 while (iscons(p)) {
8865 push_term_factors(car(p));
8866 p = cdr(p);
8867 }
8868 } else {
8869 push_term_factors(p);
8870 }
8871 return tos - h;
8872 };
8873
8874 push_term_factors = function(p) {
8875 var results;
8876 if (car(p) === symbol(MULTIPLY)) {
8877 p = cdr(p);
8878 results = [];
8879 while (iscons(p)) {
8880 push(car(p));
8881 results.push(p = cdr(p));
8882 }
8883 return results;
8884 } else {
8885 return push(p);
8886 }
8887 };
8888
8889
8890 /*
8891 Remove terms that involve a given symbol or expression. For example...
8892
8893 filter(x^2 + x + 1, x) => 1
8894
8895 filter(x^2 + x + 1, x^2) => x + 1
8896 */
8897
8898 Eval_filter = function() {
8899 var results;
8900 p1 = cdr(p1);
8901 push(car(p1));
8902 Eval();
8903 p1 = cdr(p1);
8904 results = [];
8905 while (iscons(p1)) {
8906 push(car(p1));
8907 Eval();
8908 filter();
8909 results.push(p1 = cdr(p1));
8910 }
8911 return results;
8912 };
8913
8914
8915 /*
8916 For example...
8917
8918 push(F)
8919 push(X)
8920 filter()
8921 F = pop()
8922 */
8923
8924 filter = function() {
8925 save();
8926 p2 = pop();
8927 p1 = pop();
8928 filter_main();
8929 return restore();
8930 };
8931
8932 filter_main = function() {
8933 if (car(p1) === symbol(ADD)) {
8934 return filter_sum();
8935 } else if (istensor(p1)) {
8936 return filter_tensor();
8937 } else if (Find(p1, p2)) {
8938 return push_integer(0);
8939 } else {
8940 return push(p1);
8941 }
8942 };
8943
8944 filter_sum = function() {
8945 var results;
8946 push_integer(0);
8947 p1 = cdr(p1);
8948 results = [];
8949 while (iscons(p1)) {
8950 push(car(p1));
8951 push(p2);
8952 filter();
8953 add();
8954 results.push(p1 = cdr(p1));
8955 }
8956 return results;
8957 };
8958
8959 filter_tensor = function() {
8960 var ac, i, n, o, ref, ref1;
8961 i = 0;
8962 n = 0;
8963 n = p1.tensor.nelem;
8964 p3 = alloc_tensor(n);
8965 p3.tensor.ndim = p1.tensor.ndim;
8966 for (i = o = 0, ref = p1.tensor.ndim; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
8967 p3.tensor.dim[i] = p1.tensor.dim[i];
8968 }
8969 for (i = ac = 0, ref1 = n; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
8970 push(p1.tensor.elem[i]);
8971 push(p2);
8972 filter();
8973 p3.tensor.elem[i] = pop();
8974 }
8975 return push(p3);
8976 };
8977
8978 Eval_float = function() {
8979 push(cadr(p1));
8980 Eval();
8981 yyfloat();
8982 return Eval();
8983 };
8984
8985 yyfloat = function() {
8986 var h, i, o, ref;
8987 i = 0;
8988 h = 0;
8989 save();
8990 p1 = pop();
8991 if (iscons(p1)) {
8992 h = tos;
8993 while (iscons(p1)) {
8994 push(car(p1));
8995 yyfloat();
8996 p1 = cdr(p1);
8997 }
8998 list(tos - h);
8999 } else if (p1.k === TENSOR) {
9000 push(p1);
9001 copy_tensor();
9002 p1 = pop();
9003 for (i = o = 0, ref = p1.tensor.nelem; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
9004 push(p1.tensor.elem[i]);
9005 yyfloat();
9006 p1.tensor.elem[i] = pop();
9007 }
9008 push(p1);
9009 } else if (p1.k === NUM) {
9010 push(p1);
9011 bignum_float();
9012 } else if (p1 === symbol(PI)) {
9013 push_double(Math.PI);
9014 } else if (p1 === symbol(E)) {
9015 push_double(Math.E);
9016 } else {
9017 push(p1);
9018 }
9019 return restore();
9020 };
9021
9022 Eval_floor = function() {
9023 push(cadr(p1));
9024 Eval();
9025 return yfloor();
9026 };
9027
9028 yfloor = function() {
9029 save();
9030 yyfloor();
9031 return restore();
9032 };
9033
9034 yyfloor = function() {
9035 var d;
9036 d = 0.0;
9037 p1 = pop();
9038 if (!isnum(p1)) {
9039 push_symbol(FLOOR);
9040 push(p1);
9041 list(2);
9042 return;
9043 }
9044 if (isdouble(p1)) {
9045 d = Math.floor(p1.d);
9046 push_double(d);
9047 return;
9048 }
9049 if (isinteger(p1)) {
9050 push(p1);
9051 return;
9052 }
9053 p3 = new U();
9054 p3.k = NUM;
9055 p3.q.a = mdiv(p1.q.a, p1.q.b);
9056 p3.q.b = mint(1);
9057 push(p3);
9058 if (isnegativenumber(p1)) {
9059 push_integer(-1);
9060 return add();
9061 }
9062 };
9063
9064 Eval_for = function() {
9065 var i, j, k, o, ref, ref1;
9066 i = 0;
9067 j = 0;
9068 k = 0;
9069 p6 = cadr(p1);
9070 if (!issymbol(p6)) {
9071 stop("for: 1st arg?");
9072 }
9073 push(caddr(p1));
9074 Eval();
9075 j = pop_integer();
9076 if (j === 0x80000000) {
9077 stop("for: 2nd arg?");
9078 }
9079 push(cadddr(p1));
9080 Eval();
9081 k = pop_integer();
9082 if (k === 0x80000000) {
9083 stop("for: 3rd arg?");
9084 }
9085 p1 = cddddr(p1);
9086 p4 = get_binding(p6);
9087 p3 = get_arglist(p6);
9088 for (i = o = ref = j, ref1 = k; ref <= ref1 ? o <= ref1 : o >= ref1; i = ref <= ref1 ? ++o : --o) {
9089 push_integer(i);
9090 p5 = pop();
9091 set_binding(p6, p5);
9092 p2 = p1;
9093 while (iscons(p2)) {
9094 push(car(p2));
9095 Eval();
9096 pop();
9097 p2 = cdr(p2);
9098 }
9099 }
9100 set_binding_and_arglist(p6, p4, p3);
9101 return push_symbol(NIL);
9102 };
9103
9104 Eval_gamma = function() {
9105 push(cadr(p1));
9106 Eval();
9107 return gamma();
9108 };
9109
9110 gamma = function() {
9111 save();
9112 gammaf();
9113 return restore();
9114 };
9115
9116 gammaf = function() {
9117 p1 = pop();
9118 if (isrational(p1) && MEQUAL(p1.q.a, 1) && MEQUAL(p1.q.b, 2)) {
9119 push_symbol(PI);
9120 push_rational(1, 2);
9121 power();
9122 return;
9123 }
9124 if (isrational(p1) && MEQUAL(p1.q.a, 3) && MEQUAL(p1.q.b, 2)) {
9125 push_symbol(PI);
9126 push_rational(1, 2);
9127 power();
9128 push_rational(1, 2);
9129 multiply();
9130 return;
9131 }
9132 if (isnegativeterm(p1)) {
9133 push_symbol(PI);
9134 push_integer(-1);
9135 multiply();
9136 push_symbol(PI);
9137 push(p1);
9138 multiply();
9139 sine();
9140 push(p1);
9141 multiply();
9142 push(p1);
9143 negate();
9144 gamma();
9145 multiply();
9146 divide();
9147 return;
9148 }
9149 if (car(p1) === symbol(ADD)) {
9150 gamma_of_sum();
9151 return;
9152 }
9153 push_symbol(GAMMA);
9154 push(p1);
9155 list(2);
9156 };
9157
9158 gamma_of_sum = function() {
9159 p3 = cdr(p1);
9160 if (isrational(car(p3)) && MEQUAL(car(p3).q.a, 1) && MEQUAL(car(p3).q.b, 1)) {
9161 push(cadr(p3));
9162 push(cadr(p3));
9163 gamma();
9164 return multiply();
9165 } else {
9166 if (isrational(car(p3)) && MEQUAL(car(p3).q.a, -1) && MEQUAL(car(p3).q.b, 1)) {
9167 push(cadr(p3));
9168 gamma();
9169 push(cadr(p3));
9170 push_integer(-1);
9171 add();
9172 return divide();
9173 } else {
9174 push_symbol(GAMMA);
9175 push(p1);
9176 list(2);
9177 }
9178 }
9179 };
9180
9181 Eval_gcd = function() {
9182 var results;
9183 p1 = cdr(p1);
9184 push(car(p1));
9185 Eval();
9186 p1 = cdr(p1);
9187 results = [];
9188 while (iscons(p1)) {
9189 push(car(p1));
9190 Eval();
9191 gcd();
9192 results.push(p1 = cdr(p1));
9193 }
9194 return results;
9195 };
9196
9197 gcd = function() {
9198 var x;
9199 x = expanding;
9200 save();
9201 gcd_main();
9202 restore();
9203 return expanding = x;
9204 };
9205
9206 gcd_main = function() {
9207 expanding = 1;
9208 p2 = pop();
9209 p1 = pop();
9210 if (equal(p1, p2)) {
9211 push(p1);
9212 return;
9213 }
9214 if (isrational(p1) && isrational(p2)) {
9215 push(p1);
9216 push(p2);
9217 gcd_numbers();
9218 return;
9219 }
9220 if (car(p1) === symbol(ADD) && car(p2) === symbol(ADD)) {
9221 gcd_expr_expr();
9222 return;
9223 }
9224 if (car(p1) === symbol(ADD)) {
9225 gcd_expr(p1);
9226 p1 = pop();
9227 }
9228 if (car(p2) === symbol(ADD)) {
9229 gcd_expr(p2);
9230 p2 = pop();
9231 }
9232 if (car(p1) === symbol(MULTIPLY) && car(p2) === symbol(MULTIPLY)) {
9233 gcd_term_term();
9234 return;
9235 }
9236 if (car(p1) === symbol(MULTIPLY)) {
9237 gcd_term_factor();
9238 return;
9239 }
9240 if (car(p2) === symbol(MULTIPLY)) {
9241 gcd_factor_term();
9242 return;
9243 }
9244 if (car(p1) === symbol(POWER)) {
9245 p3 = caddr(p1);
9246 p1 = cadr(p1);
9247 } else {
9248 p3 = one;
9249 }
9250 if (car(p2) === symbol(POWER)) {
9251 p4 = caddr(p2);
9252 p2 = cadr(p2);
9253 } else {
9254 p4 = one;
9255 }
9256 if (!equal(p1, p2)) {
9257 push(one);
9258 return;
9259 }
9260 if (isnum(p3) && isnum(p4)) {
9261 push(p1);
9262 if (lessp(p3, p4)) {
9263 push(p3);
9264 } else {
9265 push(p4);
9266 }
9267 power();
9268 return;
9269 }
9270 push(p3);
9271 push(p4);
9272 divide();
9273 p5 = pop();
9274 if (isnum(p5)) {
9275 push(p1);
9276 if (car(p3) === symbol(MULTIPLY) && isnum(cadr(p3))) {
9277 p5 = cadr(p3);
9278 } else {
9279 p5 = one;
9280 }
9281 if (car(p4) === symbol(MULTIPLY) && isnum(cadr(p4))) {
9282 p6 = cadr(p4);
9283 } else {
9284 p6 = one;
9285 }
9286 if (lessp(p5, p6)) {
9287 push(p3);
9288 } else {
9289 push(p4);
9290 }
9291 power();
9292 return;
9293 }
9294 push(p3);
9295 push(p4);
9296 subtract();
9297 p5 = pop();
9298 if (!isnum(p5)) {
9299 push(one);
9300 return;
9301 }
9302 push(p1);
9303 if (isnegativenumber(p5)) {
9304 push(p3);
9305 } else {
9306 push(p4);
9307 }
9308 return power();
9309 };
9310
9311 gcd_expr_expr = function() {
9312 if (length(p1) !== length(p2)) {
9313 push(one);
9314 return;
9315 }
9316 p3 = cdr(p1);
9317 push(car(p3));
9318 p3 = cdr(p3);
9319 while (iscons(p3)) {
9320 push(car(p3));
9321 gcd();
9322 p3 = cdr(p3);
9323 }
9324 p3 = pop();
9325 p4 = cdr(p2);
9326 push(car(p4));
9327 p4 = cdr(p4);
9328 while (iscons(p4)) {
9329 push(car(p4));
9330 gcd();
9331 p4 = cdr(p4);
9332 }
9333 p4 = pop();
9334 push(p1);
9335 push(p3);
9336 divide();
9337 p5 = pop();
9338 push(p2);
9339 push(p4);
9340 divide();
9341 p6 = pop();
9342 if (equal(p5, p6)) {
9343 push(p5);
9344 push(p3);
9345 push(p4);
9346 gcd();
9347 return multiply();
9348 } else {
9349 return push(one);
9350 }
9351 };
9352
9353 gcd_expr = function(p) {
9354 var results;
9355 p = cdr(p);
9356 push(car(p));
9357 p = cdr(p);
9358 results = [];
9359 while (iscons(p)) {
9360 push(car(p));
9361 gcd();
9362 results.push(p = cdr(p));
9363 }
9364 return results;
9365 };
9366
9367 gcd_term_term = function() {
9368 var results;
9369 push(one);
9370 p3 = cdr(p1);
9371 results = [];
9372 while (iscons(p3)) {
9373 p4 = cdr(p2);
9374 while (iscons(p4)) {
9375 push(car(p3));
9376 push(car(p4));
9377 gcd();
9378 multiply();
9379 p4 = cdr(p4);
9380 }
9381 results.push(p3 = cdr(p3));
9382 }
9383 return results;
9384 };
9385
9386 gcd_term_factor = function() {
9387 var results;
9388 push(one);
9389 p3 = cdr(p1);
9390 results = [];
9391 while (iscons(p3)) {
9392 push(car(p3));
9393 push(p2);
9394 gcd();
9395 multiply();
9396 results.push(p3 = cdr(p3));
9397 }
9398 return results;
9399 };
9400
9401 gcd_factor_term = function() {
9402 var results;
9403 push(one);
9404 p4 = cdr(p2);
9405 results = [];
9406 while (iscons(p4)) {
9407 push(p1);
9408 push(car(p4));
9409 gcd();
9410 multiply();
9411 results.push(p4 = cdr(p4));
9412 }
9413 return results;
9414 };
9415
9416 guess = function() {
9417 var p;
9418 p = pop();
9419 push(p);
9420 if (Find(p, symbol(SYMBOL_X))) {
9421 return push_symbol(SYMBOL_X);
9422 } else if (Find(p, symbol(SYMBOL_Y))) {
9423 return push_symbol(SYMBOL_Y);
9424 } else if (Find(p, symbol(SYMBOL_Z))) {
9425 return push_symbol(SYMBOL_Z);
9426 } else if (Find(p, symbol(SYMBOL_T))) {
9427 return push_symbol(SYMBOL_T);
9428 } else if (Find(p, symbol(SYMBOL_S))) {
9429 return push_symbol(SYMBOL_S);
9430 } else {
9431 return push_symbol(SYMBOL_X);
9432 }
9433 };
9434
9435 hermite = function() {
9436 save();
9437 yyhermite();
9438 return restore();
9439 };
9440
9441 yyhermite = function() {
9442 var n;
9443 n = 0;
9444 p2 = pop();
9445 p1 = pop();
9446 push(p2);
9447 n = pop_integer();
9448 if (n < 0 || n === 0x80000000) {
9449 push_symbol(HERMITE);
9450 push(p1);
9451 push(p2);
9452 list(3);
9453 return;
9454 }
9455 if (issymbol(p1)) {
9456 return yyhermite2(n);
9457 } else {
9458 p3 = p1;
9459 p1 = symbol(SECRETX);
9460 yyhermite2(n);
9461 p1 = p3;
9462 push(symbol(SECRETX));
9463 push(p1);
9464 subst();
9465 return Eval();
9466 }
9467 };
9468
9469 yyhermite2 = function(n) {
9470 var i, o, ref, results;
9471 i = 0;
9472 push_integer(1);
9473 push_integer(0);
9474 p4 = pop();
9475 results = [];
9476 for (i = o = 0, ref = n; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
9477 p5 = p4;
9478 p4 = pop();
9479 push(p1);
9480 push(p4);
9481 multiply();
9482 push_integer(i);
9483 push(p5);
9484 multiply();
9485 subtract();
9486 push_integer(2);
9487 results.push(multiply());
9488 }
9489 return results;
9490 };
9491
9492 hilbert = function() {
9493 var ac, i, j, n, o, ref, ref1;
9494 i = 0;
9495 j = 0;
9496 n = 0;
9497 save();
9498 p2 = pop();
9499 push(p2);
9500 n = pop_integer();
9501 if (n < 2) {
9502 push_symbol(HILBERT);
9503 push(p2);
9504 list(2);
9505 restore();
9506 return;
9507 }
9508 push_zero_matrix(n, n);
9509 p1 = pop();
9510 for (i = o = 0, ref = n; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
9511 for (j = ac = 0, ref1 = n; 0 <= ref1 ? ac < ref1 : ac > ref1; j = 0 <= ref1 ? ++ac : --ac) {
9512 push_integer(i + j + 1);
9513 inverse();
9514 p1.tensor.elem[i * n + j] = pop();
9515 }
9516 }
9517 push(p1);
9518 return restore();
9519 };
9520
9521
9522 /*
9523 Returns the coefficient of the imaginary part of complex z
9524
9525 z imag(z)
9526 - -------
9527
9528 a + i b b
9529
9530 exp(i a) sin(a)
9531 */
9532
9533 Eval_imag = function() {
9534 push(cadr(p1));
9535 Eval();
9536 return imag();
9537 };
9538
9539 imag = function() {
9540 save();
9541 rect();
9542 p1 = pop();
9543 push(p1);
9544 push(p1);
9545 conjugate();
9546 subtract();
9547 push_integer(2);
9548 divide();
9549 push(imaginaryunit);
9550 divide();
9551 return restore();
9552 };
9553
9554 index_function = function(n) {
9555 var ac, ad, ae, af, i, k, m, ndim, nelem, o, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, s, t;
9556 i = 0;
9557 k = 0;
9558 m = 0;
9559 ndim = 0;
9560 nelem = 0;
9561 t = 0;
9562 save();
9563 s = tos - n;
9564 p1 = stack[s];
9565 if (!istensor(p1)) {
9566 tos -= n;
9567 push(p1);
9568 restore();
9569 return;
9570 }
9571 ndim = p1.tensor.ndim;
9572 m = n - 1;
9573 if (m > ndim) {
9574 stop("too many indices for tensor");
9575 }
9576 k = 0;
9577 for (i = o = 0, ref = m; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
9578 push(stack[s + i + 1]);
9579 t = pop_integer();
9580 if (t < 1 || t > p1.tensor.dim[i]) {
9581 stop("index out of range");
9582 }
9583 k = k * p1.tensor.dim[i] + t - 1;
9584 }
9585 if (ndim === m) {
9586 tos -= n;
9587 push(p1.tensor.elem[k]);
9588 restore();
9589 return;
9590 }
9591 for (i = ac = ref1 = m, ref2 = ndim; ref1 <= ref2 ? ac < ref2 : ac > ref2; i = ref1 <= ref2 ? ++ac : --ac) {
9592 k = k * p1.tensor.dim[i] + 0;
9593 }
9594 nelem = 1;
9595 for (i = ad = ref3 = m, ref4 = ndim; ref3 <= ref4 ? ad < ref4 : ad > ref4; i = ref3 <= ref4 ? ++ad : --ad) {
9596 nelem *= p1.tensor.dim[i];
9597 }
9598 p2 = alloc_tensor(nelem);
9599 p2.tensor.ndim = ndim - m;
9600 for (i = ae = ref5 = m, ref6 = ndim; ref5 <= ref6 ? ae < ref6 : ae > ref6; i = ref5 <= ref6 ? ++ae : --ae) {
9601 p2.tensor.dim[i - m] = p1.tensor.dim[i];
9602 }
9603 for (i = af = 0, ref7 = nelem; 0 <= ref7 ? af < ref7 : af > ref7; i = 0 <= ref7 ? ++af : --af) {
9604 p2.tensor.elem[i] = p1.tensor.elem[k + i];
9605 }
9606 if (p1.tensor.nelem !== p1.tensor.elem.length) {
9607 console.log("something wrong in tensor dimensions");
9608 debugger;
9609 }
9610 if (p2.tensor.nelem !== p2.tensor.elem.length) {
9611 console.log("something wrong in tensor dimensions");
9612 debugger;
9613 }
9614 tos -= n;
9615 push(p2);
9616 return restore();
9617 };
9618
9619 set_component = function(n) {
9620 var ac, ad, ae, af, ag, i, k, m, ndim, o, ref, ref1, ref2, ref3, ref4, ref5, ref6, s, t;
9621 i = 0;
9622 k = 0;
9623 m = 0;
9624 ndim = 0;
9625 t = 0;
9626 save();
9627 if (n < 3) {
9628 stop("error in indexed assign");
9629 }
9630 s = tos - n;
9631 p2 = stack[s];
9632 p1 = stack[s + 1];
9633 if (!istensor(p1)) {
9634 stop("error in indexed assign");
9635 }
9636 ndim = p1.tensor.ndim;
9637 m = n - 2;
9638 if (m > ndim) {
9639 stop("error in indexed assign");
9640 }
9641 k = 0;
9642 for (i = o = 0, ref = m; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
9643 push(stack[s + i + 2]);
9644 t = pop_integer();
9645 if (t < 1 || t > p1.tensor.dim[i]) {
9646 stop("error in indexed assign\n");
9647 }
9648 k = k * p1.tensor.dim[i] + t - 1;
9649 }
9650 for (i = ac = ref1 = m, ref2 = ndim; ref1 <= ref2 ? ac < ref2 : ac > ref2; i = ref1 <= ref2 ? ++ac : --ac) {
9651 k = k * p1.tensor.dim[i] + 0;
9652 }
9653 p3 = alloc_tensor(p1.tensor.nelem);
9654 p3.tensor.ndim = p1.tensor.ndim;
9655 for (i = ad = 0, ref3 = p1.tensor.ndim; 0 <= ref3 ? ad < ref3 : ad > ref3; i = 0 <= ref3 ? ++ad : --ad) {
9656 p3.tensor.dim[i] = p1.tensor.dim[i];
9657 }
9658 for (i = ae = 0, ref4 = p1.tensor.nelem; 0 <= ref4 ? ae < ref4 : ae > ref4; i = 0 <= ref4 ? ++ae : --ae) {
9659 p3.tensor.elem[i] = p1.tensor.elem[i];
9660 }
9661 if (p1.tensor.nelem !== p1.tensor.elem.length) {
9662 console.log("something wrong in tensor dimensions");
9663 debugger;
9664 }
9665 if (p3.tensor.nelem !== p3.tensor.elem.length) {
9666 console.log("something wrong in tensor dimensions");
9667 debugger;
9668 }
9669 p1 = p3;
9670 if (ndim === m) {
9671 if (istensor(p2)) {
9672 stop("error in indexed assign");
9673 }
9674 p1.tensor.elem[k] = p2;
9675 if (p1.tensor.nelem !== p1.tensor.elem.length) {
9676 console.log("something wrong in tensor dimensions");
9677 debugger;
9678 }
9679 tos -= n;
9680 push(p1);
9681 restore();
9682 return;
9683 }
9684 if (!istensor(p2)) {
9685 stop("error in indexed assign");
9686 }
9687 if (ndim - m !== p2.tensor.ndim) {
9688 stop("error in indexed assign");
9689 }
9690 for (i = af = 0, ref5 = p2.tensor.ndim; 0 <= ref5 ? af < ref5 : af > ref5; i = 0 <= ref5 ? ++af : --af) {
9691 if (p1.tensor.dim[m + i] !== p2.tensor.dim[i]) {
9692 stop("error in indexed assign");
9693 }
9694 }
9695 for (i = ag = 0, ref6 = p2.tensor.nelem; 0 <= ref6 ? ag < ref6 : ag > ref6; i = 0 <= ref6 ? ++ag : --ag) {
9696 p1.tensor.elem[k + i] = p2.tensor.elem[i];
9697 }
9698 if (p1.tensor.nelem !== p1.tensor.elem.length) {
9699 console.log("something wrong in tensor dimensions");
9700 debugger;
9701 }
9702 if (p2.tensor.nelem !== p2.tensor.elem.length) {
9703 console.log("something wrong in tensor dimensions");
9704 debugger;
9705 }
9706 tos -= n;
9707 push(p1);
9708 return restore();
9709 };
9710
9711 Eval_inner = function() {
9712 var results;
9713 p1 = cdr(p1);
9714 push(car(p1));
9715 Eval();
9716 p1 = cdr(p1);
9717 results = [];
9718 while (iscons(p1)) {
9719 push(car(p1));
9720 Eval();
9721 inner();
9722 results.push(p1 = cdr(p1));
9723 }
9724 return results;
9725 };
9726
9727 inner = function() {
9728 save();
9729 p2 = pop();
9730 p1 = pop();
9731 if (istensor(p1) && istensor(p2)) {
9732 inner_f();
9733 } else {
9734 push(p1);
9735 push(p2);
9736 if (istensor(p1)) {
9737 tensor_times_scalar();
9738 } else if (istensor(p2)) {
9739 scalar_times_tensor();
9740 } else {
9741 multiply();
9742 }
9743 }
9744 return restore();
9745 };
9746
9747 inner_f = function() {
9748 var a, ac, ad, ae, af, ag, ah, ak, b, bk, c, i, j, k, n, ndim, o, ref, ref1, ref2, ref3, ref4, ref5, ref6;
9749 i = 0;
9750 n = p1.tensor.dim[p1.tensor.ndim - 1];
9751 if (n !== p2.tensor.dim[0]) {
9752 debugger;
9753 stop("inner: tensor dimension check");
9754 }
9755 ndim = p1.tensor.ndim + p2.tensor.ndim - 2;
9756 if (ndim > MAXDIM) {
9757 stop("inner: rank of result exceeds maximum");
9758 }
9759 a = p1.tensor.elem;
9760 b = p2.tensor.elem;
9761 ak = 1;
9762 for (i = o = 0, ref = p1.tensor.ndim - 1; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
9763 ak *= p1.tensor.dim[i];
9764 }
9765 bk = 1;
9766 for (i = ac = 1, ref1 = p2.tensor.ndim; 1 <= ref1 ? ac < ref1 : ac > ref1; i = 1 <= ref1 ? ++ac : --ac) {
9767 bk *= p2.tensor.dim[i];
9768 }
9769 p3 = alloc_tensor(ak * bk);
9770 c = p3.tensor.elem;
9771 for (i = ad = 0, ref2 = ak; 0 <= ref2 ? ad < ref2 : ad > ref2; i = 0 <= ref2 ? ++ad : --ad) {
9772 for (j = ae = 0, ref3 = n; 0 <= ref3 ? ae < ref3 : ae > ref3; j = 0 <= ref3 ? ++ae : --ae) {
9773 if (iszero(a[i * n + j])) {
9774 continue;
9775 }
9776 for (k = af = 0, ref4 = bk; 0 <= ref4 ? af < ref4 : af > ref4; k = 0 <= ref4 ? ++af : --af) {
9777 push(a[i * n + j]);
9778 push(b[j * bk + k]);
9779 multiply();
9780 push(c[i * bk + k]);
9781 add();
9782 c[i * bk + k] = pop();
9783 }
9784 }
9785 }
9786 if (ndim === 0) {
9787 return push(p3.tensor.elem[0]);
9788 } else {
9789 p3.tensor.ndim = ndim;
9790 j = 0;
9791 for (i = ag = 0, ref5 = p1.tensor.ndim - 1; 0 <= ref5 ? ag < ref5 : ag > ref5; i = 0 <= ref5 ? ++ag : --ag) {
9792 p3.tensor.dim[i] = p1.tensor.dim[i];
9793 }
9794 j = p1.tensor.ndim - 1;
9795 for (i = ah = 0, ref6 = p2.tensor.ndim - 1; 0 <= ref6 ? ah < ref6 : ah > ref6; i = 0 <= ref6 ? ++ah : --ah) {
9796 p3.tensor.dim[j + i] = p2.tensor.dim[i + 1];
9797 }
9798 return push(p3);
9799 }
9800 };
9801
9802
9803 /*
9804 Table of integrals
9805
9806 The symbol f is just a dummy symbol for creating a list f(A,B,C,C,...) where
9807
9808 A is the template expression
9809
9810 B is the result expression
9811
9812 C is an optional list of conditional expressions
9813 */
9814
9815 itab = ["f(a,a*x)", "f(1/x,log(x))", "f(x^a,x^(a+1)/(a+1))", "f(exp(a*x),1/a*exp(a*x))", "f(exp(a*x+b),1/a*exp(a*x+b))", "f(x*exp(a*x^2),exp(a*x^2)/(2*a))", "f(x*exp(a*x^2+b),exp(a*x^2+b)/(2*a))", "f(log(a*x),x*log(a*x)-x)", "f(a^x,a^x/log(a),or(not(number(a)),a>0))", "f(1/(a+x^2),1/sqrt(a)*arctan(x/sqrt(a)),or(not(number(a)),a>0))", "f(1/(a-x^2),1/sqrt(a)*arctanh(x/sqrt(a)))", "f(1/sqrt(a-x^2),arcsin(x/(sqrt(a))))", "f(1/sqrt(a+x^2),log(x+sqrt(a+x^2)))", "f(1/(a+b*x),1/b*log(a+b*x))", "f(1/(a+b*x)^2,-1/(b*(a+b*x)))", "f(1/(a+b*x)^3,-1/(2*b)*1/(a+b*x)^2)", "f(x/(a+b*x),x/b-a*log(a+b*x)/b/b)", "f(x/(a+b*x)^2,1/b^2*(log(a+b*x)+a/(a+b*x)))", "f(x^2/(a+b*x),1/b^2*(1/2*(a+b*x)^2-2*a*(a+b*x)+a^2*log(a+b*x)))", "f(x^2/(a+b*x)^2,1/b^3*(a+b*x-2*a*log(a+b*x)-a^2/(a+b*x)))", "f(x^2/(a+b*x)^3,1/b^3*(log(a+b*x)+2*a/(a+b*x)-1/2*a^2/(a+b*x)^2))", "f(1/x*1/(a+b*x),-1/a*log((a+b*x)/x))", "f(1/x*1/(a+b*x)^2,1/a*1/(a+b*x)-1/a^2*log((a+b*x)/x))", "f(1/x*1/(a+b*x)^3,1/a^3*(1/2*((2*a+b*x)/(a+b*x))^2+log(x/(a+b*x))))", "f(1/x^2*1/(a+b*x),-1/(a*x)+b/a^2*log((a+b*x)/x))", "f(1/x^3*1/(a+b*x),(2*b*x-a)/(2*a^2*x^2)+b^2/a^3*log(x/(a+b*x)))", "f(1/x^2*1/(a+b*x)^2,-(a+2*b*x)/(a^2*x*(a+b*x))+2*b/a^3*log((a+b*x)/x))", "f(1/(a+b*x^2),1/sqrt(a*b)*arctan(x*sqrt(a*b)/a),or(not(number(a*b)),a*b>0))", "f(1/(a+b*x^2),1/(2*sqrt(-a*b))*log((a+x*sqrt(-a*b))/(a-x*sqrt(-a*b))),or(not(number(a*b)),a*b<0))", "f(x/(a+b*x^2),1/2*1/b*log(a+b*x^2))", "f(x^2/(a+b*x^2),x/b-a/b*integral(1/(a+b*x^2),x))", "f(1/(a+b*x^2)^2,x/(2*a*(a+b*x^2))+1/2*1/a*integral(1/(a+b*x^2),x))", "f(1/x*1/(a+b*x^2),1/2*1/a*log(x^2/(a+b*x^2)))", "f(1/x^2*1/(a+b*x^2),-1/(a*x)-b/a*integral(1/(a+b*x^2),x))", "f(1/(a+b*x^3),1/3*1/a*(a/b)^(1/3)*(1/2*log(((a/b)^(1/3)+x)^3/(a+b*x^3))+sqrt(3)*arctan((2*x-(a/b)^(1/3))*(a/b)^(-1/3)/sqrt(3))))", "f(x^2/(a+b*x^3),1/3*1/b*log(a+b*x^3))", "f(1/(a+b*x^4),1/2*1/a*(a/b/4)^(1/4)*(1/2*log((x^2+2*(a/b/4)^(1/4)*x+2*(a/b/4)^(1/2))/(x^2-2*(a/b/4)^(1/4)*x+2*(a/b/4)^(1/2)))+arctan(2*(a/b/4)^(1/4)*x/(2*(a/b/4)^(1/2)-x^2))),or(not(number(a*b)),a*b>0))", "f(1/(a+b*x^4),1/2*(-a/b)^(1/4)/a*(1/2*log((x+(-a/b)^(1/4))/(x-(-a/b)^(1/4)))+arctan(x*(-a/b)^(-1/4))),or(not(number(a*b)),a*b<0))", "f(x/(a+b*x^4),1/2*sqrt(b/a)/b*arctan(x^2*sqrt(b/a)),or(not(number(a*b)),a*b>0))", "f(x/(a+b*x^4),1/4*sqrt(-b/a)/b*log((x^2-sqrt(-a/b))/(x^2+sqrt(-a/b))),or(not(number(a*b)),a*b<0))", "f(x^2/(a+b*x^4),1/4*1/b*(a/b/4)^(-1/4)*(1/2*log((x^2-2*(a/b/4)^(1/4)*x+2*sqrt(a/b/4))/(x^2+2*(a/b/4)^(1/4)*x+2*sqrt(a/b/4)))+arctan(2*(a/b/4)^(1/4)*x/(2*sqrt(a/b/4)-x^2))),or(not(number(a*b)),a*b>0))", "f(x^2/(a+b*x^4),1/4*1/b*(-a/b)^(-1/4)*(log((x-(-a/b)^(1/4))/(x+(-a/b)^(1/4)))+2*arctan(x*(-a/b)^(-1/4))),or(not(number(a*b)),a*b<0))", "f(x^3/(a+b*x^4),1/4*1/b*log(a+b*x^4))", "f(sqrt(a+b*x),2/3*1/b*sqrt((a+b*x)^3))", "f(x*sqrt(a+b*x),-2*(2*a-3*b*x)*sqrt((a+b*x)^3)/15/b^2)", "f(x^2*sqrt(a+b*x),2*(8*a^2-12*a*b*x+15*b^2*x^2)*sqrt((a+b*x)^3)/105/b^3)", "f(sqrt(a+b*x)/x,2*sqrt(a+b*x)+a*integral(1/x*1/sqrt(a+b*x),x))", "f(sqrt(a+b*x)/x^2,-sqrt(a+b*x)/x+b/2*integral(1/x*1/sqrt(a+b*x),x))", "f(1/sqrt(a+b*x),2*sqrt(a+b*x)/b)", "f(x/sqrt(a+b*x),-2/3*(2*a-b*x)*sqrt(a+b*x)/b^2)", "f(x^2/sqrt(a+b*x),2/15*(8*a^2-4*a*b*x+3*b^2*x^2)*sqrt(a+b*x)/b^3)", "f(1/x*1/sqrt(a+b*x),1/sqrt(a)*log((sqrt(a+b*x)-sqrt(a))/(sqrt(a+b*x)+sqrt(a))),or(not(number(a)),a>0))", "f(1/x*1/sqrt(a+b*x),2/sqrt(-a)*arctan(sqrt(-(a+b*x)/a)),or(not(number(a)),a<0))", "f(1/x^2*1/sqrt(a+b*x),-sqrt(a+b*x)/a/x-1/2*b/a*integral(1/x*1/sqrt(a+b*x),x))", "f(sqrt(x^2+a),1/2*(x*sqrt(x^2+a)+a*log(x+sqrt(x^2+a))))", "f(1/sqrt(x^2+a),log(x+sqrt(x^2+a)))", "f(1/x*1/sqrt(x^2+a),arcsec(x/sqrt(-a))/sqrt(-a),or(not(number(a)),a<0))", "f(1/x*1/sqrt(x^2+a),-1/sqrt(a)*log((sqrt(a)+sqrt(x^2+a))/x),or(not(number(a)),a>0))", "f(sqrt(x^2+a)/x,sqrt(x^2+a)-sqrt(a)*log((sqrt(a)+sqrt(x^2+a))/x),or(not(number(a)),a>0))", "f(sqrt(x^2+a)/x,sqrt(x^2+a)-sqrt(-a)*arcsec(x/sqrt(-a)),or(not(number(a)),a<0))", "f(x/sqrt(x^2+a),sqrt(x^2+a))", "f(x*sqrt(x^2+a),1/3*sqrt((x^2+a)^3))", "f(sqrt(a+x^6+3*a^(1/3)*x^4+3*a^(2/3)*x^2),1/4*(x*sqrt((x^2+a^(1/3))^3)+3/2*a^(1/3)*x*sqrt(x^2+a^(1/3))+3/2*a^(2/3)*log(x+sqrt(x^2+a^(1/3)))))", "f(sqrt(-a+x^6-3*a^(1/3)*x^4+3*a^(2/3)*x^2),1/4*(x*sqrt((x^2-a^(1/3))^3)-3/2*a^(1/3)*x*sqrt(x^2-a^(1/3))+3/2*a^(2/3)*log(x+sqrt(x^2-a^(1/3)))))", "f(1/sqrt(a+x^6+3*a^(1/3)*x^4+3*a^(2/3)*x^2),x/a^(1/3)/sqrt(x^2+a^(1/3)))", "f(x/sqrt(a+x^6+3*a^(1/3)*x^4+3*a^(2/3)*x^2),-1/sqrt(x^2+a^(1/3)))", "f(x*sqrt(a+x^6+3*a^(1/3)*x^4+3*a^(2/3)*x^2),1/5*sqrt((x^2+a^(1/3))^5))", "f(x^2*sqrt(x^2+a),1/4*x*sqrt((x^2+a)^3)-1/8*a*x*sqrt(x^2+a)-1/8*a^2*log(x+sqrt(x^2+a)))", "f(x^3*sqrt(x^2+a),(1/5*x^2-2/15*a)*sqrt((x^2+a)^3),and(number(a),a>0))", "f(x^3*sqrt(x^2+a),sqrt((x^2+a)^5)/5-a*sqrt((x^2+a)^3)/3,and(number(a),a<0))", "f(x^2/sqrt(x^2+a),1/2*x*sqrt(x^2+a)-1/2*a*log(x+sqrt(x^2+a)))", "f(x^3/sqrt(x^2+a),1/3*sqrt((x^2+a)^3)-a*sqrt(x^2+a))", "f(1/x^2*1/sqrt(x^2+a),-sqrt(x^2+a)/a/x)", "f(1/x^3*1/sqrt(x^2+a),-1/2*sqrt(x^2+a)/a/x^2+1/2*log((sqrt(a)+sqrt(x^2+a))/x)/a^(3/2),or(not(number(a)),a>0))", "f(1/x^3*1/sqrt(x^2-a),1/2*sqrt(x^2-a)/a/x^2+1/2*1/(a^(3/2))*arcsec(x/(a^(1/2))),or(not(number(a)),a>0))", "f(x^2*sqrt(a+x^6+3*a^(1/3)*x^4+3*a^(2/3)*x^2),1/6*x*sqrt((x^2+a^(1/3))^5)-1/24*a^(1/3)*x*sqrt((x^2+a^(1/3))^3)-1/16*a^(2/3)*x*sqrt(x^2+a^(1/3))-1/16*a*log(x+sqrt(x^2+a^(1/3))),or(not(number(a)),a>0))", "f(x^2*sqrt(-a-3*a^(1/3)*x^4+3*a^(2/3)*x^2+x^6),1/6*x*sqrt((x^2-a^(1/3))^5)+1/24*a^(1/3)*x*sqrt((x^2-a^(1/3))^3)-1/16*a^(2/3)*x*sqrt(x^2-a^(1/3))+1/16*a*log(x+sqrt(x^2-a^(1/3))),or(not(number(a)),a>0))", "f(x^3*sqrt(a+x^6+3*a^(1/3)*x^4+3*a^(2/3)*x^2),1/7*sqrt((x^2+a^(1/3))^7)-1/5*a^(1/3)*sqrt((x^2+a^(1/3))^5),or(not(number(a)),a>0))", "f(x^3*sqrt(-a-3*a^(1/3)*x^4+3*a^(2/3)*x^2+x^6),1/7*sqrt((x^2-a^(1/3))^7)+1/5*a^(1/3)*sqrt((x^2-a^(1/3))^5),or(not(number(a)),a>0))", "f(1/(x-a)/sqrt(x^2-a^2),-sqrt(x^2-a^2)/a/(x-a))", "f(1/(x+a)/sqrt(x^2-a^2),sqrt(x^2-a^2)/a/(x+a))", "f(sqrt(a-x^2),1/2*(x*sqrt(a-x^2)+a*arcsin(x/sqrt(abs(a)))))", "f(1/x*1/sqrt(a-x^2),-1/sqrt(a)*log((sqrt(a)+sqrt(a-x^2))/x),or(not(number(a)),a>0))", "f(sqrt(a-x^2)/x,sqrt(a-x^2)-sqrt(a)*log((sqrt(a)+sqrt(a-x^2))/x),or(not(number(a)),a>0))", "f(x/sqrt(a-x^2),-sqrt(a-x^2))", "f(x*sqrt(a-x^2),-1/3*sqrt((a-x^2)^3))", "f(x^2*sqrt(a-x^2),-x/4*sqrt((a-x^2)^3)+1/8*a*(x*sqrt(a-x^2)+a*arcsin(x/sqrt(a))),or(not(number(a)),a>0))", "f(x^3*sqrt(a-x^2),(-1/5*x^2-2/15*a)*sqrt((a-x^2)^3),or(not(number(a)),a>0))", "f(x^2/sqrt(a-x^2),-x/2*sqrt(a-x^2)+a/2*arcsin(x/sqrt(a)),or(not(number(a)),a>0))", "f(1/x^2*1/sqrt(a-x^2),-sqrt(a-x^2)/a/x,or(not(number(a)),a>0))", "f(sqrt(a-x^2)/x^2,-sqrt(a-x^2)/x-arcsin(x/sqrt(a)),or(not(number(a)),a>0))", "f(sqrt(a-x^2)/x^3,-1/2*sqrt(a-x^2)/x^2+1/2*log((sqrt(a)+sqrt(a-x^2))/x)/sqrt(a),or(not(number(a)),a>0))", "f(sqrt(a-x^2)/x^4,-1/3*sqrt((a-x^2)^3)/a/x^3,or(not(number(a)),a>0))", "f(sqrt(a*x^2+b),x*sqrt(a*x^2+b)/2+b*log(x*sqrt(a)+sqrt(a*x^2+b))/2/sqrt(a),and(number(a),a>0))", "f(sqrt(a*x^2+b),x*sqrt(a*x^2+b)/2+b*arcsin(x*sqrt(-a/b))/2/sqrt(-a),and(number(a),a<0))", "f(sin(a*x),-cos(a*x)/a)", "f(cos(a*x),sin(a*x)/a)", "f(tan(a*x),-log(cos(a*x))/a)", "f(1/tan(a*x),log(sin(a*x))/a)", "f(1/cos(a*x),log(tan(pi/4+a*x/2))/a)", "f(1/sin(a*x),log(tan(a*x/2))/a)", "f(sin(a*x)^2,x/2-sin(2*a*x)/(4*a))", "f(sin(a*x)^3,-cos(a*x)*(sin(a*x)^2+2)/(3*a))", "f(sin(a*x)^4,3/8*x-sin(2*a*x)/(4*a)+sin(4*a*x)/(32*a))", "f(cos(a*x)^2,x/2+sin(2*a*x)/(4*a))", "f(cos(a*x)^3,sin(a*x)*(cos(a*x)^2+2)/(3*a))", "f(cos(a*x)^4,3/8*x+sin(2*a*x)/(4*a)+sin(4*a*x)/(32*a))", "f(1/sin(a*x)^2,-1/(a*tan(a*x)))", "f(1/cos(a*x)^2,tan(a*x)/a)", "f(sin(a*x)*cos(a*x),sin(a*x)^2/(2*a))", "f(sin(a*x)^2*cos(a*x)^2,-sin(4*a*x)/(32*a)+x/8)", "f(sin(a*x)/cos(a*x)^2,1/(a*cos(a*x)))", "f(sin(a*x)^2/cos(a*x),(log(tan(pi/4+a*x/2))-sin(a*x))/a)", "f(cos(a*x)/sin(a*x)^2,-1/(a*sin(a*x)))", "f(1/(sin(a*x)*cos(a*x)),log(tan(a*x))/a)", "f(1/(sin(a*x)*cos(a*x)^2),(1/cos(a*x)+log(tan(a*x/2)))/a)", "f(1/(sin(a*x)^2*cos(a*x)),(log(tan(pi/4+a*x/2))-1/sin(a*x))/a)", "f(1/(sin(a*x)^2*cos(a*x)^2),-2/(a*tan(2*a*x)))", "f(sin(a+b*x),-cos(a+b*x)/b)", "f(cos(a+b*x),sin(a+b*x)/b)", "f(1/(b+b*sin(a*x)),-tan(pi/4-a*x/2)/a/b)", "f(1/(b-b*sin(a*x)),tan(pi/4+a*x/2)/a/b)", "f(1/(b+b*cos(a*x)),tan(a*x/2)/a/b)", "f(1/(b-b*cos(a*x)),-1/tan(a*x/2)/a/b)", "f(1/(a+b*sin(x)),1/sqrt(b^2-a^2)*log((a*tan(x/2)+b-sqrt(b^2-a^2))/(a*tan(x/2)+b+sqrt(b^2-a^2))),b^2-a^2)", "f(1/(a+b*cos(x)),1/sqrt(b^2-a^2)*log((sqrt(b^2-a^2)*tan(x/2)+a+b)/(sqrt(b^2-a^2)*tan(x/2)-a-b)),b^2-a^2)", "f(x*sin(a*x),sin(a*x)/a^2-x*cos(a*x)/a)", "f(x^2*sin(a*x),2*x*sin(a*x)/a^2-(a^2*x^2-2)*cos(a*x)/a^3)", "f(x*cos(a*x),cos(a*x)/a^2+x*sin(a*x)/a)", "f(x^2*cos(a*x),2*x*cos(a*x)/a^2+(a^2*x^2-2)*sin(a*x)/a^3)", "f(arcsin(a*x),x*arcsin(a*x)+sqrt(1-a^2*x^2)/a)", "f(arccos(a*x),x*arccos(a*x)-sqrt(1-a^2*x^2)/a)", "f(arctan(a*x),x*arctan(a*x)-1/2*log(1+a^2*x^2)/a)", "f(log(a*x),x*log(a*x)-x)", "f(x*log(a*x),x^2*log(a*x)/2-x^2/4)", "f(x^2*log(a*x),x^3*log(a*x)/3-1/9*x^3)", "f(log(x)^2,x*log(x)^2-2*x*log(x)+2*x)", "f(1/x*1/(a+log(x)),log(a+log(x)))", "f(log(a*x+b),(a*x+b)*log(a*x+b)/a-x)", "f(log(a*x+b)/x^2,a/b*log(x)-(a*x+b)*log(a*x+b)/b/x)", "f(sinh(x),cosh(x))", "f(cosh(x),sinh(x))", "f(tanh(x),log(cosh(x)))", "f(x*sinh(x),x*cosh(x)-sinh(x))", "f(x*cosh(x),x*sinh(x)-cosh(x))", "f(sinh(x)^2,sinh(2*x)/4-x/2)", "f(tanh(x)^2,x-tanh(x))", "f(cosh(x)^2,sinh(2*x)/4+x/2)", "f(x^3*exp(a*x^2),exp(a*x^2)*(x^2/a-1/(a^2))/2)", "f(x^3*exp(a*x^2+b),exp(a*x^2)*exp(b)*(x^2/a-1/(a^2))/2)", "f(exp(a*x^2),-i*sqrt(pi)*erf(i*sqrt(a)*x)/sqrt(a)/2)", "f(erf(a*x),x*erf(a*x)+exp(-a^2*x^2)/a/sqrt(pi))", "f(x^2*(1-x^2)^(3/2),(x*sqrt(1-x^2)*(-8*x^4+14*x^2-3)+3*arcsin(x))/48)", "f(x^2*(1-x^2)^(5/2),(x*sqrt(1-x^2)*(48*x^6-136*x^4+118*x^2-15)+15*arcsin(x))/384)", "f(x^4*(1-x^2)^(3/2),(-x*sqrt(1-x^2)*(16*x^6-24*x^4+2*x^2+3)+3*arcsin(x))/128)", "f(x*exp(a*x),exp(a*x)*(a*x-1)/(a^2))", "f(x*exp(a*x+b),exp(a*x+b)*(a*x-1)/(a^2))", "f(x^2*exp(a*x),exp(a*x)*(a^2*x^2-2*a*x+2)/(a^3))", "f(x^2*exp(a*x+b),exp(a*x+b)*(a^2*x^2-2*a*x+2)/(a^3))", "f(x^3*exp(a*x),exp(a*x)*x^3/a-3/a*integral(x^2*exp(a*x),x))", "f(x^3*exp(a*x+b),exp(a*x+b)*x^3/a-3/a*integral(x^2*exp(a*x+b),x))", 0];
9816
9817 Eval_integral = function() {
9818 var ac, doNothing, i, n, o, ref, ref1;
9819 i = 0;
9820 n = 0;
9821 p1 = cdr(p1);
9822 push(car(p1));
9823 Eval();
9824 p1 = cdr(p1);
9825 push(car(p1));
9826 Eval();
9827 p2 = pop();
9828 if (p2 === symbol(NIL)) {
9829 guess();
9830 push(symbol(NIL));
9831 } else if (isnum(p2)) {
9832 guess();
9833 push(p2);
9834 } else {
9835 push(p2);
9836 p1 = cdr(p1);
9837 push(car(p1));
9838 Eval();
9839 }
9840 p5 = pop();
9841 p4 = pop();
9842 p3 = pop();
9843 while (1.) {
9844 if (isnum(p5)) {
9845 push(p5);
9846 n = pop_integer();
9847 if (n === 0x80000000) {
9848 stop("nth integral: check n");
9849 }
9850 } else {
9851 n = 1;
9852 }
9853 push(p3);
9854 if (n >= 0) {
9855 for (i = o = 0, ref = n; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
9856 push(p4);
9857 integral();
9858 }
9859 } else {
9860 n = -n;
9861 for (i = ac = 0, ref1 = n; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
9862 push(p4);
9863 derivative();
9864 }
9865 }
9866 p3 = pop();
9867 if (p5 === symbol(NIL)) {
9868 break;
9869 }
9870 if (isnum(p5)) {
9871 p1 = cdr(p1);
9872 push(car(p1));
9873 Eval();
9874 p5 = pop();
9875 if (p5 === symbol(NIL)) {
9876 break;
9877 }
9878 if (isnum(p5)) {
9879 doNothing = 1;
9880 } else {
9881 p4 = p5;
9882 p1 = cdr(p1);
9883 push(car(p1));
9884 Eval();
9885 p5 = pop();
9886 }
9887 } else {
9888 p4 = p5;
9889 p1 = cdr(p1);
9890 push(car(p1));
9891 Eval();
9892 p5 = pop();
9893 }
9894 }
9895 return push(p3);
9896 };
9897
9898 integral = function() {
9899 save();
9900 p2 = pop();
9901 p1 = pop();
9902 if (car(p1) === symbol(ADD)) {
9903 integral_of_sum();
9904 } else if (car(p1) === symbol(MULTIPLY)) {
9905 integral_of_product();
9906 } else {
9907 integral_of_form();
9908 }
9909 p1 = pop();
9910 if (Find(p1, symbol(INTEGRAL))) {
9911 stop("integral: sorry, could not find a solution");
9912 }
9913 push(p1);
9914 simplify();
9915 Eval();
9916 return restore();
9917 };
9918
9919 integral_of_sum = function() {
9920 var results;
9921 p1 = cdr(p1);
9922 push(car(p1));
9923 push(p2);
9924 integral();
9925 p1 = cdr(p1);
9926 results = [];
9927 while (iscons(p1)) {
9928 push(car(p1));
9929 push(p2);
9930 integral();
9931 add();
9932 results.push(p1 = cdr(p1));
9933 }
9934 return results;
9935 };
9936
9937 integral_of_product = function() {
9938 push(p1);
9939 push(p2);
9940 partition();
9941 p1 = pop();
9942 integral_of_form();
9943 return multiply();
9944 };
9945
9946 integral_of_form = function() {
9947 push(p1);
9948 push(p2);
9949 transform(itab);
9950 p3 = pop();
9951 if (p3 === symbol(NIL)) {
9952 push_symbol(INTEGRAL);
9953 push(p1);
9954 push(p2);
9955 return list(3);
9956 } else {
9957 return push(p3);
9958 }
9959 };
9960
9961 INV_check_arg = function() {
9962 if (!istensor(p1)) {
9963 return 0;
9964 } else if (p1.tensor.ndim !== 2) {
9965 return 0;
9966 } else if (p1.tensor.dim[0] !== p1.tensor.dim[1]) {
9967 return 0;
9968 } else {
9969 return 1;
9970 }
9971 };
9972
9973 inv = function() {
9974 var a, i, n, o, ref;
9975 i = 0;
9976 n = 0;
9977 save();
9978 p1 = pop();
9979 if (INV_check_arg() === 0) {
9980 push_symbol(INV);
9981 push(p1);
9982 list(2);
9983 restore();
9984 return;
9985 }
9986 n = p1.tensor.nelem;
9987 a = p1.tensor.elem;
9988 for (i = o = 0, ref = n; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
9989 if (!isnum(a[i])) {
9990 break;
9991 }
9992 }
9993 if (i === n) {
9994 yyinvg();
9995 } else {
9996 push(p1);
9997 adj();
9998 push(p1);
9999 det();
10000 p2 = pop();
10001 if (iszero(p2)) {
10002 stop("inverse of singular matrix");
10003 }
10004 push(p2);
10005 divide();
10006 }
10007 return restore();
10008 };
10009
10010 invg = function() {
10011 save();
10012 p1 = pop();
10013 if (INV_check_arg() === 0) {
10014 push_symbol(INVG);
10015 push(p1);
10016 list(2);
10017 restore();
10018 return;
10019 }
10020 yyinvg();
10021 return restore();
10022 };
10023
10024 yyinvg = function() {
10025 var ac, ad, ae, h, i, j, n, o, ref, ref1, ref2, ref3;
10026 h = 0;
10027 i = 0;
10028 j = 0;
10029 n = 0;
10030 n = p1.tensor.dim[0];
10031 h = tos;
10032 for (i = o = 0, ref = n; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
10033 for (j = ac = 0, ref1 = n; 0 <= ref1 ? ac < ref1 : ac > ref1; j = 0 <= ref1 ? ++ac : --ac) {
10034 if (i === j) {
10035 push(one);
10036 } else {
10037 push(zero);
10038 }
10039 }
10040 }
10041 for (i = ad = 0, ref2 = n * n; 0 <= ref2 ? ad < ref2 : ad > ref2; i = 0 <= ref2 ? ++ad : --ad) {
10042 push(p1.tensor.elem[i]);
10043 }
10044 INV_decomp(n);
10045 p1 = alloc_tensor(n * n);
10046 p1.tensor.ndim = 2;
10047 p1.tensor.dim[0] = n;
10048 p1.tensor.dim[1] = n;
10049 for (i = ae = 0, ref3 = n * n; 0 <= ref3 ? ae < ref3 : ae > ref3; i = 0 <= ref3 ? ++ae : --ae) {
10050 p1.tensor.elem[i] = stack[h + i];
10051 }
10052 tos -= 2 * n * n;
10053 return push(p1);
10054 };
10055
10056 INV_decomp = function(n) {
10057 var a, ac, ad, ae, d, i, j, o, ref, ref1, ref2, ref3, ref4, results, u;
10058 a = 0;
10059 d = 0;
10060 i = 0;
10061 j = 0;
10062 u = 0;
10063 a = tos - n * n;
10064 u = a - n * n;
10065 results = [];
10066 for (d = o = 0, ref = n; 0 <= ref ? o < ref : o > ref; d = 0 <= ref ? ++o : --o) {
10067 if (equal(stack[a + n * d + d], zero)) {
10068 for (i = ac = ref1 = d + 1, ref2 = n; ref1 <= ref2 ? ac < ref2 : ac > ref2; i = ref1 <= ref2 ? ++ac : --ac) {
10069 if (!equal(stack[a + n * i + d], zero)) {
10070 break;
10071 }
10072 }
10073 if (i === n) {
10074 stop("inverse of singular matrix");
10075 }
10076 for (j = ad = 0, ref3 = n; 0 <= ref3 ? ad < ref3 : ad > ref3; j = 0 <= ref3 ? ++ad : --ad) {
10077 p2 = stack[a + n * d + j];
10078 stack[a + n * d + j] = stack[a + n * i + j];
10079 stack[a + n * i + j] = p2;
10080 p2 = stack[u + n * d + j];
10081 stack[u + n * d + j] = stack[u + n * i + j];
10082 stack[u + n * i + j] = p2;
10083 }
10084 }
10085 p2 = stack[a + n * d + d];
10086 for (j = ae = 0, ref4 = n; 0 <= ref4 ? ae < ref4 : ae > ref4; j = 0 <= ref4 ? ++ae : --ae) {
10087 if (j > d) {
10088 push(stack[a + n * d + j]);
10089 push(p2);
10090 divide();
10091 stack[a + n * d + j] = pop();
10092 }
10093 push(stack[u + n * d + j]);
10094 push(p2);
10095 divide();
10096 stack[u + n * d + j] = pop();
10097 }
10098 results.push((function() {
10099 var af, ref5, results1;
10100 results1 = [];
10101 for (i = af = 0, ref5 = n; 0 <= ref5 ? af < ref5 : af > ref5; i = 0 <= ref5 ? ++af : --af) {
10102 if (i === d) {
10103 continue;
10104 }
10105 p2 = stack[a + n * i + d];
10106 results1.push((function() {
10107 var ag, ref6, results2;
10108 results2 = [];
10109 for (j = ag = 0, ref6 = n; 0 <= ref6 ? ag < ref6 : ag > ref6; j = 0 <= ref6 ? ++ag : --ag) {
10110 if (j > d) {
10111 push(stack[a + n * i + j]);
10112 push(stack[a + n * d + j]);
10113 push(p2);
10114 multiply();
10115 subtract();
10116 stack[a + n * i + j] = pop();
10117 }
10118 push(stack[u + n * i + j]);
10119 push(stack[u + n * d + j]);
10120 push(p2);
10121 multiply();
10122 subtract();
10123 results2.push(stack[u + n * i + j] = pop());
10124 }
10125 return results2;
10126 })());
10127 }
10128 return results1;
10129 })());
10130 }
10131 return results;
10132 };
10133
10134 iszero = function(p) {
10135 var i, o, ref;
10136 i = 0;
10137 switch (p.k) {
10138 case NUM:
10139 if (MZERO(p.q.a)) {
10140 return 1;
10141 }
10142 break;
10143 case DOUBLE:
10144 if (p.d === 0.0) {
10145 return 1;
10146 }
10147 break;
10148 case TENSOR:
10149 for (i = o = 0, ref = p.tensor.nelem; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
10150 if (!iszero(p.tensor.elem[i])) {
10151 return 0;
10152 }
10153 }
10154 return 1;
10155 }
10156 return 0;
10157 };
10158
10159 isnegativenumber = function(p) {
10160 switch (p.k) {
10161 case NUM:
10162 if (MSIGN(p.q.a) === -1) {
10163 return 1;
10164 }
10165 break;
10166 case DOUBLE:
10167 if (p.d < 0.0) {
10168 return 1;
10169 }
10170 }
10171 return 0;
10172 };
10173
10174 isplusone = function(p) {
10175 switch (p.k) {
10176 case NUM:
10177 if (MEQUAL(p.q.a, 1) && MEQUAL(p.q.b, 1)) {
10178 return 1;
10179 }
10180 break;
10181 case DOUBLE:
10182 if (p.d === 1.0) {
10183 return 1;
10184 }
10185 }
10186 return 0;
10187 };
10188
10189 isminusone = function(p) {
10190 switch (p.k) {
10191 case NUM:
10192 if (MEQUAL(p.q.a, -1) && MEQUAL(p.q.b, 1)) {
10193 return 1;
10194 }
10195 break;
10196 case DOUBLE:
10197 if (p.d === -1.0) {
10198 return 1;
10199 }
10200 }
10201 return 0;
10202 };
10203
10204 isinteger = function(p) {
10205 if (p.k === NUM && MEQUAL(p.q.b, 1)) {
10206 return 1;
10207 } else {
10208 return 0;
10209 }
10210 };
10211
10212 isnonnegativeinteger = function(p) {
10213 if (isrational(p) && MEQUAL(p.q.b, 1) && MSIGN(p.q.a) === 1) {
10214 return 1;
10215 } else {
10216 return 0;
10217 }
10218 };
10219
10220 isposint = function(p) {
10221 if (isinteger(p) && MSIGN(p.q.a) === 1) {
10222 return 1;
10223 } else {
10224 return 0;
10225 }
10226 };
10227
10228 ispoly = function(p, x) {
10229 if (Find(p, x)) {
10230 return ispoly_expr(p, x);
10231 } else {
10232 return 0;
10233 }
10234 };
10235
10236 ispoly_expr = function(p, x) {
10237 if (car(p) === symbol(ADD)) {
10238 p = cdr(p);
10239 while (iscons(p)) {
10240 if (!ispoly_term(car(p), x)) {
10241 return 0;
10242 }
10243 p = cdr(p);
10244 }
10245 return 1;
10246 } else {
10247 return ispoly_term(p, x);
10248 }
10249 };
10250
10251 ispoly_term = function(p, x) {
10252 if (car(p) === symbol(MULTIPLY)) {
10253 p = cdr(p);
10254 while (iscons(p)) {
10255 if (!ispoly_factor(car(p), x)) {
10256 return 0;
10257 }
10258 p = cdr(p);
10259 }
10260 return 1;
10261 } else {
10262 return ispoly_factor(p, x);
10263 }
10264 };
10265
10266 ispoly_factor = function(p, x) {
10267 if (equal(p, x)) {
10268 return 1;
10269 }
10270 if (car(p) === symbol(POWER) && equal(cadr(p), x)) {
10271 if (isposint(caddr(p))) {
10272 return 1;
10273 } else {
10274 return 0;
10275 }
10276 }
10277 if (Find(p, x)) {
10278 return 0;
10279 } else {
10280 return 1;
10281 }
10282 };
10283
10284 isnegativeterm = function(p) {
10285 if (isnegativenumber(p)) {
10286 return 1;
10287 } else if (car(p) === symbol(MULTIPLY) && isnegativenumber(cadr(p))) {
10288 return 1;
10289 } else {
10290 return 0;
10291 }
10292 };
10293
10294 isimaginarynumber = function(p) {
10295 if ((car(p) === symbol(MULTIPLY) && length(p) === 3 && isnum(cadr(p)) && equal(caddr(p), imaginaryunit)) || equal(p, imaginaryunit)) {
10296 return 1;
10297 } else {
10298 return 0;
10299 }
10300 };
10301
10302 iscomplexnumber = function(p) {
10303 if ((car(p) === symbol(ADD) && length(p) === 3 && isnum(cadr(p)) && isimaginarynumber(caddr(p))) || isimaginarynumber(p)) {
10304 return 1;
10305 } else {
10306 return 0;
10307 }
10308 };
10309
10310 iseveninteger = function(p) {
10311 if (isinteger(p) && p.q.a.isEven()) {
10312 return 1;
10313 } else {
10314 return 0;
10315 }
10316 };
10317
10318 isnegative = function(p) {
10319 if (car(p) === symbol(ADD) && isnegativeterm(cadr(p))) {
10320 return 1;
10321 } else if (isnegativeterm(p)) {
10322 return 1;
10323 } else {
10324 return 0;
10325 }
10326 };
10327
10328 issymbolic = function(p) {
10329 if (issymbol(p)) {
10330 return 1;
10331 } else {
10332 while (iscons(p)) {
10333 if (issymbolic(car(p))) {
10334 return 1;
10335 }
10336 p = cdr(p);
10337 }
10338 return 0;
10339 }
10340 };
10341
10342 isintegerfactor = function(p) {
10343 if (isinteger(p) || car(p) === symbol(POWER) && isinteger(cadr(p)) && isinteger(caddr(p))) {
10344 return 1;
10345 } else {
10346 return 0;
10347 }
10348 };
10349
10350 isoneover = function(p) {
10351 if (car(p) === symbol(POWER) && isminusone(caddr(p))) {
10352 return 1;
10353 } else {
10354 return 0;
10355 }
10356 };
10357
10358 isfraction = function(p) {
10359 if (p.k === NUM && !MEQUAL(p.q.b, 1)) {
10360 return 1;
10361 } else {
10362 return 0;
10363 }
10364 };
10365
10366 equaln = function(p, n) {
10367 switch (p.k) {
10368 case NUM:
10369 if (MEQUAL(p.q.a, n) && MEQUAL(p.q.b, 1)) {
10370 return 1;
10371 }
10372 break;
10373 case DOUBLE:
10374 if (p.d === n) {
10375 return 1;
10376 }
10377 }
10378 return 0;
10379 };
10380
10381 equalq = function(p, a, b) {
10382 switch (p.k) {
10383 case NUM:
10384 if (MEQUAL(p.q.a, a) && MEQUAL(p.q.b, b)) {
10385 return 1;
10386 }
10387 break;
10388 case DOUBLE:
10389 if (p.d === a / b) {
10390 return 1;
10391 }
10392 }
10393 return 0;
10394 };
10395
10396 isoneoversqrttwo = function(p) {
10397 if (car(p) === symbol(POWER) && equaln(cadr(p), 2) && equalq(caddr(p), -1, 2)) {
10398 return 1;
10399 } else {
10400 return 0;
10401 }
10402 };
10403
10404 isminusoneoversqrttwo = function(p) {
10405 if (car(p) === symbol(MULTIPLY) && equaln(cadr(p), -1) && isoneoversqrttwo(caddr(p)) && length(p) === 3) {
10406 return 1;
10407 } else {
10408 return 0;
10409 }
10410 };
10411
10412 isfloating = function(p) {
10413 if (p.k === DOUBLE) {
10414 return 1;
10415 }
10416 while (iscons(p)) {
10417 if (isfloating(car(p))) {
10418 return 1;
10419 }
10420 p = cdr(p);
10421 }
10422 return 0;
10423 };
10424
10425 isimaginaryunit = function(p) {
10426 if (equal(p, imaginaryunit)) {
10427 return 1;
10428 } else {
10429 return 0;
10430 }
10431 };
10432
10433 isquarterturn = function(p) {
10434 var minussign, n;
10435 n = 0;
10436 minussign = 0;
10437 if (car(p) !== symbol(MULTIPLY)) {
10438 return 0;
10439 }
10440 if (equal(cadr(p), imaginaryunit)) {
10441 if (caddr(p) !== symbol(PI)) {
10442 return 0;
10443 }
10444 if (length(p) !== 3) {
10445 return 0;
10446 }
10447 return 2;
10448 }
10449 if (!isnum(cadr(p))) {
10450 return 0;
10451 }
10452 if (!equal(caddr(p), imaginaryunit)) {
10453 return 0;
10454 }
10455 if (cadddr(p) !== symbol(PI)) {
10456 return 0;
10457 }
10458 if (length(p) !== 4) {
10459 return 0;
10460 }
10461 push(cadr(p));
10462 push_integer(2);
10463 multiply();
10464 n = pop_integer();
10465 if (n === 0x80000000) {
10466 return 0;
10467 }
10468 if (n < 1) {
10469 minussign = 1;
10470 n = -n;
10471 }
10472 switch (n % 4) {
10473 case 0:
10474 n = 1;
10475 break;
10476 case 1:
10477 if (minussign) {
10478 n = 4;
10479 } else {
10480 n = 3;
10481 }
10482 break;
10483 case 2:
10484 n = 2;
10485 break;
10486 case 3:
10487 if (minussign) {
10488 n = 3;
10489 } else {
10490 n = 4;
10491 }
10492 }
10493 return n;
10494 };
10495
10496 isnpi = function(p) {
10497 var doNothing, n;
10498 n = 0;
10499 if (p === symbol(PI)) {
10500 return 2;
10501 }
10502 if (car(p) === symbol(MULTIPLY) && isnum(cadr(p)) && caddr(p) === symbol(PI) && length(p) === 3) {
10503 doNothing = 0;
10504 } else {
10505 return 0;
10506 }
10507 push(cadr(p));
10508 push_integer(2);
10509 multiply();
10510 n = pop_integer();
10511 if (n === 0x80000000) {
10512 return 0;
10513 }
10514 if (n < 0) {
10515 n = 4 - (-n) % 4;
10516 } else {
10517 n = 1 + (n - 1) % 4;
10518 }
10519 return n;
10520 };
10521
10522 $.iszero = iszero;
10523
10524 $.isnegativenumber = isnegativenumber;
10525
10526 $.isplusone = isplusone;
10527
10528 $.isminusone = isminusone;
10529
10530 $.isinteger = isinteger;
10531
10532 $.isnonnegativeinteger = isnonnegativeinteger;
10533
10534 $.isposint = isposint;
10535
10536 $.isnegativeterm = isnegativeterm;
10537
10538 $.isimaginarynumber = isimaginarynumber;
10539
10540 $.iscomplexnumber = iscomplexnumber;
10541
10542 $.iseveninteger = iseveninteger;
10543
10544 $.isnegative = isnegative;
10545
10546 $.issymbolic = issymbolic;
10547
10548 $.isintegerfactor = isintegerfactor;
10549
10550 $.isoneover = isoneover;
10551
10552 $.isfraction = isfraction;
10553
10554 $.isoneoversqrttwo = isoneoversqrttwo;
10555
10556 $.isminusoneoversqrttwo = isminusoneoversqrttwo;
10557
10558 $.isfloating = isfloating;
10559
10560 $.isimaginaryunit = isimaginaryunit;
10561
10562 $.isquarterturn = isquarterturn;
10563
10564 $.isnpi = isnpi;
10565
10566 Eval_isprime = function() {
10567 push(cadr(p1));
10568 Eval();
10569 p1 = pop();
10570 if (isnonnegativeinteger(p1) && mprime(p1.q.a)) {
10571 return push_integer(1);
10572 } else {
10573 return push_integer(0);
10574 }
10575 };
10576
10577
10578 /*
10579 Laguerre function
10580
10581 Example
10582
10583 laguerre(x,3)
10584
10585 Result
10586
10587 1 3 3 2
10588 - --- x + --- x - 3 x + 1
10589 6 2
10590
10591 The computation uses the following recurrence relation.
10592
10593 L(x,0,k) = 1
10594
10595 L(x,1,k) = -x + k + 1
10596
10597 n*L(x,n,k) = (2*(n-1)+1-x+k)*L(x,n-1,k) - (n-1+k)*L(x,n-2,k)
10598
10599 In the "for" loop i = n-1 so the recurrence relation becomes
10600
10601 (i+1)*L(x,n,k) = (2*i+1-x+k)*L(x,n-1,k) - (i+k)*L(x,n-2,k)
10602 */
10603
10604 Eval_laguerre = function() {
10605 push(cadr(p1));
10606 Eval();
10607 push(caddr(p1));
10608 Eval();
10609 push(cadddr(p1));
10610 Eval();
10611 p2 = pop();
10612 if (p2 === symbol(NIL)) {
10613 push_integer(0);
10614 } else {
10615 push(p2);
10616 }
10617 return laguerre();
10618 };
10619
10620 laguerre = function() {
10621 var n;
10622 n = 0;
10623 save();
10624 p3 = pop();
10625 p2 = pop();
10626 p1 = pop();
10627 push(p2);
10628 n = pop_integer();
10629 if (n < 0 || n === 0x80000000) {
10630 push_symbol(LAGUERRE);
10631 push(p1);
10632 push(p2);
10633 push(p3);
10634 list(4);
10635 restore();
10636 return;
10637 }
10638 if (issymbol(p1)) {
10639 laguerre2(n);
10640 } else {
10641 p4 = p1;
10642 p1 = symbol(SECRETX);
10643 laguerre2(n);
10644 p1 = p4;
10645 push(symbol(SECRETX));
10646 push(p1);
10647 subst();
10648 Eval();
10649 }
10650 return restore();
10651 };
10652
10653 laguerre2 = function(n) {
10654 var i, o, ref, results;
10655 i = 0;
10656 push_integer(1);
10657 push_integer(0);
10658 p6 = pop();
10659 results = [];
10660 for (i = o = 0, ref = n; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
10661 p5 = p6;
10662 p6 = pop();
10663 push_integer(2 * i + 1);
10664 push(p1);
10665 subtract();
10666 push(p3);
10667 add();
10668 push(p6);
10669 multiply();
10670 push_integer(i);
10671 push(p3);
10672 add();
10673 push(p5);
10674 multiply();
10675 subtract();
10676 push_integer(i + 1);
10677 results.push(divide());
10678 }
10679 return results;
10680 };
10681
10682 Eval_lcm = function() {
10683 var results;
10684 p1 = cdr(p1);
10685 push(car(p1));
10686 Eval();
10687 p1 = cdr(p1);
10688 results = [];
10689 while (iscons(p1)) {
10690 push(car(p1));
10691 Eval();
10692 lcm();
10693 results.push(p1 = cdr(p1));
10694 }
10695 return results;
10696 };
10697
10698 lcm = function() {
10699 var x;
10700 x = 0;
10701 x = expanding;
10702 save();
10703 yylcm();
10704 restore();
10705 return expanding = x;
10706 };
10707
10708 yylcm = function() {
10709 expanding = 1;
10710 p2 = pop();
10711 p1 = pop();
10712 push(p1);
10713 push(p2);
10714 gcd();
10715 push(p1);
10716 divide();
10717 push(p2);
10718 divide();
10719 return inverse();
10720 };
10721
10722
10723 /*
10724 Return the leading coefficient of a polynomial.
10725
10726 Example
10727
10728 leading(5x^2+x+1,x)
10729
10730 Result
10731
10732 5
10733
10734 The result is undefined if P is not a polynomial.
10735 */
10736
10737 Eval_leading = function() {
10738 push(cadr(p1));
10739 Eval();
10740 push(caddr(p1));
10741 Eval();
10742 p1 = pop();
10743 if (p1 === symbol(NIL)) {
10744 guess();
10745 } else {
10746 push(p1);
10747 }
10748 return leading();
10749 };
10750
10751 leading = function() {
10752 save();
10753 p2 = pop();
10754 p1 = pop();
10755 push(p1);
10756 push(p2);
10757 degree();
10758 p3 = pop();
10759 push(p1);
10760 push(p2);
10761 push(p3);
10762 power();
10763 divide();
10764 push(p2);
10765 filter();
10766 return restore();
10767 };
10768
10769
10770 /*
10771 Legendre function
10772
10773 Example
10774
10775 legendre(x,3,0)
10776
10777 Result
10778
10779 5 3 3
10780 --- x - --- x
10781 2 2
10782
10783 The computation uses the following recurrence relation.
10784
10785 P(x,0) = 1
10786
10787 P(x,1) = x
10788
10789 n*P(x,n) = (2*(n-1)+1)*x*P(x,n-1) - (n-1)*P(x,n-2)
10790
10791 In the "for" loop we have i = n-1 so the recurrence relation becomes
10792
10793 (i+1)*P(x,n) = (2*i+1)*x*P(x,n-1) - i*P(x,n-2)
10794
10795 For m > 0
10796
10797 P(x,n,m) = (-1)^m * (1-x^2)^(m/2) * d^m/dx^m P(x,n)
10798 */
10799
10800 Eval_legendre = function() {
10801 push(cadr(p1));
10802 Eval();
10803 push(caddr(p1));
10804 Eval();
10805 push(cadddr(p1));
10806 Eval();
10807 p2 = pop();
10808 if (p2 === symbol(NIL)) {
10809 push_integer(0);
10810 } else {
10811 push(p2);
10812 }
10813 return legendre();
10814 };
10815
10816 legendre = function() {
10817 save();
10818 __legendre();
10819 return restore();
10820 };
10821
10822 __legendre = function() {
10823 var m, n;
10824 m = 0;
10825 n = 0;
10826 p3 = pop();
10827 p2 = pop();
10828 p1 = pop();
10829 push(p2);
10830 n = pop_integer();
10831 push(p3);
10832 m = pop_integer();
10833 if (n < 0 || n === 0x80000000 || m < 0 || m === 0x80000000) {
10834 push_symbol(LEGENDRE);
10835 push(p1);
10836 push(p2);
10837 push(p3);
10838 list(4);
10839 return;
10840 }
10841 if (issymbol(p1)) {
10842 __legendre2(n, m);
10843 } else {
10844 p4 = p1;
10845 p1 = symbol(SECRETX);
10846 __legendre2(n, m);
10847 p1 = p4;
10848 push(symbol(SECRETX));
10849 push(p1);
10850 subst();
10851 Eval();
10852 }
10853 return __legendre3(m);
10854 };
10855
10856 __legendre2 = function(n, m) {
10857 var ac, i, o, ref, ref1, results;
10858 i = 0;
10859 push_integer(1);
10860 push_integer(0);
10861 p6 = pop();
10862 for (i = o = 0, ref = n; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
10863 p5 = p6;
10864 p6 = pop();
10865 push_integer(2 * i + 1);
10866 push(p1);
10867 multiply();
10868 push(p6);
10869 multiply();
10870 push_integer(i);
10871 push(p5);
10872 multiply();
10873 subtract();
10874 push_integer(i + 1);
10875 divide();
10876 }
10877 results = [];
10878 for (i = ac = 0, ref1 = m; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
10879 push(p1);
10880 results.push(derivative());
10881 }
10882 return results;
10883 };
10884
10885 __legendre3 = function(m) {
10886 if (m === 0) {
10887 return;
10888 }
10889 if (car(p1) === symbol(COS)) {
10890 push(cadr(p1));
10891 sine();
10892 square();
10893 } else if (car(p1) === symbol(SIN)) {
10894 push(cadr(p1));
10895 cosine();
10896 square();
10897 } else {
10898 push_integer(1);
10899 push(p1);
10900 square();
10901 subtract();
10902 }
10903 push_integer(m);
10904 push_rational(1, 2);
10905 multiply();
10906 power();
10907 multiply();
10908 if (m % 2) {
10909 return negate();
10910 }
10911 };
10912
10913 list = function(n) {
10914 var listIterator, o, ref, results;
10915 listIterator = 0;
10916 push(symbol(NIL));
10917 results = [];
10918 for (listIterator = o = 0, ref = n; 0 <= ref ? o < ref : o > ref; listIterator = 0 <= ref ? ++o : --o) {
10919 results.push(cons());
10920 }
10921 return results;
10922 };
10923
10924 Eval_log = function() {
10925 push(cadr(p1));
10926 Eval();
10927 return logarithm();
10928 };
10929
10930 logarithm = function() {
10931 save();
10932 yylog();
10933 return restore();
10934 };
10935
10936 yylog = function() {
10937 var d;
10938 d = 0.0;
10939 p1 = pop();
10940 if (p1 === symbol(E)) {
10941 push_integer(1);
10942 return;
10943 }
10944 if (equaln(p1, 1)) {
10945 push_integer(0);
10946 return;
10947 }
10948 if (isnegativenumber(p1)) {
10949 push(p1);
10950 negate();
10951 logarithm();
10952 push(imaginaryunit);
10953 push_symbol(PI);
10954 multiply();
10955 add();
10956 return;
10957 }
10958 if (isdouble(p1)) {
10959 d = Math.log(p1.d);
10960 push_double(d);
10961 return;
10962 }
10963 if (isfraction(p1)) {
10964 push(p1);
10965 numerator();
10966 logarithm();
10967 push(p1);
10968 denominator();
10969 logarithm();
10970 subtract();
10971 return;
10972 }
10973 if (car(p1) === symbol(POWER)) {
10974 push(caddr(p1));
10975 push(cadr(p1));
10976 logarithm();
10977 multiply();
10978 return;
10979 }
10980 if (car(p1) === symbol(MULTIPLY)) {
10981 push_integer(0);
10982 p1 = cdr(p1);
10983 while (iscons(p1)) {
10984 push(car(p1));
10985 logarithm();
10986 add();
10987 p1 = cdr(p1);
10988 }
10989 return;
10990 }
10991 push_symbol(LOG);
10992 push(p1);
10993 return list(2);
10994 };
10995
10996 madd = function(a, b) {
10997 return a.add(b);
10998 };
10999
11000 msub = function(a, b) {
11001 return a.subtract(b);
11002 };
11003
11004 addf = function(a, b) {
11005 return a.add(b);
11006 };
11007
11008 subf = function(a, b) {
11009 return a.subtract(b);
11010 };
11011
11012 ucmp = function(a, b) {
11013 return a.compareAbs(b);
11014 };
11015
11016
11017 /*
11018 Magnitude of complex z
11019
11020 z mag(z)
11021 - ------
11022
11023 a a
11024
11025 -a a
11026
11027 (-1)^a 1
11028
11029 exp(a + i b) exp(a)
11030
11031 a b mag(a) mag(b)
11032
11033 a + i b sqrt(a^2 + b^2)
11034
11035 Notes
11036
11037 1. Handles mixed polar and rectangular forms, e.g. 1 + exp(i pi/3)
11038
11039 2. jean-francois.debroux reports that when z=(a+i*b)/(c+i*d) then
11040
11041 mag(numerator(z)) / mag(denominator(z))
11042
11043 must be used to get the correct answer. Now the operation is
11044 automatic.
11045 */
11046
11047 Eval_mag = function() {
11048 push(cadr(p1));
11049 Eval();
11050 return mag();
11051 };
11052
11053 mag = function() {
11054 save();
11055 p1 = pop();
11056 push(p1);
11057 numerator();
11058 yymag();
11059 push(p1);
11060 denominator();
11061 yymag();
11062 divide();
11063 return restore();
11064 };
11065
11066 yymag = function() {
11067 save();
11068 p1 = pop();
11069 if (isnegativenumber(p1)) {
11070 push(p1);
11071 negate();
11072 } else if (car(p1) === symbol(POWER) && equaln(cadr(p1), -1)) {
11073 push_integer(1);
11074 } else if (car(p1) === symbol(POWER) && cadr(p1) === symbol(E)) {
11075 push(caddr(p1));
11076 real();
11077 exponential();
11078 } else if (car(p1) === symbol(MULTIPLY)) {
11079 push_integer(1);
11080 p1 = cdr(p1);
11081 while (iscons(p1)) {
11082 push(car(p1));
11083 mag();
11084 multiply();
11085 p1 = cdr(p1);
11086 }
11087 } else if (car(p1) === symbol(ADD)) {
11088 push(p1);
11089 rect();
11090 p1 = pop();
11091 push(p1);
11092 real();
11093 push_integer(2);
11094 power();
11095 push(p1);
11096 imag();
11097 push_integer(2);
11098 power();
11099 add();
11100 push_rational(1, 2);
11101 power();
11102 simplify_trig();
11103 } else {
11104 push(p1);
11105 }
11106 return restore();
11107 };
11108
11109 mgcd = function(u, v) {
11110 return bigInt.gcd(u, v);
11111 };
11112
11113 new_string = function(s) {
11114 save();
11115 p1 = new U();
11116 p1.k = STR;
11117 p1.str = s;
11118 push(p1);
11119 return restore();
11120 };
11121
11122 out_of_memory = function() {
11123 return stop("out of memory");
11124 };
11125
11126 push_zero_matrix = function(i, j) {
11127 push(alloc_tensor(i * j));
11128 stack[tos - 1].tensor.ndim = 2;
11129 stack[tos - 1].tensor.dim[0] = i;
11130 return stack[tos - 1].tensor.dim[1] = j;
11131 };
11132
11133 push_identity_matrix = function(n) {
11134 var i, o, ref;
11135 push_zero_matrix(n, n);
11136 i = 0;
11137 for (i = o = 0, ref = n; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
11138 stack[tos - 1].tensor.elem[i * n + i] = one;
11139 }
11140 if (stack[tos - 1].tensor.nelem !== stack[tos - 1].tensor.elem.length) {
11141 console.log("something wrong in tensor dimensions");
11142 debugger;
11143 }
11144 };
11145
11146 push_cars = function(p) {
11147 var results;
11148 results = [];
11149 while (iscons(p)) {
11150 push(car(p));
11151 results.push(p = cdr(p));
11152 }
11153 return results;
11154 };
11155
11156 peek = function() {
11157 save();
11158 p1 = pop();
11159 push(p1);
11160 printline(p1);
11161 return restore();
11162 };
11163
11164 peek2 = function() {
11165 print_lisp(stack[tos - 2]);
11166 return print_lisp(stack[tos - 1]);
11167 };
11168
11169 equal = function(p1, p2) {
11170 if (cmp_expr(p1, p2) === 0) {
11171 return 1;
11172 } else {
11173 return 0;
11174 }
11175 };
11176
11177 lessp = function(p1, p2) {
11178 if (cmp_expr(p1, p2) < 0) {
11179 return 1;
11180 } else {
11181 return 0;
11182 }
11183 };
11184
11185 sign = function(n) {
11186 if (n < 0) {
11187 return -1;
11188 } else if (n > 0) {
11189 return 1;
11190 } else {
11191 return 0;
11192 }
11193 };
11194
11195 cmp_expr = function(p1, p2) {
11196 var n;
11197 n = 0;
11198 if (p1 === p2) {
11199 return 0;
11200 }
11201 if (p1 === symbol(NIL)) {
11202 return -1;
11203 }
11204 if (p2 === symbol(NIL)) {
11205 return 1;
11206 }
11207 if (isnum(p1) && isnum(p2)) {
11208 return sign(compare_numbers(p1, p2));
11209 }
11210 if (isnum(p1)) {
11211 return -1;
11212 }
11213 if (isnum(p2)) {
11214 return 1;
11215 }
11216 if (isstr(p1) && isstr(p2)) {
11217 return sign(strcmp(p1.str, p2.str));
11218 }
11219 if (isstr(p1)) {
11220 return -1;
11221 }
11222 if (isstr(p2)) {
11223 return 1;
11224 }
11225 if (issymbol(p1) && issymbol(p2)) {
11226 return sign(strcmp(get_printname(p1), get_printname(p2)));
11227 }
11228 if (issymbol(p1)) {
11229 return -1;
11230 }
11231 if (issymbol(p2)) {
11232 return 1;
11233 }
11234 if (istensor(p1) && istensor(p2)) {
11235 return compare_tensors(p1, p2);
11236 }
11237 if (istensor(p1)) {
11238 return -1;
11239 }
11240 if (istensor(p2)) {
11241 return 1;
11242 }
11243 while (iscons(p1) && iscons(p2)) {
11244 n = cmp_expr(car(p1), car(p2));
11245 if (n !== 0) {
11246 return n;
11247 }
11248 p1 = cdr(p1);
11249 p2 = cdr(p2);
11250 }
11251 if (iscons(p2)) {
11252 return -1;
11253 }
11254 if (iscons(p1)) {
11255 return 1;
11256 }
11257 return 0;
11258 };
11259
11260 length = function(p) {
11261 var n;
11262 n = 0;
11263 while (iscons(p)) {
11264 p = cdr(p);
11265 n++;
11266 }
11267 return n;
11268 };
11269
11270 unique = function(p) {
11271 save();
11272 p1 = symbol(NIL);
11273 p2 = symbol(NIL);
11274 unique_f(p);
11275 if (p2 !== symbol(NIL)) {
11276 p1 = symbol(NIL);
11277 }
11278 p = p1;
11279 restore();
11280 return p;
11281 };
11282
11283 unique_f = function(p) {
11284 if (isstr(p)) {
11285 if (p1 === symbol(NIL)) {
11286 p1 = p;
11287 } else if (p !== p1) {
11288 p2 = p;
11289 }
11290 return;
11291 }
11292 while (iscons(p)) {
11293 unique_f(car(p));
11294 if (p2 !== symbol(NIL)) {
11295 return;
11296 }
11297 p = cdr(p);
11298 }
11299 };
11300
11301 ssqrt = function() {
11302 push_rational(1, 2);
11303 return power();
11304 };
11305
11306 yyexpand = function() {
11307 var x;
11308 x = expanding;
11309 expanding = 1;
11310 Eval();
11311 return expanding = x;
11312 };
11313
11314 exponential = function() {
11315 push_symbol(E);
11316 swap();
11317 return power();
11318 };
11319
11320 square = function() {
11321 push_integer(2);
11322 return power();
11323 };
11324
11325 sort_stack = function(n) {
11326 var h, subsetOfStack;
11327 h = tos - n;
11328 subsetOfStack = stack.slice(h, h + n);
11329 subsetOfStack.sort(cmp_expr);
11330 return stack = stack.slice(0, h).concat(subsetOfStack).concat(stack.slice(h + n));
11331 };
11332
11333 $.equal = equal;
11334
11335 $.length = length;
11336
11337 mmul = function(a, b) {
11338 return a.multiply(b);
11339 };
11340
11341 mdiv = function(a, b) {
11342 return a.divide(b);
11343 };
11344
11345
11346 /*
11347 static void
11348 addf(unsigned int *a, unsigned int *b, int len)
11349 {
11350 int i
11351 long long t = 0; # can be signed or unsigned
11352 for (i = 0; i < len; i++) {
11353 t += (long long) a[i] + b[i]
11354 a[i] = (unsigned int) t
11355 t >>= 32
11356 }
11357 }
11358
11359 // a = a - b
11360
11361 static void
11362 subf(unsigned int *a, unsigned int *b, int len)
11363 {
11364 int i
11365 long long t = 0; # must be signed
11366 for (i = 0; i < len; i++) {
11367 t += (long long) a[i] - b[i]
11368 a[i] = (unsigned int) t
11369 t >>= 32
11370 }
11371 }
11372
11373 // a = b * c
11374
11375 // 0xffffffff + 0xffffffff * 0xffffffff == 0xffffffff00000000
11376
11377 static void
11378 mulf(unsigned int *a, unsigned int *b, int len, unsigned int c)
11379 {
11380 int i
11381 unsigned long long t = 0; # must be unsigned
11382 for (i = 0; i < len; i++) {
11383 t += (unsigned long long) b[i] * c
11384 a[i] = (unsigned int) t
11385 t >>= 32
11386 }
11387 a[i] = (unsigned int) t
11388 }
11389 */
11390
11391 mmod = function(a, b) {
11392 return a.mod(b);
11393 };
11394
11395 mdivrem = function(a, b) {
11396 var toReturn;
11397 toReturn = a.divmod(b);
11398 return [toReturn.quotient, toReturn.remainder];
11399 };
11400
11401 Eval_mod = function() {
11402 push(cadr(p1));
11403 Eval();
11404 push(caddr(p1));
11405 Eval();
11406 return mod();
11407 };
11408
11409 mod = function() {
11410 var n;
11411 n = 0;
11412 save();
11413 p2 = pop();
11414 p1 = pop();
11415 if (iszero(p2)) {
11416 stop("mod function: divide by zero");
11417 }
11418 if (!isnum(p1) || !isnum(p2)) {
11419 push_symbol(MOD);
11420 push(p1);
11421 push(p2);
11422 list(3);
11423 restore();
11424 return;
11425 }
11426 if (isdouble(p1)) {
11427 push(p1);
11428 n = pop_integer();
11429 if (n === 0x80000000) {
11430 stop("mod function: cannot convert float value to integer");
11431 }
11432 push_integer(n);
11433 p1 = pop();
11434 }
11435 if (isdouble(p2)) {
11436 push(p2);
11437 n = pop_integer();
11438 if (n === 0x80000000) {
11439 stop("mod function: cannot convert float value to integer");
11440 }
11441 push_integer(n);
11442 p2 = pop();
11443 }
11444 if (!isinteger(p1) || !isinteger(p2)) {
11445 stop("mod function: integer arguments expected");
11446 }
11447 p3 = new U();
11448 p3.k = NUM;
11449 p3.q.a = mmod(p1.q.a, p2.q.a);
11450 p3.q.b = mint(1);
11451 push(p3);
11452 return restore();
11453 };
11454
11455 mpow = function(a, n) {
11456 return a.pow(n);
11457 };
11458
11459 mprime = function(n) {
11460 return n.isProbablePrime();
11461 };
11462
11463 mroot = function(n, index) {
11464 var i, j, k, o, ref, x, y;
11465 n = n.abs();
11466 i = 0;
11467 j = 0;
11468 k = 0;
11469 if (index === 0) {
11470 stop("root index is zero");
11471 }
11472 k = 0;
11473 while (n.shiftRight(k) > 0) {
11474 k++;
11475 }
11476 if (k === 0) {
11477 return mint(0);
11478 }
11479 k = Math.floor((k - 1) / index);
11480 j = Math.floor(k / 32 + 1);
11481 x = bigInt(j);
11482 for (i = o = 0, ref = j; 0 <= ref ? o < ref : o > ref; i = 0 <= ref ? ++o : --o) {
11483 x = x.and(bigInt(1).shiftLeft(i).not());
11484 }
11485 while (k >= 0) {
11486 x = x.or(bigInt(1).shiftLeft(k));
11487 y = mpow(x, index);
11488 switch (mcmp(y, n)) {
11489 case 0:
11490 return x;
11491 case 1:
11492 x = x.and(bigInt(1).shiftLeft(k).not());
11493 }
11494 k--;
11495 }
11496 return 0;
11497 };
11498
11499 multiply = function() {
11500 if (esc_flag) {
11501 stop("escape key stop");
11502 }
11503 if (isnum(stack[tos - 2]) && isnum(stack[tos - 1])) {
11504 return multiply_numbers();
11505 } else {
11506 save();
11507 yymultiply();
11508 return restore();
11509 }
11510 };
11511
11512 yymultiply = function() {
11513 var h, i, n, o, ref, ref1;
11514 h = 0;
11515 i = 0;
11516 n = 0;
11517 p2 = pop();
11518 p1 = pop();
11519 h = tos;
11520 if (iszero(p1) || iszero(p2)) {
11521 push(zero);
11522 return;
11523 }
11524 if (expanding && isadd(p1)) {
11525 p1 = cdr(p1);
11526 push(zero);
11527 while (iscons(p1)) {
11528 push(car(p1));
11529 push(p2);
11530 multiply();
11531 add();
11532 p1 = cdr(p1);
11533 }
11534 return;
11535 }
11536 if (expanding && isadd(p2)) {
11537 p2 = cdr(p2);
11538 push(zero);
11539 while (iscons(p2)) {
11540 push(p1);
11541 push(car(p2));
11542 multiply();
11543 add();
11544 p2 = cdr(p2);
11545 }
11546 return;
11547 }
11548 if (!istensor(p1) && istensor(p2)) {
11549 push(p1);
11550 push(p2);
11551 scalar_times_tensor();
11552 return;
11553 }
11554 if (istensor(p1) && !istensor(p2)) {
11555 push(p1);
11556 push(p2);
11557 tensor_times_scalar();
11558 return;
11559 }
11560 if (car(p1) === symbol(MULTIPLY)) {
11561 p1 = cdr(p1);
11562 } else {
11563 push(p1);
11564 list(1);
11565 p1 = pop();
11566 }
11567 if (car(p2) === symbol(MULTIPLY)) {
11568 p2 = cdr(p2);
11569 } else {
11570 push(p2);
11571 list(1);
11572 p2 = pop();
11573 }
11574 if (isnum(car(p1)) && isnum(car(p2))) {
11575 push(car(p1));
11576 push(car(p2));
11577 multiply_numbers();
11578 p1 = cdr(p1);
11579 p2 = cdr(p2);
11580 } else if (isnum(car(p1))) {
11581 push(car(p1));
11582 p1 = cdr(p1);
11583 } else if (isnum(car(p2))) {
11584 push(car(p2));
11585 p2 = cdr(p2);
11586 } else {
11587 push(one);
11588 }
11589 parse_p1();
11590 parse_p2();
11591 while (iscons(p1) && iscons(p2)) {
11592 if (caar(p1) === symbol(OPERATOR) && caar(p2) === symbol(OPERATOR)) {
11593 push_symbol(OPERATOR);
11594 push(cdar(p1));
11595 push(cdar(p2));
11596 append();
11597 cons();
11598 p1 = cdr(p1);
11599 p2 = cdr(p2);
11600 parse_p1();
11601 parse_p2();
11602 continue;
11603 }
11604 switch (cmp_expr(p3, p4)) {
11605 case -1:
11606 push(car(p1));
11607 p1 = cdr(p1);
11608 parse_p1();
11609 break;
11610 case 1:
11611 push(car(p2));
11612 p2 = cdr(p2);
11613 parse_p2();
11614 break;
11615 case 0:
11616 combine_factors(h);
11617 p1 = cdr(p1);
11618 p2 = cdr(p2);
11619 parse_p1();
11620 parse_p2();
11621 break;
11622 default:
11623 stop("internal error 2");
11624 }
11625 }
11626 while (iscons(p1)) {
11627 push(car(p1));
11628 p1 = cdr(p1);
11629 }
11630 while (iscons(p2)) {
11631 push(car(p2));
11632 p2 = cdr(p2);
11633 }
11634 __normalize_radical_factors(h);
11635 if (expanding) {
11636 for (i = o = ref = h, ref1 = tos; ref <= ref1 ? o < ref1 : o > ref1; i = ref <= ref1 ? ++o : --o) {
11637 if (isadd(stack[i])) {
11638 multiply_all(tos - h);
11639 return;
11640 }
11641 }
11642 }
11643 n = tos - h;
11644 if (n === 1) {
11645 return;
11646 }
11647 if (isrational(stack[h]) && equaln(stack[h], 1)) {
11648 if (n === 2) {
11649 p7 = pop();
11650 pop();
11651 push(p7);
11652 } else {
11653 stack[h] = symbol(MULTIPLY);
11654 list(n);
11655 }
11656 return;
11657 }
11658 list(n);
11659 p7 = pop();
11660 push_symbol(MULTIPLY);
11661 push(p7);
11662 return cons();
11663 };
11664
11665 parse_p1 = function() {
11666 p3 = car(p1);
11667 p5 = one;
11668 if (car(p3) === symbol(POWER)) {
11669 p5 = caddr(p3);
11670 return p3 = cadr(p3);
11671 }
11672 };
11673
11674 parse_p2 = function() {
11675 p4 = car(p2);
11676 p6 = one;
11677 if (car(p4) === symbol(POWER)) {
11678 p6 = caddr(p4);
11679 return p4 = cadr(p4);
11680 }
11681 };
11682
11683 combine_factors = function(h) {
11684 push(p4);
11685 push(p5);
11686 push(p6);
11687 add();
11688 power();
11689 p7 = pop();
11690 if (isnum(p7)) {
11691 push(stack[h]);
11692 push(p7);
11693 multiply_numbers();
11694 return stack[h] = pop();
11695 } else if (car(p7) === symbol(MULTIPLY)) {
11696 if (isnum(cadr(p7)) && cdddr(p7) === symbol(NIL)) {
11697 push(stack[h]);
11698 push(cadr(p7));
11699 multiply_numbers();
11700 stack[h] = pop();
11701 return push(caddr(p7));
11702 } else {
11703 return push(p7);
11704 }
11705 } else {
11706 return push(p7);
11707 }
11708 };
11709
11710 gp = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, -6, -7, -8, -3, -4, -5, 13, 14, 15, -16, 9, 10, 11, -12], [0, 0, 6, -1, -11, 10, -2, -15, 14, 12, -5, 4, -9, 16, -8, 7, -13], [0, 0, 7, 11, -1, -9, 15, -2, -13, 5, 12, -3, -10, 8, 16, -6, -14], [0, 0, 8, -10, 9, -1, -14, 13, -2, -4, 3, 12, -11, -7, 6, 16, -15], [0, 0, 3, 2, 15, -14, 1, 11, -10, 16, -8, 7, 13, 12, -5, 4, 9], [0, 0, 4, -15, 2, 13, -11, 1, 9, 8, 16, -6, 14, 5, 12, -3, 10], [0, 0, 5, 14, -13, 2, 10, -9, 1, -7, 6, 16, 15, -4, 3, 12, 11], [0, 0, 13, 12, -5, 4, 16, -8, 7, -1, -11, 10, -3, -2, -15, 14, -6], [0, 0, 14, 5, 12, -3, 8, 16, -6, 11, -1, -9, -4, 15, -2, -13, -7], [0, 0, 15, -4, 3, 12, -7, 6, 16, -10, 9, -1, -5, -14, 13, -2, -8], [0, 0, 16, -9, -10, -11, -13, -14, -15, -3, -4, -5, 1, -6, -7, -8, 2], [0, 0, 9, -16, 8, -7, -12, 5, -4, -2, -15, 14, 6, -1, -11, 10, 3], [0, 0, 10, -8, -16, 6, -5, -12, 3, 15, -2, -13, 7, 11, -1, -9, 4], [0, 0, 11, 7, -6, -16, 4, -3, -12, -14, 13, -2, 8, -10, 9, -1, 5], [0, 0, 12, 13, 14, 15, 9, 10, 11, -6, -7, -8, -2, -3, -4, -5, -1]];
11711
11712 combine_gammas = function(h) {
11713 var n;
11714 n = gp[Math.floor(p1.gamma)][Math.floor(p2.gamma)];
11715 if (n < 0) {
11716 n = -n;
11717 push(stack[h]);
11718 negate();
11719 stack[h] = pop();
11720 }
11721 if (n > 1) {
11722 return push(_gamma[n]);
11723 }
11724 };
11725
11726 multiply_noexpand = function() {
11727 var x;
11728 x = expanding;
11729 expanding = 0;
11730 multiply();
11731 return expanding = x;
11732 };
11733
11734 multiply_all = function(n) {
11735 var h, i, o, ref;
11736 i = 0;
11737 if (n === 1) {
11738 return;
11739 }
11740 if (n === 0) {
11741 push(one);
11742 return;
11743 }
11744 h = tos - n;
11745 push(stack[h]);
11746 for (i = o = 1, ref = n; 1 <= ref ? o < ref : o > ref; i = 1 <= ref ? ++o : --o) {
11747 push(stack[h + i]);
11748 multiply();
11749 }
11750 stack[h] = pop();
11751 return tos = h + 1;
11752 };
11753
11754 multiply_all_noexpand = function(n) {
11755 var x;
11756 x = expanding;
11757 expanding = 0;
11758 multiply_all(n);
11759 return expanding = x;
11760 };
11761
11762 divide = function() {
11763 if (isnum(stack[tos - 2]) && isnum(stack[tos - 1])) {
11764 return divide_numbers();
11765 } else {
11766 inverse();
11767 return multiply();
11768 }
11769 };
11770
11771 inverse = function() {
11772 if (isnum(stack[tos - 1])) {
11773 return invert_number();
11774 } else {
11775 push_integer(-1);
11776 return power();
11777 }
11778 };
11779
11780 reciprocate = function() {
11781 if (isnum(stack[tos - 1])) {
11782 return invert_number();
11783 } else {
11784 push_integer(-1);
11785 return power();
11786 }
11787 };
11788
11789 negate = function() {
11790 if (isnum(stack[tos - 1])) {
11791 return negate_number();
11792 } else {
11793 push_integer(-1);
11794 return multiply();
11795 }
11796 };
11797
11798 negate_expand = function() {
11799 var x;
11800 x = expanding;
11801 expanding = 1;
11802 negate();
11803 return expanding = x;
11804 };
11805
11806 negate_noexpand = function() {
11807 var x;
11808 x = expanding;
11809 expanding = 0;
11810 negate();
11811 return expanding = x;
11812 };
11813
11814 __normalize_radical_factors = function(h) {
11815 var ac, ad, i, o, ref, ref1, ref2, ref3, ref4, ref5;
11816 i = 0;
11817 if (isplusone(stack[h]) || isminusone(stack[h]) || isdouble(stack[h])) {
11818 return;
11819 }
11820 for (i = o = ref = h + 1, ref1 = tos; ref <= ref1 ? o < ref1 : o > ref1; i = ref <= ref1 ? ++o : --o) {
11821 if (__is_radical_number(stack[i])) {
11822 break;
11823 }
11824 }
11825 if (i === tos) {
11826 return;
11827 }
11828 save();
11829 push(stack[h]);
11830 mp_numerator();
11831 p1 = pop();
11832 for (i = ac = ref2 = h + 1, ref3 = tos; ref2 <= ref3 ? ac < ref3 : ac > ref3; i = ref2 <= ref3 ? ++ac : --ac) {
11833 if (isplusone(p1) || isminusone(p1)) {
11834 break;
11835 }
11836 if (!__is_radical_number(stack[i])) {
11837 continue;
11838 }
11839 p3 = cadr(stack[i]);
11840 p4 = caddr(stack[i]);
11841 if (!isnegativenumber(p4)) {
11842 continue;
11843 }
11844 push(p1);
11845 push(p3);
11846 divide();
11847 p5 = pop();
11848 if (!isinteger(p5)) {
11849 continue;
11850 }
11851 p1 = p5;
11852 push_symbol(POWER);
11853 push(p3);
11854 push(one);
11855 push(p4);
11856 add();
11857 list(3);
11858 stack[i] = pop();
11859 }
11860 push(stack[h]);
11861 mp_denominator();
11862 p2 = pop();
11863 for (i = ad = ref4 = h + 1, ref5 = tos; ref4 <= ref5 ? ad < ref5 : ad > ref5; i = ref4 <= ref5 ? ++ad : --ad) {
11864 if (isplusone(p2)) {
11865 break;
11866 }
11867 if (!__is_radical_number(stack[i])) {
11868 continue;
11869 }
11870 p3 = cadr(stack[i]);
11871 p4 = caddr(stack[i]);
11872 if (isnegativenumber(p4)) {
11873 continue;
11874 }
11875 push(p2);
11876 push(p3);
11877 divide();
11878 p5 = pop();
11879 if (!isinteger(p5)) {
11880 continue;
11881 }
11882 p2 = p5;
11883 push_symbol(POWER);
11884 push(p3);
11885 push(p4);
11886 push(one);
11887 subtract();
11888 list(3);
11889 stack[i] = pop();
11890 }
11891 push(p1);
11892 push(p2);
11893 divide();
11894 stack[h] = pop();
11895 return restore();
11896 };
11897
11898 __is_radical_number = function(p) {
11899 if (car(p) === symbol(POWER) && isnum(cadr(p)) && isnum(caddr(p)) && !isminusone(cadr(p))) {
11900 return 1;
11901 } else {
11902 return 0;
11903 }
11904 };
11905
11906 NROOTS_YMAX = 101;
11907
11908 NROOTS_DELTA = 1.0e-6;
11909
11910 NROOTS_EPSILON = 1.0e-9;
11911
11912 NROOTS_ABS = function(z) {
11913 return Math.sqrt(z.r * z.r + z.i * z.i);
11914 };
11915
11916 theRandom = 0.0;
11917
11918 NROOTS_RANDOM = function() {
11919 return 4.0 * Math.random() - 2.0;
11920 };
11921
11922 numericRootOfPolynomial = (function() {
11923 function numericRootOfPolynomial() {}
11924
11925 numericRootOfPolynomial.prototype.r = 0.0;
11926
11927 numericRootOfPolynomial.prototype.i = 0.0;
11928
11929 return numericRootOfPolynomial;
11930
11931 })();
11932
11933 nroots_a = new numericRootOfPolynomial();
11934
11935 nroots_b = new numericRootOfPolynomial();
11936
11937 nroots_x = new numericRootOfPolynomial();
11938
11939 nroots_y = new numericRootOfPolynomial();
11940
11941 nroots_fa = new numericRootOfPolynomial();
11942
11943 nroots_fb = new numericRootOfPolynomial();
11944
11945 nroots_dx = new numericRootOfPolynomial();
11946
11947 nroots_df = new numericRootOfPolynomial();
11948
11949 nroots_c = [];
11950
11951 for (initNRoots = o = 0, ref = NROOTS_YMAX; 0 <= ref ? o < ref : o > ref; initNRoots = 0 <= ref ? ++o : --o) {
11952 nroots_c[initNRoots] = new numericRootOfPolynomial();
11953 }
11954
11955 Eval_nroots = function() {
11956 var ac, ad, ae, h, i, k, n, ref1, ref2, ref3;
11957 h = 0;
11958 i = 0;
11959 k = 0;
11960 n = 0;
11961 push(cadr(p1));
11962 Eval();
11963 push(caddr(p1));
11964 Eval();
11965 p2 = pop();
11966 if (p2 === symbol(NIL)) {
11967 guess();
11968 } else {
11969 push(p2);
11970 }
11971 p2 = pop();
11972 p1 = pop();
11973 if (!ispoly(p1, p2)) {
11974 stop("nroots: polynomial?");
11975 }
11976 h = tos;
11977 push(p1);
11978 push(p2);
11979 n = coeff();
11980 if (n > NROOTS_YMAX) {
11981 stop("nroots: degree?");
11982 }
11983 for (i = ac = 0, ref1 = n; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
11984 push(stack[h + i]);
11985 real();
11986 yyfloat();
11987 Eval();
11988 p1 = pop();
11989 push(stack[h + i]);
11990 imag();
11991 yyfloat();
11992 Eval();
11993 p2 = pop();
11994 if (!isdouble(p1) || !isdouble(p2)) {
11995 stop("nroots: coefficients?");
11996 }
11997 nroots_c[i].r = p1.d;
11998 nroots_c[i].i = p2.d;
11999 }
12000 tos = h;
12001 monic(n);
12002 for (k = ad = ref2 = n; ad > 1; k = ad += -1) {
12003 findroot(k);
12004 if (Math.abs(nroots_a.r) < NROOTS_DELTA) {
12005 nroots_a.r = 0.0;
12006 }
12007 if (Math.abs(nroots_a.i) < NROOTS_DELTA) {
12008 nroots_a.i = 0.0;
12009 }
12010 push_double(nroots_a.r);
12011 push_double(nroots_a.i);
12012 push(imaginaryunit);
12013 multiply();
12014 add();
12015 NROOTS_divpoly(k);
12016 }
12017 n = tos - h;
12018 if (n > 1) {
12019 sort_stack(n);
12020 p1 = alloc_tensor(n);
12021 p1.tensor.ndim = 1;
12022 p1.tensor.dim[0] = n;
12023 for (i = ae = 0, ref3 = n; 0 <= ref3 ? ae < ref3 : ae > ref3; i = 0 <= ref3 ? ++ae : --ae) {
12024 p1.tensor.elem[i] = stack[h + i];
12025 }
12026 tos = h;
12027 return push(p1);
12028 }
12029 };
12030
12031 monic = function(n) {
12032 var ac, k, ref1, t;
12033 k = 0;
12034 t = 0.0;
12035 nroots_y.r = nroots_c[n - 1].r;
12036 nroots_y.i = nroots_c[n - 1].i;
12037 t = nroots_y.r * nroots_y.r + nroots_y.i * nroots_y.i;
12038 for (k = ac = 0, ref1 = n - 1; 0 <= ref1 ? ac < ref1 : ac > ref1; k = 0 <= ref1 ? ++ac : --ac) {
12039 nroots_c[k].r = (nroots_c[k].r * nroots_y.r + nroots_c[k].i * nroots_y.i) / t;
12040 nroots_c[k].i = (nroots_c[k].i * nroots_y.r - nroots_c[k].r * nroots_y.i) / t;
12041 }
12042 nroots_c[n - 1].r = 1.0;
12043 return nroots_c[n - 1].i = 0.0;
12044 };
12045
12046 findroot = function(n) {
12047 var ac, ad, j, k, nrabs, t;
12048 j = 0;
12049 k = 0;
12050 t = 0.0;
12051 if (NROOTS_ABS(nroots_c[0]) < NROOTS_DELTA) {
12052 nroots_a.r = 0.0;
12053 nroots_a.i = 0.0;
12054 return;
12055 }
12056 for (j = ac = 0; ac < 100; j = ++ac) {
12057 nroots_a.r = NROOTS_RANDOM();
12058 nroots_a.i = NROOTS_RANDOM();
12059 compute_fa(n);
12060 nroots_b.r = nroots_a.r;
12061 nroots_b.i = nroots_a.i;
12062 nroots_fb.r = nroots_fa.r;
12063 nroots_fb.i = nroots_fa.i;
12064 nroots_a.r = NROOTS_RANDOM();
12065 nroots_a.i = NROOTS_RANDOM();
12066 for (k = ad = 0; ad < 1000; k = ++ad) {
12067 compute_fa(n);
12068 nrabs = NROOTS_ABS(nroots_fa);
12069 if (DEBUG) {
12070 console.log("nrabs: " + nrabs);
12071 }
12072 if (nrabs < NROOTS_EPSILON) {
12073 return;
12074 }
12075 if (NROOTS_ABS(nroots_fa) < NROOTS_ABS(nroots_fb)) {
12076 nroots_x.r = nroots_a.r;
12077 nroots_x.i = nroots_a.i;
12078 nroots_a.r = nroots_b.r;
12079 nroots_a.i = nroots_b.i;
12080 nroots_b.r = nroots_x.r;
12081 nroots_b.i = nroots_x.i;
12082 nroots_x.r = nroots_fa.r;
12083 nroots_x.i = nroots_fa.i;
12084 nroots_fa.r = nroots_fb.r;
12085 nroots_fa.i = nroots_fb.i;
12086 nroots_fb.r = nroots_x.r;
12087 nroots_fb.i = nroots_x.i;
12088 }
12089 nroots_dx.r = nroots_b.r - nroots_a.r;
12090 nroots_dx.i = nroots_b.i - nroots_a.i;
12091 nroots_df.r = nroots_fb.r - nroots_fa.r;
12092 nroots_df.i = nroots_fb.i - nroots_fa.i;
12093 t = nroots_df.r * nroots_df.r + nroots_df.i * nroots_df.i;
12094 if (t === 0.0) {
12095 break;
12096 }
12097 nroots_y.r = (nroots_dx.r * nroots_df.r + nroots_dx.i * nroots_df.i) / t;
12098 nroots_y.i = (nroots_dx.i * nroots_df.r - nroots_dx.r * nroots_df.i) / t;
12099 nroots_a.r = nroots_b.r - (nroots_y.r * nroots_fb.r - nroots_y.i * nroots_fb.i);
12100 nroots_a.i = nroots_b.i - (nroots_y.r * nroots_fb.i + nroots_y.i * nroots_fb.r);
12101 }
12102 }
12103 return stop("nroots: convergence error");
12104 };
12105
12106 compute_fa = function(n) {
12107 var ac, k, ref1, results, t;
12108 k = 0;
12109 t = 0.0;
12110 nroots_x.r = nroots_a.r;
12111 nroots_x.i = nroots_a.i;
12112 nroots_fa.r = nroots_c[0].r + nroots_c[1].r * nroots_x.r - nroots_c[1].i * nroots_x.i;
12113 nroots_fa.i = nroots_c[0].i + nroots_c[1].r * nroots_x.i + nroots_c[1].i * nroots_x.r;
12114 results = [];
12115 for (k = ac = 2, ref1 = n; 2 <= ref1 ? ac < ref1 : ac > ref1; k = 2 <= ref1 ? ++ac : --ac) {
12116 t = nroots_a.r * nroots_x.r - nroots_a.i * nroots_x.i;
12117 nroots_x.i = nroots_a.r * nroots_x.i + nroots_a.i * nroots_x.r;
12118 nroots_x.r = t;
12119 nroots_fa.r += nroots_c[k].r * nroots_x.r - nroots_c[k].i * nroots_x.i;
12120 results.push(nroots_fa.i += nroots_c[k].r * nroots_x.i + nroots_c[k].i * nroots_x.r);
12121 }
12122 return results;
12123 };
12124
12125 NROOTS_divpoly = function(n) {
12126 var ac, ad, k, ref1, ref2, results;
12127 k = 0;
12128 for (k = ac = ref1 = n - 1; ref1 <= 0 ? ac < 0 : ac > 0; k = ref1 <= 0 ? ++ac : --ac) {
12129 nroots_c[k - 1].r += nroots_c[k].r * nroots_a.r - nroots_c[k].i * nroots_a.i;
12130 nroots_c[k - 1].i += nroots_c[k].i * nroots_a.r + nroots_c[k].r * nroots_a.i;
12131 }
12132 if (NROOTS_ABS(nroots_c[0]) > NROOTS_DELTA) {
12133 stop("nroots: residual error");
12134 }
12135 results = [];
12136 for (k = ad = 0, ref2 = n - 1; 0 <= ref2 ? ad < ref2 : ad > ref2; k = 0 <= ref2 ? ++ad : --ad) {
12137 nroots_c[k].r = nroots_c[k + 1].r;
12138 results.push(nroots_c[k].i = nroots_c[k + 1].i);
12139 }
12140 return results;
12141 };
12142
12143 Eval_numerator = function() {
12144 push(cadr(p1));
12145 Eval();
12146 return numerator();
12147 };
12148
12149 numerator = function() {
12150 var h;
12151 h = 0;
12152 save();
12153 p1 = pop();
12154 if (car(p1) === symbol(ADD)) {
12155 push(p1);
12156 rationalize();
12157 p1 = pop();
12158 }
12159 if (car(p1) === symbol(MULTIPLY)) {
12160 h = tos;
12161 p1 = cdr(p1);
12162 while (iscons(p1)) {
12163 push(car(p1));
12164 numerator();
12165 p1 = cdr(p1);
12166 }
12167 multiply_all(tos - h);
12168 } else if (isrational(p1)) {
12169 push(p1);
12170 mp_numerator();
12171 } else if (car(p1) === symbol(POWER) && isnegativeterm(caddr(p1))) {
12172 push(one);
12173 } else {
12174 push(p1);
12175 }
12176 return restore();
12177 };
12178
12179 Eval_outer = function() {
12180 var results;
12181 p1 = cdr(p1);
12182 push(car(p1));
12183 Eval();
12184 p1 = cdr(p1);
12185 results = [];
12186 while (iscons(p1)) {
12187 push(car(p1));
12188 Eval();
12189 outer();
12190 results.push(p1 = cdr(p1));
12191 }
12192 return results;
12193 };
12194
12195 outer = function() {
12196 save();
12197 p2 = pop();
12198 p1 = pop();
12199 if (istensor(p1) && istensor(p2)) {
12200 yyouter();
12201 } else {
12202 push(p1);
12203 push(p2);
12204 if (istensor(p1)) {
12205 tensor_times_scalar();
12206 } else if (istensor(p2)) {
12207 scalar_times_tensor();
12208 } else {
12209 multiply();
12210 }
12211 }
12212 return restore();
12213 };
12214
12215 yyouter = function() {
12216 var ac, ad, ae, af, i, j, k, ndim, nelem, ref1, ref2, ref3, ref4;
12217 i = 0;
12218 j = 0;
12219 k = 0;
12220 ndim = 0;
12221 nelem = 0;
12222 ndim = p1.tensor.ndim + p2.tensor.ndim;
12223 if (ndim > MAXDIM) {
12224 stop("outer: rank of result exceeds maximum");
12225 }
12226 nelem = p1.tensor.nelem * p2.tensor.nelem;
12227 p3 = alloc_tensor(nelem);
12228 p3.tensor.ndim = ndim;
12229 for (i = ac = 0, ref1 = p1.tensor.ndim; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
12230 p3.tensor.dim[i] = p1.tensor.dim[i];
12231 }
12232 j = i;
12233 for (i = ad = 0, ref2 = p2.tensor.ndim; 0 <= ref2 ? ad < ref2 : ad > ref2; i = 0 <= ref2 ? ++ad : --ad) {
12234 p3.tensor.dim[j + i] = p2.tensor.dim[i];
12235 }
12236 k = 0;
12237 for (i = ae = 0, ref3 = p1.tensor.nelem; 0 <= ref3 ? ae < ref3 : ae > ref3; i = 0 <= ref3 ? ++ae : --ae) {
12238 for (j = af = 0, ref4 = p2.tensor.nelem; 0 <= ref4 ? af < ref4 : af > ref4; j = 0 <= ref4 ? ++af : --af) {
12239 push(p1.tensor.elem[i]);
12240 push(p2.tensor.elem[j]);
12241 multiply();
12242 p3.tensor.elem[k++] = pop();
12243 }
12244 }
12245 return push(p3);
12246 };
12247
12248
12249 /*
12250 Partition a term
12251
12252 Input stack:
12253
12254 term (factor or product of factors)
12255
12256 free variable
12257
12258 Output stack:
12259
12260 constant expression
12261
12262 variable expression
12263 */
12264
12265 partition = function() {
12266 save();
12267 p2 = pop();
12268 p1 = pop();
12269 push_integer(1);
12270 p3 = pop();
12271 p4 = p3;
12272 p1 = cdr(p1);
12273 while (iscons(p1)) {
12274 if (Find(car(p1), p2)) {
12275 push(p4);
12276 push(car(p1));
12277 multiply();
12278 p4 = pop();
12279 } else {
12280 push(p3);
12281 push(car(p1));
12282 multiply();
12283 p3 = pop();
12284 }
12285 p1 = cdr(p1);
12286 }
12287 push(p3);
12288 push(p4);
12289 return restore();
12290 };
12291
12292
12293 /*
12294 Convert complex z to polar form
12295
12296 Input: push z
12297
12298 Output: Result on stack
12299
12300 polar(z) = mag(z) * exp(i * arg(z))
12301 */
12302
12303 Eval_polar = function() {
12304 push(cadr(p1));
12305 Eval();
12306 return polar();
12307 };
12308
12309 polar = function() {
12310 save();
12311 p1 = pop();
12312 push(p1);
12313 mag();
12314 push(imaginaryunit);
12315 push(p1);
12316 arg();
12317 multiply();
12318 exponential();
12319 multiply();
12320 return restore();
12321 };
12322
12323 n_factor_number = 0;
12324
12325 factor_number = function() {
12326 var h;
12327 h = 0;
12328 save();
12329 p1 = pop();
12330 if (equaln(p1, 0) || equaln(p1, 1) || equaln(p1, -1)) {
12331 push(p1);
12332 restore();
12333 return;
12334 }
12335 n_factor_number = p1.q.a;
12336 h = tos;
12337 factor_a();
12338 if (tos - h > 1) {
12339 list(tos - h);
12340 push_symbol(MULTIPLY);
12341 swap();
12342 cons();
12343 }
12344 return restore();
12345 };
12346
12347 factor_a = function() {
12348 var ac, k;
12349 k = 0;
12350 if (n_factor_number.isNegative()) {
12351 n_factor_number = setSignTo(n_factor_number, 1);
12352 push_integer(-1);
12353 }
12354 for (k = ac = 0; ac < 10000; k = ++ac) {
12355 try_kth_prime(k);
12356 if (n_factor_number.compare(1) === 0) {
12357 return;
12358 }
12359 }
12360 return factor_b();
12361 };
12362
12363 try_kth_prime = function(k) {
12364 var count, d, q, r, ref1;
12365 count = 0;
12366 d = mint(primetab[k]);
12367 count = 0;
12368 while (1.) {
12369 if (n_factor_number.compare(1) === 0) {
12370 if (count) {
12371 push_factor(d, count);
12372 }
12373 return;
12374 }
12375 ref1 = mdivrem(n_factor_number, d), q = ref1[0], r = ref1[1];
12376 if (r.isZero()) {
12377 count++;
12378 n_factor_number = q;
12379 } else {
12380 break;
12381 }
12382 }
12383 if (count) {
12384 push_factor(d, count);
12385 }
12386 if (mcmp(q, d) === -1) {
12387 push_factor(n_factor_number, 1);
12388 return n_factor_number = mint(1);
12389 }
12390 };
12391
12392 factor_b = function() {
12393 var bigint_one, g, k, l, t, x, xprime;
12394 k = 0;
12395 l = 0;
12396 bigint_one = mint(1);
12397 x = mint(5);
12398 xprime = mint(2);
12399 k = 1;
12400 l = 1;
12401 while (1.) {
12402 if (mprime(n_factor_number)) {
12403 push_factor(n_factor_number, 1);
12404 return 0;
12405 }
12406 while (1.) {
12407 if (esc_flag) {
12408 stop("esc");
12409 }
12410 t = msub(xprime, x);
12411 t = setSignTo(t, 1);
12412 g = mgcd(t, n_factor_number);
12413 if (MEQUAL(g, 1)) {
12414 if (--k === 0) {
12415 xprime = x;
12416 l *= 2;
12417 k = l;
12418 }
12419 t = mmul(x, x);
12420 x = madd(t, bigint_one);
12421 t = mmod(x, n_factor_number);
12422 x = t;
12423 continue;
12424 }
12425 push_factor(g, 1);
12426 if (mcmp(g, n_factor_number) === 0) {
12427 return -1;
12428 }
12429 t = mdiv(n_factor_number, g);
12430 n_factor_number = t;
12431 t = mmod(x, n_factor_number);
12432 x = t;
12433 t = mmod(xprime, n_factor_number);
12434 xprime = t;
12435 break;
12436 }
12437 }
12438 };
12439
12440 push_factor = function(d, count) {
12441 p1 = new U();
12442 p1.k = NUM;
12443 p1.q.a = d;
12444 p1.q.b = mint(1);
12445 push(p1);
12446 if (count > 1) {
12447 push_symbol(POWER);
12448 swap();
12449 p1 = new U();
12450 p1.k = NUM;
12451 p1.q.a = mint(count);
12452 p1.q.b = mint(1);
12453 push(p1);
12454 return list(3);
12455 }
12456 };
12457
12458
12459 /* Power function
12460
12461 Input: push Base
12462
12463 push Exponent
12464
12465 Output: Result on stack
12466 */
12467
12468 Eval_power = function() {
12469 push(cadr(p1));
12470 Eval();
12471 push(caddr(p1));
12472 Eval();
12473 return power();
12474 };
12475
12476 power = function() {
12477 save();
12478 yypower();
12479 return restore();
12480 };
12481
12482 yypower = function() {
12483 var n;
12484 n = 0;
12485 p2 = pop();
12486 p1 = pop();
12487 if (isrational(p1) && isrational(p2)) {
12488 push(p1);
12489 push(p2);
12490 qpow();
12491 return;
12492 }
12493 if (isnum(p1) && isnum(p2)) {
12494 push(p1);
12495 push(p2);
12496 dpow();
12497 return;
12498 }
12499 if (istensor(p1)) {
12500 power_tensor();
12501 return;
12502 }
12503 if (p1 === symbol(E) && car(p2) === symbol(LOG)) {
12504 push(cadr(p2));
12505 return;
12506 }
12507 if (p1 === symbol(E) && isdouble(p2)) {
12508 push_double(Math.exp(p2.d));
12509 return;
12510 }
12511 if (equal(p1, one) || iszero(p2)) {
12512 push(one);
12513 return;
12514 }
12515 if (equal(p2, one)) {
12516 push(p1);
12517 return;
12518 }
12519 if (car(p1) === symbol(MULTIPLY)) {
12520 p1 = cdr(p1);
12521 push(car(p1));
12522 push(p2);
12523 power();
12524 p1 = cdr(p1);
12525 while (iscons(p1)) {
12526 push(car(p1));
12527 push(p2);
12528 power();
12529 multiply();
12530 p1 = cdr(p1);
12531 }
12532 return;
12533 }
12534 if (car(p1) === symbol(POWER)) {
12535 push(cadr(p1));
12536 push(caddr(p1));
12537 push(p2);
12538 multiply();
12539 power();
12540 return;
12541 }
12542 if (expanding && isadd(p1) && isnum(p2)) {
12543 push(p2);
12544 n = pop_integer();
12545 if (n > 1 && n !== 0x80000000) {
12546 power_sum(n);
12547 return;
12548 }
12549 }
12550 if (trigmode === 1 && car(p1) === symbol(SIN) && iseveninteger(p2)) {
12551 push_integer(1);
12552 push(cadr(p1));
12553 cosine();
12554 push_integer(2);
12555 power();
12556 subtract();
12557 push(p2);
12558 push_rational(1, 2);
12559 multiply();
12560 power();
12561 return;
12562 }
12563 if (trigmode === 2 && car(p1) === symbol(COS) && iseveninteger(p2)) {
12564 push_integer(1);
12565 push(cadr(p1));
12566 sine();
12567 push_integer(2);
12568 power();
12569 subtract();
12570 push(p2);
12571 push_rational(1, 2);
12572 multiply();
12573 power();
12574 return;
12575 }
12576 if (iscomplexnumber(p1)) {
12577 if (isinteger(p2)) {
12578 push(p1);
12579 conjugate();
12580 p3 = pop();
12581 push(p3);
12582 push(p3);
12583 push(p1);
12584 multiply();
12585 divide();
12586 push(p2);
12587 negate();
12588 power();
12589 return;
12590 }
12591 if (isnum(p2)) {
12592 push(p1);
12593 mag();
12594 push(p2);
12595 power();
12596 push_integer(-1);
12597 push(p1);
12598 arg();
12599 push(p2);
12600 multiply();
12601 push(symbol(PI));
12602 divide();
12603 power();
12604 multiply();
12605 return;
12606
12607 /*
12608 push(p1)
12609 mag()
12610 push(p2)
12611 power()
12612 push(symbol(E))
12613 push(p1)
12614 arg()
12615 push(p2)
12616 multiply()
12617 push(imaginaryunit)
12618 multiply()
12619 power()
12620 multiply()
12621 */
12622 }
12623 }
12624 if (simplify_polar()) {
12625 return;
12626 }
12627 push_symbol(POWER);
12628 push(p1);
12629 push(p2);
12630 return list(3);
12631 };
12632
12633 power_sum = function(n) {
12634 var a, ac, ad, ae, i, j, k, ref1, ref2, ref3;
12635 a = [];
12636 i = 0;
12637 j = 0;
12638 k = 0;
12639 k = length(p1) - 1;
12640 push_frame(k * (n + 1));
12641 p1 = cdr(p1);
12642 for (i = ac = 0, ref1 = k; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
12643 for (j = ad = 0, ref2 = n; 0 <= ref2 ? ad <= ref2 : ad >= ref2; j = 0 <= ref2 ? ++ad : --ad) {
12644 push(car(p1));
12645 push_integer(j);
12646 power();
12647 stack[frame + i * (n + 1) + j] = pop();
12648 }
12649 p1 = cdr(p1);
12650 }
12651 push_integer(n);
12652 factorial();
12653 p1 = pop();
12654 for (i = ae = 0, ref3 = k; 0 <= ref3 ? ae < ref3 : ae > ref3; i = 0 <= ref3 ? ++ae : --ae) {
12655 a[i] = 0;
12656 }
12657 push(zero);
12658 multinomial_sum(k, n, a, 0, n);
12659 return pop_frame(k * (n + 1));
12660 };
12661
12662 multinomial_sum = function(k, n, a, i, m) {
12663 var ac, ad, ae, j, ref1, ref2, ref3;
12664 j = 0;
12665 if (i < k - 1) {
12666 for (j = ac = 0, ref1 = m; 0 <= ref1 ? ac <= ref1 : ac >= ref1; j = 0 <= ref1 ? ++ac : --ac) {
12667 a[i] = j;
12668 multinomial_sum(k, n, a, i + 1, m - j);
12669 }
12670 return;
12671 }
12672 a[i] = m;
12673 push(p1);
12674 for (j = ad = 0, ref2 = k; 0 <= ref2 ? ad < ref2 : ad > ref2; j = 0 <= ref2 ? ++ad : --ad) {
12675 push_integer(a[j]);
12676 factorial();
12677 divide();
12678 }
12679 for (j = ae = 0, ref3 = k; 0 <= ref3 ? ae < ref3 : ae > ref3; j = 0 <= ref3 ? ++ae : --ae) {
12680 push(stack[frame + j * (n + 1) + a[j]]);
12681 multiply();
12682 }
12683 return add();
12684 };
12685
12686 simplify_polar = function() {
12687 var doNothing, n;
12688 n = 0;
12689 n = isquarterturn(p2);
12690 switch (n) {
12691 case 0:
12692 doNothing = 1;
12693 break;
12694 case 1:
12695 push_integer(1);
12696 return 1;
12697 case 2:
12698 push_integer(-1);
12699 return 1;
12700 case 3:
12701 push(imaginaryunit);
12702 return 1;
12703 case 4:
12704 push(imaginaryunit);
12705 negate();
12706 return 1;
12707 }
12708 if (car(p2) === symbol(ADD)) {
12709 p3 = cdr(p2);
12710 while (iscons(p3)) {
12711 n = isquarterturn(car(p3));
12712 if (n) {
12713 break;
12714 }
12715 p3 = cdr(p3);
12716 }
12717 switch (n) {
12718 case 0:
12719 return 0;
12720 case 1:
12721 push_integer(1);
12722 break;
12723 case 2:
12724 push_integer(-1);
12725 break;
12726 case 3:
12727 push(imaginaryunit);
12728 break;
12729 case 4:
12730 push(imaginaryunit);
12731 negate();
12732 }
12733 push(p2);
12734 push(car(p3));
12735 subtract();
12736 exponential();
12737 multiply();
12738 return 1;
12739 }
12740 return 0;
12741 };
12742
12743 Eval_prime = function() {
12744 push(cadr(p1));
12745 Eval();
12746 return prime();
12747 };
12748
12749 prime = function() {
12750 var n;
12751 n = 0;
12752 n = pop_integer();
12753 if (n < 1 || n > MAXPRIMETAB) {
12754 stop("prime: Argument out of range.");
12755 }
12756 n = primetab[n - 1];
12757 return push_integer(n);
12758 };
12759
12760 power_str = "^";
12761
12762 stringToBePrinted = "";
12763
12764 print_str = function(s) {
12765 return stringToBePrinted += s;
12766 };
12767
12768 print_char = function(c) {
12769 return stringToBePrinted += c;
12770 };
12771
12772 collectResultLine = function(p) {
12773 stringToBePrinted = "";
12774 print_expr(p);
12775 return stringToBePrinted;
12776 };
12777
12778 printline = function(p) {
12779 stringToBePrinted = "";
12780 print_expr(p);
12781 return console.log(stringToBePrinted);
12782 };
12783
12784 print_denom = function(p, d) {
12785 save();
12786 p1 = cadr(p);
12787 p2 = caddr(p);
12788 if (d === 1 && !isminusone(p2)) {
12789 print_char('(');
12790 }
12791 if (isfraction(p1) || car(p1) === symbol(ADD) || car(p1) === symbol(MULTIPLY) || car(p1) === symbol(POWER) || lessp(p1, zero)) {
12792 print_char('(');
12793 print_expr(p1);
12794 print_char(')');
12795 } else {
12796 print_expr(p1);
12797 }
12798 if (isminusone(p2)) {
12799 restore();
12800 return;
12801 }
12802 if (test_flag === 0) {
12803 print_str(power_str);
12804 } else {
12805 print_char('^');
12806 }
12807 push(p2);
12808 negate();
12809 p2 = pop();
12810 if (isfraction(p2) || car(p2) === symbol(ADD) || car(p2) === symbol(MULTIPLY) || car(p2) === symbol(POWER)) {
12811 print_char('(');
12812 print_expr(p2);
12813 print_char(')');
12814 } else {
12815 print_expr(p2);
12816 }
12817 if (d === 1) {
12818 print_char(')');
12819 }
12820 return restore();
12821 };
12822
12823 print_a_over_b = function(p) {
12824 var d, doNothing, n;
12825 flag = 0;
12826 n = 0;
12827 d = 0;
12828 save();
12829 n = 0;
12830 d = 0;
12831 p1 = cdr(p);
12832 p2 = car(p1);
12833 if (isrational(p2)) {
12834 push(p2);
12835 mp_numerator();
12836 absval();
12837 p3 = pop();
12838 push(p2);
12839 mp_denominator();
12840 p4 = pop();
12841 if (!isplusone(p3)) {
12842 n++;
12843 }
12844 if (!isplusone(p4)) {
12845 d++;
12846 }
12847 p1 = cdr(p1);
12848 } else {
12849 p3 = one;
12850 p4 = one;
12851 }
12852 while (iscons(p1)) {
12853 p2 = car(p1);
12854 if (is_denominator(p2)) {
12855 d++;
12856 } else {
12857 n++;
12858 }
12859 p1 = cdr(p1);
12860 }
12861 if (n === 0) {
12862 print_char('1');
12863 } else {
12864 flag = 0;
12865 p1 = cdr(p);
12866 if (isrational(car(p1))) {
12867 p1 = cdr(p1);
12868 }
12869 if (!isplusone(p3)) {
12870 print_factor(p3);
12871 flag = 1;
12872 }
12873 while (iscons(p1)) {
12874 p2 = car(p1);
12875 if (is_denominator(p2)) {
12876 doNothing = 1;
12877 } else {
12878 if (flag) {
12879 print_multiply_sign();
12880 }
12881 print_factor(p2);
12882 flag = 1;
12883 }
12884 p1 = cdr(p1);
12885 }
12886 }
12887 if (test_flag === 0) {
12888 print_str(" / ");
12889 } else {
12890 print_str("/");
12891 }
12892 if (d > 1) {
12893 print_char('(');
12894 }
12895 flag = 0;
12896 p1 = cdr(p);
12897 if (isrational(car(p1))) {
12898 p1 = cdr(p1);
12899 }
12900 if (!isplusone(p4)) {
12901 print_factor(p4);
12902 flag = 1;
12903 }
12904 while (iscons(p1)) {
12905 p2 = car(p1);
12906 if (is_denominator(p2)) {
12907 if (flag) {
12908 print_multiply_sign();
12909 }
12910 print_denom(p2, d);
12911 flag = 1;
12912 }
12913 p1 = cdr(p1);
12914 }
12915 if (d > 1) {
12916 print_char(')');
12917 }
12918 return restore();
12919 };
12920
12921 print_expr = function(p) {
12922 var results;
12923 if (isadd(p)) {
12924 p = cdr(p);
12925 if (sign_of_term(car(p)) === '-') {
12926 print_str("-");
12927 }
12928 print_term(car(p));
12929 p = cdr(p);
12930 results = [];
12931 while (iscons(p)) {
12932 if (sign_of_term(car(p)) === '+') {
12933 if (test_flag === 0) {
12934 print_str(" + ");
12935 } else {
12936 print_str("+");
12937 }
12938 } else {
12939 if (test_flag === 0) {
12940 print_str(" - ");
12941 } else {
12942 print_str("-");
12943 }
12944 }
12945 print_term(car(p));
12946 results.push(p = cdr(p));
12947 }
12948 return results;
12949 } else {
12950 if (sign_of_term(p) === '-') {
12951 print_str("-");
12952 }
12953 return print_term(p);
12954 }
12955 };
12956
12957 sign_of_term = function(p) {
12958 if (car(p) === symbol(MULTIPLY) && isnum(cadr(p)) && lessp(cadr(p), zero)) {
12959 return '-';
12960 } else if (isnum(p) && lessp(p, zero)) {
12961 return '-';
12962 } else {
12963 return '+';
12964 }
12965 };
12966
12967 print_term = function(p) {
12968 var results;
12969 if (car(p) === symbol(MULTIPLY) && any_denominators(p)) {
12970 print_a_over_b(p);
12971 return;
12972 }
12973 if (car(p) === symbol(MULTIPLY)) {
12974 p = cdr(p);
12975 if (isminusone(car(p))) {
12976 p = cdr(p);
12977 }
12978 print_factor(car(p));
12979 p = cdr(p);
12980 results = [];
12981 while (iscons(p)) {
12982 print_multiply_sign();
12983 print_factor(car(p));
12984 results.push(p = cdr(p));
12985 }
12986 return results;
12987 } else {
12988 return print_factor(p);
12989 }
12990 };
12991
12992 print_subexpr = function(p) {
12993 print_char('(');
12994 print_expr(p);
12995 return print_char(')');
12996 };
12997
12998 print_factorial_function = function(p) {
12999 p = cadr(p);
13000 if (car(p) === symbol(ADD) || car(p) === symbol(MULTIPLY) || car(p) === symbol(POWER) || car(p) === symbol(FACTORIAL)) {
13001 print_subexpr(p);
13002 } else {
13003 print_expr(p);
13004 }
13005 return print_char('!');
13006 };
13007
13008 print_tensor = function(p) {
13009 return print_tensor_inner(p, 0, 0);
13010 };
13011
13012 print_tensor_inner = function(p, j, k) {
13013 var ac, i, ref1;
13014 i = 0;
13015 print_str("(");
13016 for (i = ac = 0, ref1 = p.tensor.dim[j]; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
13017 if (j + 1 === p.tensor.ndim) {
13018 print_expr(p.tensor.elem[k]);
13019 k++;
13020 } else {
13021 k = print_tensor_inner(p, j + 1, k);
13022 }
13023 if (i + 1 < p.tensor.dim[j]) {
13024 if (test_flag === 0) {
13025 print_str(",");
13026 } else {
13027 print_str(",");
13028 }
13029 }
13030 }
13031 print_str(")");
13032 return k;
13033 };
13034
13035 print_factor = function(p) {
13036 if (isnum(p)) {
13037 print_number(p);
13038 return;
13039 }
13040 if (isstr(p)) {
13041 print_str("\"");
13042 print_str(p.str);
13043 print_str("\"");
13044 return;
13045 }
13046 if (istensor(p)) {
13047 print_tensor(p);
13048 return;
13049 }
13050 if (isadd(p) || car(p) === symbol(MULTIPLY)) {
13051 print_str("(");
13052 print_expr(p);
13053 print_str(")");
13054 return;
13055 }
13056 if (car(p) === symbol(POWER)) {
13057 if (cadr(p) === symbol(E)) {
13058 print_str("exp(");
13059 print_expr(caddr(p));
13060 print_str(")");
13061 return;
13062 }
13063 if (isminusone(caddr(p))) {
13064 if (test_flag === 0) {
13065 print_str("1 / ");
13066 } else {
13067 print_str("1/");
13068 }
13069 if (iscons(cadr(p))) {
13070 print_str("(");
13071 print_expr(cadr(p));
13072 print_str(")");
13073 } else {
13074 print_expr(cadr(p));
13075 }
13076 return;
13077 }
13078 if (isadd(cadr(p)) || caadr(p) === symbol(MULTIPLY) || caadr(p) === symbol(POWER) || isnegativenumber(cadr(p))) {
13079 print_str("(");
13080 print_expr(cadr(p));
13081 print_str(")");
13082 } else if (isnum(cadr(p)) && (lessp(cadr(p), zero) || isfraction(cadr(p)))) {
13083 print_str("(");
13084 print_factor(cadr(p));
13085 print_str(")");
13086 } else {
13087 print_factor(cadr(p));
13088 }
13089 if (test_flag === 0) {
13090 print_str(power_str);
13091 } else {
13092 print_str("^");
13093 }
13094 if (iscons(caddr(p)) || isfraction(caddr(p)) || (isnum(caddr(p)) && lessp(caddr(p), zero))) {
13095 print_str("(");
13096 print_expr(caddr(p));
13097 print_str(")");
13098 } else {
13099 print_factor(caddr(p));
13100 }
13101 return;
13102 }
13103 if (car(p) === symbol(INDEX) && issymbol(cadr(p))) {
13104 print_index_function(p);
13105 return;
13106 }
13107 if (car(p) === symbol(FACTORIAL)) {
13108 print_factorial_function(p);
13109 return;
13110 }
13111 if (iscons(p)) {
13112 print_factor(car(p));
13113 p = cdr(p);
13114 print_str("(");
13115 if (iscons(p)) {
13116 print_expr(car(p));
13117 p = cdr(p);
13118 while (iscons(p)) {
13119 if (test_flag === 0) {
13120 print_str(",");
13121 } else {
13122 print_str(",");
13123 }
13124 print_expr(car(p));
13125 p = cdr(p);
13126 }
13127 }
13128 print_str(")");
13129 return;
13130 }
13131 if (p === symbol(DERIVATIVE)) {
13132 return print_char('d');
13133 } else if (p === symbol(E)) {
13134 return print_str("exp(1)");
13135 } else if (p === symbol(PI)) {
13136 return print_str("pi");
13137 } else {
13138 return print_str(get_printname(p));
13139 }
13140 };
13141
13142 print1 = function(p, accumulator) {
13143 var topLevelCall;
13144 topLevelCall = false;
13145 if (accumulator == null) {
13146 topLevelCall = true;
13147 accumulator = "";
13148 }
13149 switch (p.k) {
13150 case CONS:
13151 accumulator += "(";
13152 accumulator = print1(car(p), accumulator);
13153 if (p === cdr(p)) {
13154 console.log("oh no recursive!");
13155 debugger;
13156 }
13157 p = cdr(p);
13158 while (iscons(p)) {
13159 accumulator += " ";
13160 accumulator = print1(car(p), accumulator);
13161 p = cdr(p);
13162 if (p === cdr(p)) {
13163 console.log("oh no recursive!");
13164 debugger;
13165 }
13166 }
13167 if (p !== symbol(NIL)) {
13168 accumulator += " . ";
13169 accumulator = print1(p, accumulator);
13170 }
13171 accumulator += ")";
13172 break;
13173 case STR:
13174 accumulator += p.str;
13175 break;
13176 case NUM:
13177 case DOUBLE:
13178 accumulator = print_number(p, accumulator);
13179 break;
13180 case SYM:
13181 accumulator += get_printname(p);
13182 break;
13183 default:
13184 accumulator += "<tensor>";
13185 }
13186 if (topLevelCall) {
13187 return console.log(accumulator);
13188 } else {
13189 return accumulator;
13190 }
13191 };
13192
13193 print_multiply_sign = function() {
13194 if (test_flag === 0) {
13195 return print_str(" ");
13196 } else {
13197 return print_str("*");
13198 }
13199 };
13200
13201 is_denominator = function(p) {
13202 if (car(p) === symbol(POWER) && cadr(p) !== symbol(E) && isnegativeterm(caddr(p))) {
13203 return 1;
13204 } else {
13205 return 0;
13206 }
13207 };
13208
13209 any_denominators = function(p) {
13210 var q;
13211 p = cdr(p);
13212 while (iscons(p)) {
13213 q = car(p);
13214 if (is_denominator(q)) {
13215 return 1;
13216 }
13217 p = cdr(p);
13218 }
13219 return 0;
13220 };
13221
13222 Eval_product = function() {
13223 var ac, i, j, k, ref1, ref2;
13224 i = 0;
13225 j = 0;
13226 k = 0;
13227 p6 = cadr(p1);
13228 if (!issymbol(p6)) {
13229 stop("product: 1st arg?");
13230 }
13231 push(caddr(p1));
13232 Eval();
13233 j = pop_integer();
13234 if (j === 0x80000000) {
13235 stop("product: 2nd arg?");
13236 }
13237 push(cadddr(p1));
13238 Eval();
13239 k = pop_integer();
13240 if (k === 0x80000000) {
13241 stop("product: 3rd arg?");
13242 }
13243 p1 = caddddr(p1);
13244 p4 = get_binding(p6);
13245 p3 = get_arglist(p6);
13246 push_integer(1);
13247 for (i = ac = ref1 = j, ref2 = k; ref1 <= ref2 ? ac <= ref2 : ac >= ref2; i = ref1 <= ref2 ? ++ac : --ac) {
13248 push_integer(i);
13249 p5 = pop();
13250 set_binding(p6, p5);
13251 push(p1);
13252 Eval();
13253 multiply();
13254 }
13255 return set_binding_and_arglist(p6, p4, p3);
13256 };
13257
13258 qadd = function() {
13259 var a, ab, b, ba, c;
13260 save();
13261 p2 = pop();
13262 p1 = pop();
13263 ab = mmul(p1.q.a, p2.q.b);
13264 ba = mmul(p1.q.b, p2.q.a);
13265 a = madd(ab, ba);
13266 if (MZERO(a)) {
13267 push(zero);
13268 restore();
13269 return;
13270 }
13271 b = mmul(p1.q.b, p2.q.b);
13272 c = mgcd(a, b);
13273 c = makeSignSameAs(c, b);
13274 p1 = new U();
13275 p1.k = NUM;
13276 p1.q.a = mdiv(a, c);
13277 p1.q.b = mdiv(b, c);
13278 push(p1);
13279 return restore();
13280 };
13281
13282 qdiv = function() {
13283 var aa, bb, c;
13284 save();
13285 p2 = pop();
13286 p1 = pop();
13287 if (MZERO(p2.q.a)) {
13288 stop("divide by zero");
13289 }
13290 if (MZERO(p1.q.a)) {
13291 push(zero);
13292 restore();
13293 return;
13294 }
13295 aa = mmul(p1.q.a, p2.q.b);
13296 bb = mmul(p1.q.b, p2.q.a);
13297 c = mgcd(aa, bb);
13298 c = makeSignSameAs(c, bb);
13299 p1 = new U();
13300 p1.k = NUM;
13301 p1.q.a = mdiv(aa, c);
13302 p1.q.b = mdiv(bb, c);
13303 push(p1);
13304 return restore();
13305 };
13306
13307 qmul = function() {
13308 var aa, bb, c;
13309 save();
13310 p2 = pop();
13311 p1 = pop();
13312 if (MZERO(p1.q.a) || MZERO(p2.q.a)) {
13313 push(zero);
13314 restore();
13315 return;
13316 }
13317 aa = mmul(p1.q.a, p2.q.a);
13318 bb = mmul(p1.q.b, p2.q.b);
13319 c = mgcd(aa, bb);
13320 c = makeSignSameAs(c, bb);
13321 p1 = new U();
13322 p1.k = NUM;
13323 p1.q.a = mdiv(aa, c);
13324 p1.q.b = mdiv(bb, c);
13325 push(p1);
13326 return restore();
13327 };
13328
13329 qpow = function() {
13330 save();
13331 qpowf();
13332 return restore();
13333 };
13334
13335 qpowf = function() {
13336 var a, b, expo, t, x, y;
13337 expo = 0;
13338 p2 = pop();
13339 p1 = pop();
13340 if (isplusone(p1) || iszero(p2)) {
13341 push_integer(1);
13342 return;
13343 }
13344 if (iszero(p1)) {
13345 if (isnegativenumber(p2)) {
13346 stop("divide by zero");
13347 }
13348 push(zero);
13349 return;
13350 }
13351 if (isplusone(p2)) {
13352 push(p1);
13353 return;
13354 }
13355 if (isinteger(p2)) {
13356 push(p2);
13357 expo = pop_integer();
13358 if (expo === 0x80000000) {
13359 push_symbol(POWER);
13360 push(p1);
13361 push(p2);
13362 list(3);
13363 return;
13364 }
13365 x = mpow(p1.q.a, Math.abs(expo));
13366 y = mpow(p1.q.b, Math.abs(expo));
13367 if (expo < 0) {
13368 t = x;
13369 x = y;
13370 y = t;
13371 x = makeSignSameAs(x, y);
13372 y = makePositive(y);
13373 }
13374 p3 = new U();
13375 p3.k = NUM;
13376 p3.q.a = x;
13377 p3.q.b = y;
13378 push(p3);
13379 return;
13380 }
13381 if (isminusone(p1)) {
13382 push(p2);
13383 normalize_angle();
13384 return;
13385 }
13386 if (isnegativenumber(p1)) {
13387 push(p1);
13388 negate();
13389 push(p2);
13390 qpow();
13391 push_integer(-1);
13392 push(p2);
13393 qpow();
13394 multiply();
13395 return;
13396 }
13397 if (!isinteger(p1)) {
13398 push(p1);
13399 mp_numerator();
13400 push(p2);
13401 qpow();
13402 push(p1);
13403 mp_denominator();
13404 push(p2);
13405 negate();
13406 qpow();
13407 multiply();
13408 return;
13409 }
13410 if (is_small_integer(p1)) {
13411 push(p1);
13412 push(p2);
13413 quickfactor();
13414 return;
13415 }
13416 if (!p2.q.a.isSmall || !p2.q.b.isSmall) {
13417 push_symbol(POWER);
13418 push(p1);
13419 push(p2);
13420 list(3);
13421 return;
13422 }
13423 a = p2.q.a;
13424 b = p2.q.b;
13425 x = mroot(p1.q.a, b);
13426 if (x === 0) {
13427 push_symbol(POWER);
13428 push(p1);
13429 push(p2);
13430 list(3);
13431 return;
13432 }
13433 y = mpow(x, a);
13434 p3 = new U();
13435 p3.k = NUM;
13436 if (p2.q.a.isNegative()) {
13437 p3.q.a = bigInt(1);
13438 p3.q.b = y;
13439 } else {
13440 p3.q.a = y;
13441 p3.q.b = bigInt(1);
13442 }
13443 return push(p3);
13444 };
13445
13446 normalize_angle = function() {
13447 save();
13448 p1 = pop();
13449 if (isinteger(p1)) {
13450 if (p1.q.a.isOdd()) {
13451 push_integer(-1);
13452 } else {
13453 push_integer(1);
13454 }
13455 restore();
13456 return;
13457 }
13458 push(p1);
13459 bignum_truncate();
13460 p2 = pop();
13461 if (isnegativenumber(p1)) {
13462 push(p2);
13463 push_integer(-1);
13464 add();
13465 p2 = pop();
13466 }
13467 push(p1);
13468 push(p2);
13469 subtract();
13470 p3 = pop();
13471 push_symbol(POWER);
13472 push_integer(-1);
13473 push(p3);
13474 list(3);
13475 if (p2.q.a.isOdd()) {
13476 negate();
13477 }
13478 return restore();
13479 };
13480
13481 is_small_integer = function(p) {
13482 return p.q.a.isSmall;
13483 };
13484
13485 quickfactor = function() {
13486 var ac, h, i, n, ref1, stackIndex;
13487 i = 0;
13488 save();
13489 p2 = pop();
13490 p1 = pop();
13491 h = tos;
13492 push(p1);
13493 factor_small_number();
13494 n = tos - h;
13495 stackIndex = h;
13496 for (i = ac = 0, ref1 = n; ac < ref1; i = ac += 2) {
13497 push(stack[stackIndex + i]);
13498 push(stack[stackIndex + i + 1]);
13499 push(p2);
13500 multiply();
13501 quickpower();
13502 }
13503 multiply_all(tos - h - n);
13504 p1 = pop();
13505 tos = h;
13506 push(p1);
13507 return restore();
13508 };
13509
13510 quickpower = function() {
13511 var expo;
13512 expo = 0;
13513 save();
13514 p2 = pop();
13515 p1 = pop();
13516 push(p2);
13517 bignum_truncate();
13518 p3 = pop();
13519 push(p2);
13520 push(p3);
13521 subtract();
13522 p4 = pop();
13523 if (!iszero(p4)) {
13524 push_symbol(POWER);
13525 push(p1);
13526 push(p4);
13527 list(3);
13528 }
13529 push(p3);
13530 expo = pop_integer();
13531 if (expo === 0x80000000) {
13532 push_symbol(POWER);
13533 push(p1);
13534 push(p3);
13535 list(3);
13536 restore();
13537 return;
13538 }
13539 if (expo === 0) {
13540 restore();
13541 return;
13542 }
13543 push(p1);
13544 bignum_power_number(expo);
13545 return restore();
13546 };
13547
13548 Eval_quotient = function() {
13549 push(cadr(p1));
13550 Eval();
13551 push(caddr(p1));
13552 Eval();
13553 push(cadddr(p1));
13554 Eval();
13555 p1 = pop();
13556 if (p1 === symbol(NIL)) {
13557 p1 = symbol(SYMBOL_X);
13558 }
13559 push(p1);
13560 return divpoly();
13561 };
13562
13563 divpoly = function() {
13564 var ac, dividend, divisor, h, i, m, n, ref1, x;
13565 h = 0;
13566 i = 0;
13567 m = 0;
13568 n = 0;
13569 x = 0;
13570 save();
13571 p3 = pop();
13572 p2 = pop();
13573 p1 = pop();
13574 h = tos;
13575 dividend = tos;
13576 push(p1);
13577 push(p3);
13578 m = coeff() - 1;
13579 divisor = tos;
13580 push(p2);
13581 push(p3);
13582 n = coeff() - 1;
13583 x = m - n;
13584 push_integer(0);
13585 p5 = pop();
13586 while (x >= 0) {
13587 push(stack[dividend + m]);
13588 push(stack[divisor + n]);
13589 divide();
13590 p4 = pop();
13591 for (i = ac = 0, ref1 = n; 0 <= ref1 ? ac <= ref1 : ac >= ref1; i = 0 <= ref1 ? ++ac : --ac) {
13592 push(stack[dividend + x + i]);
13593 push(stack[divisor + i]);
13594 push(p4);
13595 multiply();
13596 subtract();
13597 stack[dividend + x + i] = pop();
13598 }
13599 push(p5);
13600 push(p4);
13601 push(p3);
13602 push_integer(x);
13603 power();
13604 multiply();
13605 add();
13606 p5 = pop();
13607 m--;
13608 x--;
13609 }
13610 tos = h;
13611 push(p5);
13612 return restore();
13613 };
13614
13615 DEBUG = 0;
13616
13617 Eval_rationalize = function() {
13618 push(cadr(p1));
13619 Eval();
13620 return rationalize();
13621 };
13622
13623 rationalize = function() {
13624 var x;
13625 x = expanding;
13626 save();
13627 yyrationalize();
13628 restore();
13629 return expanding = x;
13630 };
13631
13632 yyrationalize = function() {
13633 p1 = pop();
13634 if (istensor(p1)) {
13635 __rationalize_tensor();
13636 return;
13637 }
13638 expanding = 0;
13639 if (car(p1) !== symbol(ADD)) {
13640 push(p1);
13641 return;
13642 }
13643 if (DEBUG) {
13644 printf("rationalize: this is the input expr:\n");
13645 printline(p1);
13646 }
13647 push(one);
13648 multiply_denominators(p1);
13649 p2 = pop();
13650 if (DEBUG) {
13651 printf("rationalize: this is the common denominator:\n");
13652 printline(p2);
13653 }
13654 push(zero);
13655 p3 = cdr(p1);
13656 while (iscons(p3)) {
13657 push(p2);
13658 push(car(p3));
13659 multiply();
13660 add();
13661 p3 = cdr(p3);
13662 }
13663 if (DEBUG) {
13664 printf("rationalize: original expr times common denominator:\n");
13665 printline(stack[tos - 1]);
13666 }
13667 Condense();
13668 if (DEBUG) {
13669 printf("rationalize: after factoring:\n");
13670 printline(stack[tos - 1]);
13671 }
13672 push(p2);
13673 divide();
13674 if (DEBUG) {
13675 printf("rationalize: after dividing by common denom. (and we're done):\n");
13676 return printline(stack[tos - 1]);
13677 }
13678 };
13679
13680 multiply_denominators = function(p) {
13681 var results;
13682 if (car(p) === symbol(ADD)) {
13683 p = cdr(p);
13684 results = [];
13685 while (iscons(p)) {
13686 multiply_denominators_term(car(p));
13687 results.push(p = cdr(p));
13688 }
13689 return results;
13690 } else {
13691 return multiply_denominators_term(p);
13692 }
13693 };
13694
13695 multiply_denominators_term = function(p) {
13696 var results;
13697 if (car(p) === symbol(MULTIPLY)) {
13698 p = cdr(p);
13699 results = [];
13700 while (iscons(p)) {
13701 multiply_denominators_factor(car(p));
13702 results.push(p = cdr(p));
13703 }
13704 return results;
13705 } else {
13706 return multiply_denominators_factor(p);
13707 }
13708 };
13709
13710 multiply_denominators_factor = function(p) {
13711 if (car(p) !== symbol(POWER)) {
13712 return;
13713 }
13714 push(p);
13715 p = caddr(p);
13716 if (isnegativenumber(p)) {
13717 inverse();
13718 __lcm();
13719 return;
13720 }
13721 if (car(p) === symbol(MULTIPLY) && isnegativenumber(cadr(p))) {
13722 inverse();
13723 __lcm();
13724 return;
13725 }
13726 return pop();
13727 };
13728
13729 __rationalize_tensor = function() {
13730 var ac, i, n, ref1;
13731 i = 0;
13732 push(p1);
13733 Eval();
13734 p1 = pop();
13735 if (!istensor(p1)) {
13736 push(p1);
13737 return;
13738 }
13739 n = p1.tensor.nelem;
13740 for (i = ac = 0, ref1 = n; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
13741 push(p1.tensor.elem[i]);
13742 rationalize();
13743 p1.tensor.elem[i] = pop();
13744 }
13745 if (p1.tensor.nelem !== p1.tensor.elem.length) {
13746 console.log("something wrong in tensor dimensions");
13747 debugger;
13748 }
13749 return push(p1);
13750 };
13751
13752 __lcm = function() {
13753 save();
13754 p1 = pop();
13755 p2 = pop();
13756 push(p1);
13757 push(p2);
13758 multiply();
13759 push(p1);
13760 push(p2);
13761 gcd();
13762 divide();
13763 return restore();
13764 };
13765
13766
13767 /*
13768 Returns the real part of complex z
13769
13770 z real(z)
13771 - -------
13772
13773 a + i b a
13774
13775 exp(i a) cos(a)
13776 */
13777
13778 Eval_real = function() {
13779 push(cadr(p1));
13780 Eval();
13781 return real();
13782 };
13783
13784 real = function() {
13785 save();
13786 rect();
13787 p1 = pop();
13788 push(p1);
13789 push(p1);
13790 conjugate();
13791 add();
13792 push_integer(2);
13793 divide();
13794 return restore();
13795 };
13796
13797
13798 /*
13799 Convert complex z to rectangular form
13800
13801 Input: push z
13802
13803 Output: Result on stack
13804 */
13805
13806 Eval_rect = function() {
13807 push(cadr(p1));
13808 Eval();
13809 return rect();
13810 };
13811
13812 rect = function() {
13813 save();
13814 p1 = pop();
13815 if (car(p1) === symbol(ADD)) {
13816 push_integer(0);
13817 p1 = cdr(p1);
13818 while (iscons(p1)) {
13819 push(car(p1));
13820 rect();
13821 add();
13822 p1 = cdr(p1);
13823 }
13824 } else {
13825 push(p1);
13826 mag();
13827 push(p1);
13828 arg();
13829 p1 = pop();
13830 push(p1);
13831 cosine();
13832 push(imaginaryunit);
13833 push(p1);
13834 sine();
13835 multiply();
13836 add();
13837 multiply();
13838 }
13839 return restore();
13840 };
13841
13842 Eval_roots = function() {
13843 p2 = cadr(p1);
13844 if (car(p2) === symbol(SETQ) || car(p2) === symbol(TESTEQ)) {
13845 push(cadr(p2));
13846 Eval();
13847 push(caddr(p2));
13848 Eval();
13849 subtract();
13850 } else {
13851 push(p2);
13852 Eval();
13853 p2 = pop();
13854 if (car(p2) === symbol(SETQ) || car(p2) === symbol(TESTEQ)) {
13855 push(cadr(p2));
13856 Eval();
13857 push(caddr(p2));
13858 Eval();
13859 subtract();
13860 } else {
13861 push(p2);
13862 }
13863 }
13864 push(caddr(p1));
13865 Eval();
13866 p2 = pop();
13867 if (p2 === symbol(NIL)) {
13868 guess();
13869 } else {
13870 push(p2);
13871 }
13872 p2 = pop();
13873 p1 = pop();
13874 if (!ispoly(p1, p2)) {
13875 stop("roots: 1st argument is not a polynomial");
13876 }
13877 push(p1);
13878 push(p2);
13879 return roots();
13880 };
13881
13882 hasImaginaryCoeff = function() {
13883 var ac, h, i, imaginaryCoefficients, k, ref1;
13884 polycoeff = tos;
13885 push(p1);
13886 push(p2);
13887 k = coeff();
13888 imaginaryCoefficients = false;
13889 h = tos;
13890 for (i = ac = ref1 = k; ac > 0; i = ac += -1) {
13891 if (iscomplexnumber(stack[tos - i])) {
13892 imaginaryCoefficients = true;
13893 break;
13894 }
13895 }
13896 tos -= k;
13897 return imaginaryCoefficients;
13898 };
13899
13900 roots = function() {
13901 var ac, h, i, n, ref1;
13902 h = 0;
13903 i = 0;
13904 n = 0;
13905 h = tos - 2;
13906 roots2();
13907 n = tos - h;
13908 if (n === 0) {
13909 stop("roots: the polynomial is not factorable, try nroots");
13910 }
13911 if (n === 1) {
13912 return;
13913 }
13914 sort_stack(n);
13915 save();
13916 p1 = alloc_tensor(n);
13917 p1.tensor.ndim = 1;
13918 p1.tensor.dim[0] = n;
13919 for (i = ac = 0, ref1 = n; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
13920 p1.tensor.elem[i] = stack[h + i];
13921 }
13922 tos = h;
13923 push(p1);
13924 return restore();
13925 };
13926
13927 roots2 = function() {
13928 save();
13929 p2 = pop();
13930 p1 = pop();
13931 push(p1);
13932 push(p2);
13933 if (!hasImaginaryCoeff()) {
13934 factorpoly();
13935 p1 = pop();
13936 } else {
13937 pop();
13938 pop();
13939 }
13940 if (car(p1) === symbol(MULTIPLY)) {
13941 p1 = cdr(p1);
13942 while (iscons(p1)) {
13943 push(car(p1));
13944 push(p2);
13945 roots3();
13946 p1 = cdr(p1);
13947 }
13948 } else {
13949 push(p1);
13950 push(p2);
13951 roots3();
13952 }
13953 return restore();
13954 };
13955
13956 roots3 = function() {
13957 save();
13958 p2 = pop();
13959 p1 = pop();
13960 if (car(p1) === symbol(POWER) && ispoly(cadr(p1), p2) && isposint(caddr(p1))) {
13961 push(cadr(p1));
13962 push(p2);
13963 mini_solve();
13964 } else if (ispoly(p1, p2)) {
13965 push(p1);
13966 push(p2);
13967 mini_solve();
13968 }
13969 return restore();
13970 };
13971
13972 mini_solve = function() {
13973 var C_CHECKED_AS_NOT_ZERO, R_18_a_b_c_d, R_27_a2_d, R_2_b3, R_3_a, R_3_a_C, R_3_a_c, R_4_DELTA03, R_6_a, R_6_a_C, R_C, R_C_over_3a, R_C_simplified_toCheckIfZero, R_DELTA0, R_DELTA0_toBeCheckedIfZero, R_DELTA1, R_Q, R_a_b_c, R_a_c, R_b2, R_b2_c2, R_b3, R_c2, R_c3, R_determinant, R_m27_a2_d2, R_m4_a_c3, R_m4_b3_d, R_m9_a_b_c, R_m_b_over_3a, flipSignOFQSoCIsNotZero, i_sqrt3, n, one_minus_i_sqrt3, one_plus_i_sqrt3, root_solution;
13974 n = 0;
13975 save();
13976 p2 = pop();
13977 p1 = pop();
13978 push(p1);
13979 push(p2);
13980 n = coeff();
13981 if (n === 2) {
13982 p3 = pop();
13983 p4 = pop();
13984 push(p4);
13985 push(p3);
13986 divide();
13987 negate();
13988 restore();
13989 return;
13990 }
13991 if (n === 3) {
13992 p3 = pop();
13993 p4 = pop();
13994 p5 = pop();
13995 push(p4);
13996 push(p4);
13997 multiply();
13998 push_integer(4);
13999 push(p3);
14000 multiply();
14001 push(p5);
14002 multiply();
14003 subtract();
14004 push_rational(1, 2);
14005 power();
14006 p6 = pop();
14007 push(p6);
14008 push(p4);
14009 subtract();
14010 push(p3);
14011 divide();
14012 push_rational(1, 2);
14013 multiply();
14014 push(p6);
14015 push(p4);
14016 add();
14017 negate();
14018 push(p3);
14019 divide();
14020 push_rational(1, 2);
14021 multiply();
14022 restore();
14023 return;
14024 }
14025 if (n === 4) {
14026 p3 = pop();
14027 p4 = pop();
14028 p5 = pop();
14029 p6 = pop();
14030 push(p5);
14031 push(p5);
14032 multiply();
14033 R_c2 = pop();
14034 push(R_c2);
14035 push(p5);
14036 multiply();
14037 R_c3 = pop();
14038 push(p4);
14039 push(p4);
14040 multiply();
14041 R_b2 = pop();
14042 push(R_b2);
14043 push(p4);
14044 multiply();
14045 R_b3 = pop();
14046 push(R_b3);
14047 push(p6);
14048 push_integer(-4);
14049 multiply();
14050 multiply();
14051 R_m4_b3_d = pop();
14052 push(R_b3);
14053 push_integer(2);
14054 multiply();
14055 R_2_b3 = pop();
14056 push_integer(3);
14057 push(p3);
14058 multiply();
14059 R_3_a = pop();
14060 push(R_3_a);
14061 push_integer(9);
14062 multiply();
14063 push(p3);
14064 multiply();
14065 push(p6);
14066 multiply();
14067 R_27_a2_d = pop();
14068 push(R_27_a2_d);
14069 push(p6);
14070 multiply();
14071 negate();
14072 R_m27_a2_d2 = pop();
14073 push(R_3_a);
14074 push_integer(2);
14075 multiply();
14076 R_6_a = pop();
14077 push(p3);
14078 push(p5);
14079 multiply();
14080 R_a_c = pop();
14081 push(R_a_c);
14082 push(p4);
14083 multiply();
14084 R_a_b_c = pop();
14085 push(R_a_c);
14086 push_integer(3);
14087 multiply();
14088 R_3_a_c = pop();
14089 push_integer(-4);
14090 push(p3);
14091 push(R_c3);
14092 multiply();
14093 multiply();
14094 R_m4_a_c3 = pop();
14095 push(R_a_b_c);
14096 push_integer(9);
14097 multiply();
14098 negate();
14099 R_m9_a_b_c = pop();
14100 push(R_m9_a_b_c);
14101 push(p6);
14102 push_integer(-2);
14103 multiply();
14104 multiply();
14105 R_18_a_b_c_d = pop();
14106 push(R_b2);
14107 push(R_3_a_c);
14108 subtract();
14109 R_DELTA0 = pop();
14110 push(R_b2);
14111 push(R_c2);
14112 multiply();
14113 R_b2_c2 = pop();
14114 push(R_DELTA0);
14115 push_integer(3);
14116 power();
14117 push_integer(4);
14118 multiply();
14119 R_4_DELTA03 = pop();
14120 push(R_DELTA0);
14121 simplify();
14122 Eval();
14123 yyfloat();
14124 Eval();
14125 absval();
14126 R_DELTA0_toBeCheckedIfZero = pop();
14127 push(R_18_a_b_c_d);
14128 push(R_m4_b3_d);
14129 push(R_b2_c2);
14130 push(R_m4_a_c3);
14131 push(R_m27_a2_d2);
14132 add();
14133 add();
14134 add();
14135 add();
14136 simplify();
14137 Eval();
14138 yyfloat();
14139 Eval();
14140 absval();
14141 R_determinant = pop();
14142 push(R_2_b3);
14143 push(R_m9_a_b_c);
14144 push(R_27_a2_d);
14145 add();
14146 add();
14147 R_DELTA1 = pop();
14148 push(R_DELTA1);
14149 push_integer(2);
14150 power();
14151 push(R_4_DELTA03);
14152 subtract();
14153 push_rational(1, 2);
14154 power();
14155 R_Q = pop();
14156 push(p4);
14157 negate();
14158 push(R_3_a);
14159 divide();
14160 R_m_b_over_3a = pop();
14161 if (iszero(R_determinant)) {
14162 if (iszero(R_DELTA0_toBeCheckedIfZero)) {
14163 push(R_m_b_over_3a);
14164 restore();
14165 return;
14166 } else {
14167 push(p3);
14168 push(p6);
14169 push_integer(9);
14170 multiply();
14171 multiply();
14172 push(p4);
14173 push(p5);
14174 multiply();
14175 subtract();
14176 push(R_DELTA0);
14177 push_integer(2);
14178 multiply();
14179 divide();
14180 root_solution = pop();
14181 push(root_solution);
14182 push(root_solution);
14183 push(R_a_b_c);
14184 push_integer(4);
14185 multiply();
14186 push(p3);
14187 push(p3);
14188 push(p6);
14189 push_integer(9);
14190 multiply();
14191 multiply();
14192 multiply();
14193 negate();
14194 push(R_b3);
14195 negate();
14196 add();
14197 add();
14198 push(p3);
14199 push(R_DELTA0);
14200 multiply();
14201 divide();
14202 restore();
14203 return;
14204 }
14205 }
14206 C_CHECKED_AS_NOT_ZERO = false;
14207 flipSignOFQSoCIsNotZero = false;
14208 while (!C_CHECKED_AS_NOT_ZERO) {
14209 push(R_Q);
14210 if (flipSignOFQSoCIsNotZero) {
14211 negate();
14212 }
14213 push(R_DELTA1);
14214 add();
14215 push_rational(1, 2);
14216 multiply();
14217 push_rational(1, 3);
14218 power();
14219 R_C = pop();
14220 push(R_C);
14221 simplify();
14222 Eval();
14223 yyfloat();
14224 Eval();
14225 absval();
14226 R_C_simplified_toCheckIfZero = pop();
14227 if (iszero(R_C_simplified_toCheckIfZero)) {
14228 flipSignOFQSoCIsNotZero = true;
14229 } else {
14230 C_CHECKED_AS_NOT_ZERO = true;
14231 }
14232 }
14233 push(R_C);
14234 push(R_3_a);
14235 multiply();
14236 R_3_a_C = pop();
14237 push(R_3_a_C);
14238 push_integer(2);
14239 multiply();
14240 R_6_a_C = pop();
14241 push(imaginaryunit);
14242 push_integer(3);
14243 push_rational(1, 2);
14244 power();
14245 multiply();
14246 i_sqrt3 = pop();
14247 push_integer(1);
14248 push(i_sqrt3);
14249 add();
14250 one_plus_i_sqrt3 = pop();
14251 push_integer(1);
14252 push(i_sqrt3);
14253 subtract();
14254 one_minus_i_sqrt3 = pop();
14255 push(R_C);
14256 push(R_3_a);
14257 divide();
14258 R_C_over_3a = pop();
14259 push(R_m_b_over_3a);
14260 push(R_C_over_3a);
14261 negate();
14262 push(R_DELTA0);
14263 push(R_3_a_C);
14264 divide();
14265 negate();
14266 add();
14267 add();
14268 simplify();
14269 push(R_m_b_over_3a);
14270 push(R_C_over_3a);
14271 push(one_plus_i_sqrt3);
14272 multiply();
14273 push_integer(2);
14274 divide();
14275 push(one_minus_i_sqrt3);
14276 push(R_DELTA0);
14277 multiply();
14278 push(R_6_a_C);
14279 divide();
14280 add();
14281 add();
14282 simplify();
14283 push(R_m_b_over_3a);
14284 push(R_C_over_3a);
14285 push(one_minus_i_sqrt3);
14286 multiply();
14287 push_integer(2);
14288 divide();
14289 push(one_plus_i_sqrt3);
14290 push(R_DELTA0);
14291 multiply();
14292 push(R_6_a_C);
14293 divide();
14294 add();
14295 add();
14296 simplify();
14297 restore();
14298 return;
14299 }
14300 tos -= n;
14301 return restore();
14302 };
14303
14304 T_INTEGER = 1001;
14305
14306 T_DOUBLE = 1002;
14307
14308 T_SYMBOL = 1003;
14309
14310 T_FUNCTION = 1004;
14311
14312 T_NEWLINE = 1006;
14313
14314 T_STRING = 1007;
14315
14316 T_GTEQ = 1008;
14317
14318 T_LTEQ = 1009;
14319
14320 T_EQ = 1010;
14321
14322 token = "";
14323
14324 newline_flag = 0;
14325
14326 meta_mode = 0;
14327
14328 input_str = 0;
14329
14330 scan_str = 0;
14331
14332 token_str = 0;
14333
14334 token_buf = 0;
14335
14336 scanned = "";
14337
14338 scan = function(s) {
14339 if (DEBUG) {
14340 console.log("#### scanning " + s);
14341 }
14342 scanned = s;
14343 meta_mode = 0;
14344 expanding++;
14345 input_str = 0;
14346 scan_str = 0;
14347 get_next_token();
14348 if (token === "") {
14349 push(symbol(NIL));
14350 expanding--;
14351 return 0;
14352 }
14353 scan_stmt();
14354 expanding--;
14355 return token_str - input_str;
14356 };
14357
14358 scan_meta = function(s) {
14359 scanned = s;
14360 meta_mode = 1;
14361 expanding++;
14362 input_str = 0;
14363 scan_str = 0;
14364 get_next_token();
14365 if (token === "") {
14366 push(symbol(NIL));
14367 expanding--;
14368 return 0;
14369 }
14370 scan_stmt();
14371 expanding--;
14372 return token_str - input_str;
14373 };
14374
14375 scan_stmt = function() {
14376 scan_relation();
14377 if (token === '=') {
14378 get_next_token();
14379 push_symbol(SETQ);
14380 swap();
14381 scan_relation();
14382 return list(3);
14383 }
14384 };
14385
14386 scan_relation = function() {
14387 scan_expression();
14388 switch (token) {
14389 case T_EQ:
14390 push_symbol(TESTEQ);
14391 swap();
14392 get_next_token();
14393 scan_expression();
14394 return list(3);
14395 case T_LTEQ:
14396 push_symbol(TESTLE);
14397 swap();
14398 get_next_token();
14399 scan_expression();
14400 return list(3);
14401 case T_GTEQ:
14402 push_symbol(TESTGE);
14403 swap();
14404 get_next_token();
14405 scan_expression();
14406 return list(3);
14407 case '<':
14408 push_symbol(TESTLT);
14409 swap();
14410 get_next_token();
14411 scan_expression();
14412 return list(3);
14413 case '>':
14414 push_symbol(TESTGT);
14415 swap();
14416 get_next_token();
14417 scan_expression();
14418 return list(3);
14419 }
14420 };
14421
14422 scan_expression = function() {
14423 var h;
14424 h = tos;
14425 switch (token) {
14426 case '+':
14427 get_next_token();
14428 scan_term();
14429 break;
14430 case '-':
14431 get_next_token();
14432 scan_term();
14433 negate();
14434 break;
14435 default:
14436 scan_term();
14437 }
14438 while (newline_flag === 0 && (token === '+' || token === '-')) {
14439 if (token === '+') {
14440 get_next_token();
14441 scan_term();
14442 } else {
14443 get_next_token();
14444 scan_term();
14445 negate();
14446 }
14447 }
14448 if (tos - h > 1) {
14449 list(tos - h);
14450 push_symbol(ADD);
14451 swap();
14452 return cons();
14453 }
14454 };
14455
14456 is_factor = function() {
14457 switch (token) {
14458 case '*':
14459 case '/':
14460 return 1;
14461 case '(':
14462 case T_SYMBOL:
14463 case T_FUNCTION:
14464 case T_INTEGER:
14465 case T_DOUBLE:
14466 case T_STRING:
14467 if (newline_flag) {
14468 scan_str = token_str;
14469 return 0;
14470 } else {
14471 return 1;
14472 }
14473 }
14474 return 0;
14475 };
14476
14477 scan_term = function() {
14478 var h;
14479 h = tos;
14480 scan_power();
14481 if (tos > h && isrational(stack[tos - 1]) && equaln(stack[tos - 1], 1)) {
14482 pop();
14483 }
14484 while (is_factor()) {
14485 if (token === '*') {
14486 get_next_token();
14487 scan_power();
14488 } else if (token === '/') {
14489 get_next_token();
14490 scan_power();
14491 inverse();
14492 } else {
14493 scan_power();
14494 }
14495 if (tos > h + 1 && isnum(stack[tos - 2]) && isnum(stack[tos - 1])) {
14496 multiply();
14497 }
14498 if (tos > h && isrational(stack[tos - 1]) && equaln(stack[tos - 1], 1)) {
14499 pop();
14500 }
14501 }
14502 if (h === tos) {
14503 return push_integer(1);
14504 } else if (tos - h > 1) {
14505 list(tos - h);
14506 push_symbol(MULTIPLY);
14507 swap();
14508 return cons();
14509 }
14510 };
14511
14512 scan_power = function() {
14513 scan_factor();
14514 if (token === '^') {
14515 get_next_token();
14516 push_symbol(POWER);
14517 swap();
14518 scan_power();
14519 return list(3);
14520 }
14521 };
14522
14523 scan_factor = function() {
14524 var h, results;
14525 h = tos;
14526 if (token === '(') {
14527 scan_subexpr();
14528 } else if (token === T_SYMBOL) {
14529 scan_symbol();
14530 } else if (token === T_FUNCTION) {
14531 scan_function_call();
14532 } else if (token === T_INTEGER) {
14533 bignum_scan_integer(token_buf);
14534 get_next_token();
14535 } else if (token === T_DOUBLE) {
14536 bignum_scan_float(token_buf);
14537 get_next_token();
14538 } else if (token === T_STRING) {
14539 scan_string();
14540 } else {
14541 scan_error("syntax error");
14542 }
14543 if (token === '[') {
14544 get_next_token();
14545 push_symbol(INDEX);
14546 swap();
14547 scan_expression();
14548 while (token === ',') {
14549 get_next_token();
14550 scan_expression();
14551 }
14552 if (token !== ']') {
14553 scan_error("] expected");
14554 }
14555 get_next_token();
14556 list(tos - h);
14557 }
14558 results = [];
14559 while (token === '!') {
14560 get_next_token();
14561 push_symbol(FACTORIAL);
14562 swap();
14563 results.push(list(2));
14564 }
14565 return results;
14566 };
14567
14568 scan_symbol = function() {
14569 if (token !== T_SYMBOL) {
14570 scan_error("symbol expected");
14571 }
14572 if (meta_mode && token_buf.length === 1) {
14573 switch (token_buf[0]) {
14574 case 'a':
14575 push(symbol(METAA));
14576 break;
14577 case 'b':
14578 push(symbol(METAB));
14579 break;
14580 case 'x':
14581 push(symbol(METAX));
14582 break;
14583 default:
14584 push(usr_symbol(token_buf));
14585 }
14586 } else {
14587 push(usr_symbol(token_buf));
14588 }
14589 return get_next_token();
14590 };
14591
14592 scan_string = function() {
14593 new_string(token_buf);
14594 return get_next_token();
14595 };
14596
14597 scan_function_call = function() {
14598 var n, p;
14599 n = 1;
14600 p = new U();
14601 p = usr_symbol(token_buf);
14602 push(p);
14603 get_next_token();
14604 get_next_token();
14605 if (token !== ')') {
14606 scan_stmt();
14607 n++;
14608 while (token === ',') {
14609 get_next_token();
14610 scan_stmt();
14611 n++;
14612 }
14613 }
14614 if (token !== ')') {
14615 scan_error(") expected");
14616 }
14617 get_next_token();
14618 return list(n);
14619 };
14620
14621 scan_subexpr = function() {
14622 var n;
14623 n = 0;
14624 if (token !== '(') {
14625 scan_error("( expected");
14626 }
14627 get_next_token();
14628 scan_stmt();
14629 if (token === ',') {
14630 n = 1;
14631 while (token === ',') {
14632 get_next_token();
14633 scan_stmt();
14634 n++;
14635 }
14636 build_tensor(n);
14637 }
14638 if (token !== ')') {
14639 scan_error(") expected");
14640 }
14641 return get_next_token();
14642 };
14643
14644 scan_error = function(errmsg) {
14645 errorMessage = "";
14646 while (input_str !== scan_str) {
14647 if ((scanned[input_str] === '\n' || scanned[input_str] === '\r') && input_str + 1 === scan_str) {
14648 break;
14649 }
14650 errorMessage += scanned[input_str++];
14651 }
14652 errorMessage += " ? ";
14653 while (scanned[input_str] && (scanned[input_str] !== '\n' && scanned[input_str] !== '\r')) {
14654 errorMessage += scanned[input_str++];
14655 }
14656 errorMessage += '\n';
14657 return stop(errmsg);
14658 };
14659
14660 build_tensor = function(n) {
14661 var ac, i, ref1;
14662 i = 0;
14663 save();
14664 p2 = alloc_tensor(n);
14665 p2.tensor.ndim = 1;
14666 p2.tensor.dim[0] = n;
14667 for (i = ac = 0, ref1 = n; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
14668 p2.tensor.elem[i] = stack[tos - n + i];
14669 }
14670 if (p2.tensor.nelem !== p2.tensor.elem.length) {
14671 console.log("something wrong in tensor dimensions");
14672 debugger;
14673 }
14674 tos -= n;
14675 push(p2);
14676 return restore();
14677 };
14678
14679 get_next_token = function() {
14680 newline_flag = 0;
14681 while (1.) {
14682 get_token();
14683 if (token !== T_NEWLINE) {
14684 break;
14685 }
14686 newline_flag = 1;
14687 }
14688 if (DEBUG) {
14689 return console.log("get_next_token token: " + token);
14690 }
14691 };
14692
14693 get_token = function() {
14694 while (isspace(scanned[scan_str])) {
14695 if (scanned[scan_str] === '\n' || scanned[scan_str] === '\r') {
14696 token = T_NEWLINE;
14697 scan_str++;
14698 return;
14699 }
14700 scan_str++;
14701 }
14702 token_str = scan_str;
14703 if (scan_str === scanned.length) {
14704 token = "";
14705 return;
14706 }
14707 if (isdigit(scanned[scan_str]) || scanned[scan_str] === '.') {
14708 while (isdigit(scanned[scan_str])) {
14709 scan_str++;
14710 }
14711 if (scanned[scan_str] === '.') {
14712 scan_str++;
14713 while (isdigit(scanned[scan_str])) {
14714 scan_str++;
14715 }
14716 if (scanned[scan_str] === 'e' && (scanned[scan_str + 1] === '+' || scanned[scan_str + 1] === '-' || isdigit(scanned[scan_str + 1]))) {
14717 scan_str += 2;
14718 while (isdigit(scanned[scan_str])) {
14719 scan_str++;
14720 }
14721 }
14722 token = T_DOUBLE;
14723 } else {
14724 token = T_INTEGER;
14725 }
14726 update_token_buf(token_str, scan_str);
14727 return;
14728 }
14729 if (isalpha(scanned[scan_str])) {
14730 while (isalnum(scanned[scan_str])) {
14731 scan_str++;
14732 }
14733 if (scanned[scan_str] === '(') {
14734 token = T_FUNCTION;
14735 } else {
14736 token = T_SYMBOL;
14737 }
14738 update_token_buf(token_str, scan_str);
14739 return;
14740 }
14741 if (scanned[scan_str] === '"') {
14742 scan_str++;
14743 while (scanned[scan_str] !== '"') {
14744 if (scan_str === scanned.length || scanned[scan_str] === '\n' || scanned[scan_str] === '\r') {
14745 scan_error("runaway string");
14746 }
14747 scan_str++;
14748 }
14749 scan_str++;
14750 token = T_STRING;
14751 update_token_buf(token_str + 1, scan_str - 1);
14752 return;
14753 }
14754 if (scanned[scan_str] === '#' || scanned[scan_str] === '-' && scanned[scan_str + 1] === '-') {
14755 while (scanned[scan_str] && scanned[scan_str] !== '\n' && scanned[scan_str] !== '\r') {
14756 scan_str++;
14757 }
14758 if (scanned[scan_str]) {
14759 scan_str++;
14760 }
14761 token = T_NEWLINE;
14762 return;
14763 }
14764 if (scanned[scan_str] === '=' && scanned[scan_str + 1] === '=') {
14765 scan_str += 2;
14766 token = T_EQ;
14767 return;
14768 }
14769 if (scanned[scan_str] === '<' && scanned[scan_str + 1] === '=') {
14770 scan_str += 2;
14771 token = T_LTEQ;
14772 return;
14773 }
14774 if (scanned[scan_str] === '>' && scanned[scan_str + 1] === '=') {
14775 scan_str += 2;
14776 token = T_GTEQ;
14777 return;
14778 }
14779 return token = scanned[scan_str++];
14780 };
14781
14782 update_token_buf = function(a, b) {
14783 return token_buf = scanned.substring(a, b);
14784 };
14785
14786 $.scan = scan;
14787
14788 Eval_sgn = function() {
14789 push(cadr(p1));
14790 Eval();
14791 return sgn();
14792 };
14793
14794 sgn = function() {
14795 save();
14796 yysgn();
14797 return restore();
14798 };
14799
14800 yysgn = function() {
14801 p1 = pop();
14802 if (isdouble(p1)) {
14803 if (p1.d > 0) {
14804 push_integer(1);
14805 return;
14806 } else {
14807 if (p1.d === 0) {
14808 push_integer(1);
14809 return;
14810 } else {
14811 push_integer(-1);
14812 return;
14813 }
14814 }
14815 }
14816 if (isrational(p1)) {
14817 if (MSIGN(mmul(p1.q.a, p1.q.b)) === -1) {
14818 push_integer(-1);
14819 return;
14820 } else {
14821 if (MZERO(mmul(p1.q.a, p1.q.b))) {
14822 push_integer(0);
14823 return;
14824 } else {
14825 push_integer(1);
14826 return;
14827 }
14828 }
14829 }
14830 if (iscomplexnumber(p1)) {
14831 push_integer(-1);
14832 push(p1);
14833 absval();
14834 power();
14835 push(p1);
14836 multiply();
14837 return;
14838 }
14839 if (isnegativeterm(p1)) {
14840 push_symbol(SGN);
14841 push(p1);
14842 negate();
14843 list(2);
14844 push_integer(-1);
14845 multiply();
14846 return;
14847 }
14848
14849 /*
14850 push_integer(2)
14851 push(p1)
14852 heaviside()
14853 multiply()
14854 push_integer(-1)
14855 add()
14856 */
14857 push_symbol(SGN);
14858 push(p1);
14859 return list(2);
14860 };
14861
14862 Eval_shape = function() {
14863 push(cadr(p1));
14864 Eval();
14865 return shape();
14866 };
14867
14868 shape = function() {
14869 var ac, ad, ai, an, i, ndim, ref1, ref2, t;
14870 i = 0;
14871 ndim = 0;
14872 t = 0;
14873 ai = [];
14874 an = [];
14875 for (i = ac = 0, ref1 = MAXDIM; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
14876 ai[i] = 0;
14877 an[i] = 0;
14878 }
14879 save();
14880 p1 = pop();
14881 if (!istensor(p1)) {
14882 if (!iszero(p1)) {
14883 stop("transpose: tensor expected, 1st arg is not a tensor");
14884 }
14885 push(zero);
14886 restore();
14887 return;
14888 }
14889 ndim = p1.tensor.ndim;
14890 p2 = alloc_tensor(ndim);
14891 p2.tensor.ndim = 1;
14892 p2.tensor.dim[0] = ndim;
14893 for (i = ad = 0, ref2 = ndim; 0 <= ref2 ? ad < ref2 : ad > ref2; i = 0 <= ref2 ? ++ad : --ad) {
14894 push_integer(p1.tensor.dim[i]);
14895 p2.tensor.elem[i] = pop();
14896 }
14897 push(p2);
14898 return restore();
14899 };
14900
14901
14902 /*
14903 Simplify factorials
14904
14905 The following script
14906
14907 F(n,k) = k binomial(n,k)
14908 (F(n,k) + F(n,k-1)) / F(n+1,k)
14909
14910 generates
14911
14912 k! n! n! (1 - k + n)! k! n!
14913 -------------------- + -------------------- - ----------------------
14914 (-1 + k)! (1 + n)! (1 + n)! (-k + n)! k (-1 + k)! (1 + n)!
14915
14916 Simplify each term to get
14917
14918 k 1 - k + n 1
14919 ------- + ----------- - -------
14920 1 + n 1 + n 1 + n
14921
14922 Then simplify the sum to get
14923
14924 n
14925 -------
14926 1 + n
14927 */
14928
14929 Eval_simfac = function() {
14930 push(cadr(p1));
14931 Eval();
14932 return simfac();
14933 };
14934
14935 simfac = function() {
14936 var h;
14937 h = 0;
14938 save();
14939 p1 = pop();
14940 if (car(p1) === symbol(ADD)) {
14941 h = tos;
14942 p1 = cdr(p1);
14943 while (p1 !== symbol(NIL)) {
14944 push(car(p1));
14945 simfac_term();
14946 p1 = cdr(p1);
14947 }
14948 add_all(tos - h);
14949 } else {
14950 push(p1);
14951 simfac_term();
14952 }
14953 return restore();
14954 };
14955
14956
14957 /*
14958 void
14959 simfac(void)
14960 {
14961 int h
14962 save()
14963 p1 = pop()
14964 if (car(p1) == symbol(ADD)) {
14965 h = tos
14966 p1 = cdr(p1)
14967 while (p1 != symbol(NIL)) {
14968 push(car(p1))
14969 simfac_term()
14970 p1 = cdr(p1)
14971 }
14972 addk(tos - h)
14973 p1 = pop()
14974 if (find(p1, symbol(FACTORIAL))) {
14975 push(p1)
14976 if (car(p1) == symbol(ADD)) {
14977 Condense()
14978 simfac_term()
14979 }
14980 }
14981 } else {
14982 push(p1)
14983 simfac_term()
14984 }
14985 restore()
14986 }
14987
14988 #endif
14989 */
14990
14991 simfac_term = function() {
14992 var doNothing, h;
14993 h = 0;
14994 save();
14995 p1 = pop();
14996 if (car(p1) !== symbol(MULTIPLY)) {
14997 push(p1);
14998 restore();
14999 return;
15000 }
15001 h = tos;
15002 p1 = cdr(p1);
15003 while (p1 !== symbol(NIL)) {
15004 push(car(p1));
15005 p1 = cdr(p1);
15006 }
15007 while (yysimfac(h)) {
15008 doNothing = 1;
15009 }
15010 multiply_all_noexpand(tos - h);
15011 return restore();
15012 };
15013
15014 yysimfac = function(h) {
15015 var ac, ad, i, j, ref1, ref2, ref3, ref4;
15016 i = 0;
15017 j = 0;
15018 for (i = ac = ref1 = h, ref2 = tos; ref1 <= ref2 ? ac < ref2 : ac > ref2; i = ref1 <= ref2 ? ++ac : --ac) {
15019 p1 = stack[i];
15020 for (j = ad = ref3 = h, ref4 = tos; ref3 <= ref4 ? ad < ref4 : ad > ref4; j = ref3 <= ref4 ? ++ad : --ad) {
15021 if (i === j) {
15022 continue;
15023 }
15024 p2 = stack[j];
15025 if (car(p1) === symbol(FACTORIAL) && car(p2) === symbol(POWER) && isminusone(caddr(p2)) && equal(cadr(p1), cadr(p2))) {
15026 push(cadr(p1));
15027 push(one);
15028 subtract();
15029 factorial();
15030 stack[i] = pop();
15031 stack[j] = one;
15032 return 1;
15033 }
15034 if (car(p2) === symbol(POWER) && isminusone(caddr(p2)) && caadr(p2) === symbol(FACTORIAL) && equal(p1, cadadr(p2))) {
15035 push(p1);
15036 push_integer(-1);
15037 add();
15038 factorial();
15039 reciprocate();
15040 stack[i] = pop();
15041 stack[j] = one;
15042 return 1;
15043 }
15044 if (car(p2) === symbol(FACTORIAL)) {
15045 push(p1);
15046 push(cadr(p2));
15047 subtract();
15048 p3 = pop();
15049 if (isplusone(p3)) {
15050 push(p1);
15051 factorial();
15052 stack[i] = pop();
15053 stack[j] = one;
15054 return 1;
15055 }
15056 }
15057 if (car(p1) === symbol(POWER) && isminusone(caddr(p1)) && car(p2) === symbol(POWER) && isminusone(caddr(p2)) && caadr(p2) === symbol(FACTORIAL)) {
15058 push(cadr(p1));
15059 push(cadr(cadr(p2)));
15060 subtract();
15061 p3 = pop();
15062 if (isplusone(p3)) {
15063 push(cadr(p1));
15064 factorial();
15065 reciprocate();
15066 stack[i] = pop();
15067 stack[j] = one;
15068 return 1;
15069 }
15070 }
15071 if (car(p1) === symbol(FACTORIAL) && car(p2) === symbol(POWER) && isminusone(caddr(p2)) && caadr(p2) === symbol(FACTORIAL)) {
15072 push(cadr(p1));
15073 push(cadr(cadr(p2)));
15074 subtract();
15075 p3 = pop();
15076 if (isplusone(p3)) {
15077 stack[i] = cadr(p1);
15078 stack[j] = one;
15079 return 1;
15080 }
15081 if (isminusone(p3)) {
15082 push(cadr(cadr(p2)));
15083 reciprocate();
15084 stack[i] = pop();
15085 stack[j] = one;
15086 return 1;
15087 }
15088 if (equaln(p3, 2)) {
15089 stack[i] = cadr(p1);
15090 push(cadr(p1));
15091 push_integer(-1);
15092 add();
15093 stack[j] = pop();
15094 return 1;
15095 }
15096 if (equaln(p3, -2)) {
15097 push(cadr(cadr(p2)));
15098 reciprocate();
15099 stack[i] = pop();
15100 push(cadr(cadr(p2)));
15101 push_integer(-1);
15102 add();
15103 reciprocate();
15104 stack[j] = pop();
15105 return 1;
15106 }
15107 }
15108 }
15109 }
15110 return 0;
15111 };
15112
15113 Eval_simplify = function() {
15114 push(cadr(p1));
15115 Eval();
15116 return simplify();
15117 };
15118
15119 simplify = function() {
15120 save();
15121 simplify_main();
15122 return restore();
15123 };
15124
15125 simplify_main = function() {
15126 p1 = pop();
15127 if (istensor(p1)) {
15128 simplify_tensor();
15129 return;
15130 }
15131 if (Find(p1, symbol(FACTORIAL))) {
15132 push(p1);
15133 simfac();
15134 p2 = pop();
15135 push(p1);
15136 rationalize();
15137 simfac();
15138 p3 = pop();
15139 if (count(p2) < count(p3)) {
15140 p1 = p2;
15141 } else {
15142 p1 = p3;
15143 }
15144 }
15145 f1();
15146 f2();
15147 f3();
15148 f4();
15149 f5();
15150 f9();
15151 return push(p1);
15152 };
15153
15154 simplify_tensor = function() {
15155 var ac, ad, i, ref1, ref2;
15156 i = 0;
15157 p2 = alloc_tensor(p1.tensor.nelem);
15158 p2.tensor.ndim = p1.tensor.ndim;
15159 for (i = ac = 0, ref1 = p1.tensor.ndim; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
15160 p2.tensor.dim[i] = p1.tensor.dim[i];
15161 }
15162 for (i = ad = 0, ref2 = p1.tensor.nelem; 0 <= ref2 ? ad < ref2 : ad > ref2; i = 0 <= ref2 ? ++ad : --ad) {
15163 push(p1.tensor.elem[i]);
15164 simplify();
15165 p2.tensor.elem[i] = pop();
15166 }
15167 if (p2.tensor.nelem !== p2.tensor.elem.length) {
15168 console.log("something wrong in tensor dimensions");
15169 debugger;
15170 }
15171 if (iszero(p2)) {
15172 p2 = zero;
15173 }
15174 return push(p2);
15175 };
15176
15177 count = function(p) {
15178 var n;
15179 if (iscons(p)) {
15180 n = 0;
15181 while (iscons(p)) {
15182 n += count(car(p)) + 1;
15183 p = cdr(p);
15184 }
15185 } else {
15186 n = 1;
15187 }
15188 return n;
15189 };
15190
15191 f1 = function() {
15192 if (car(p1) !== symbol(ADD)) {
15193 return;
15194 }
15195 push(p1);
15196 rationalize();
15197 p2 = pop();
15198 if (count(p2) < count(p1)) {
15199 return p1 = p2;
15200 }
15201 };
15202
15203 f2 = function() {
15204 if (car(p1) !== symbol(ADD)) {
15205 return;
15206 }
15207 push(p1);
15208 Condense();
15209 p2 = pop();
15210 if (count(p2) <= count(p1)) {
15211 return p1 = p2;
15212 }
15213 };
15214
15215 f3 = function() {
15216 push(p1);
15217 rationalize();
15218 negate();
15219 rationalize();
15220 negate();
15221 rationalize();
15222 p2 = pop();
15223 if (count(p2) < count(p1)) {
15224 return p1 = p2;
15225 }
15226 };
15227
15228 f4 = function() {
15229 if (iszero(p1)) {
15230 return;
15231 }
15232 push(p1);
15233 rationalize();
15234 inverse();
15235 rationalize();
15236 inverse();
15237 rationalize();
15238 p2 = pop();
15239 if (count(p2) < count(p1)) {
15240 return p1 = p2;
15241 }
15242 };
15243
15244 simplify_trig = function() {
15245 save();
15246 p1 = pop();
15247 f5();
15248 push(p1);
15249 return restore();
15250 };
15251
15252 f5 = function() {
15253 if (Find(p1, symbol(SIN)) === 0 && Find(p1, symbol(COS)) === 0) {
15254 return;
15255 }
15256 p2 = p1;
15257 trigmode = 1;
15258 push(p2);
15259 Eval();
15260 p3 = pop();
15261 trigmode = 2;
15262 push(p2);
15263 Eval();
15264 p4 = pop();
15265 trigmode = 0;
15266 if (count(p4) < count(p3) || nterms(p4) < nterms(p3)) {
15267 p3 = p4;
15268 }
15269 if (count(p3) < count(p1) || nterms(p3) < nterms(p1)) {
15270 return p1 = p3;
15271 }
15272 };
15273
15274 f9 = function() {
15275 if (car(p1) !== symbol(ADD)) {
15276 return;
15277 }
15278 push_integer(0);
15279 p2 = cdr(p1);
15280 while (iscons(p2)) {
15281 push(car(p2));
15282 simplify();
15283 add();
15284 p2 = cdr(p2);
15285 }
15286 p2 = pop();
15287 if (count(p2) < count(p1)) {
15288 return p1 = p2;
15289 }
15290 };
15291
15292 nterms = function(p) {
15293 if (car(p) !== symbol(ADD)) {
15294 return 1;
15295 } else {
15296 return length(p) - 1;
15297 }
15298 };
15299
15300 Eval_sin = function() {
15301 push(cadr(p1));
15302 Eval();
15303 return sine();
15304 };
15305
15306 sine = function() {
15307 save();
15308 p1 = pop();
15309 if (car(p1) === symbol(ADD)) {
15310 sine_of_angle_sum();
15311 } else {
15312 sine_of_angle();
15313 }
15314 return restore();
15315 };
15316
15317 sine_of_angle_sum = function() {
15318 p2 = cdr(p1);
15319 while (iscons(p2)) {
15320 p4 = car(p2);
15321 if (isnpi(p4)) {
15322 push(p1);
15323 push(p4);
15324 subtract();
15325 p3 = pop();
15326 push(p3);
15327 sine();
15328 push(p4);
15329 cosine();
15330 multiply();
15331 push(p3);
15332 cosine();
15333 push(p4);
15334 sine();
15335 multiply();
15336 add();
15337 return;
15338 }
15339 p2 = cdr(p2);
15340 }
15341 return sine_of_angle();
15342 };
15343
15344 sine_of_angle = function() {
15345 var d, n;
15346 if (car(p1) === symbol(ARCSIN)) {
15347 push(cadr(p1));
15348 return;
15349 }
15350 if (isdouble(p1)) {
15351 d = Math.sin(p1.d);
15352 if (Math.abs(d) < 1e-10) {
15353 d = 0.0;
15354 }
15355 push_double(d);
15356 return;
15357 }
15358 if (isnegative(p1)) {
15359 push(p1);
15360 negate();
15361 sine();
15362 negate();
15363 return;
15364 }
15365 if (car(p1) === symbol(ARCTAN)) {
15366 push(cadr(p1));
15367 push_integer(1);
15368 push(cadr(p1));
15369 push_integer(2);
15370 power();
15371 add();
15372 push_rational(-1, 2);
15373 power();
15374 multiply();
15375 return;
15376 }
15377 push(p1);
15378 push_integer(180);
15379 multiply();
15380 push_symbol(PI);
15381 divide();
15382 n = pop_integer();
15383 if (n < 0 || n === 0x80000000) {
15384 push(symbol(SIN));
15385 push(p1);
15386 list(2);
15387 return;
15388 }
15389 switch (n % 360) {
15390 case 0:
15391 case 180:
15392 return push_integer(0);
15393 case 30:
15394 case 150:
15395 return push_rational(1, 2);
15396 case 210:
15397 case 330:
15398 return push_rational(-1, 2);
15399 case 45:
15400 case 135:
15401 push_rational(1, 2);
15402 push_integer(2);
15403 push_rational(1, 2);
15404 power();
15405 return multiply();
15406 case 225:
15407 case 315:
15408 push_rational(-1, 2);
15409 push_integer(2);
15410 push_rational(1, 2);
15411 power();
15412 return multiply();
15413 case 60:
15414 case 120:
15415 push_rational(1, 2);
15416 push_integer(3);
15417 push_rational(1, 2);
15418 power();
15419 return multiply();
15420 case 240:
15421 case 300:
15422 push_rational(-1, 2);
15423 push_integer(3);
15424 push_rational(1, 2);
15425 power();
15426 return multiply();
15427 case 90:
15428 return push_integer(1);
15429 case 270:
15430 return push_integer(-1);
15431 default:
15432 push(symbol(SIN));
15433 push(p1);
15434 return list(2);
15435 }
15436 };
15437
15438 Eval_sinh = function() {
15439 push(cadr(p1));
15440 Eval();
15441 return ysinh();
15442 };
15443
15444 ysinh = function() {
15445 save();
15446 yysinh();
15447 return restore();
15448 };
15449
15450 yysinh = function() {
15451 var d;
15452 d = 0.0;
15453 p1 = pop();
15454 if (car(p1) === symbol(ARCSINH)) {
15455 push(cadr(p1));
15456 return;
15457 }
15458 if (isdouble(p1)) {
15459 d = Math.sinh(p1.d);
15460 if (Math.abs(d) < 1e-10) {
15461 d = 0.0;
15462 }
15463 push_double(d);
15464 return;
15465 }
15466 if (iszero(p1)) {
15467 push(zero);
15468 return;
15469 }
15470 push_symbol(SINH);
15471 push(p1);
15472 return list(2);
15473 };
15474
15475
15476 /*
15477 Substitute new expr for old expr in expr.
15478
15479 Input: push expr
15480
15481 push old expr
15482
15483 push new expr
15484
15485 Output: Result on stack
15486 */
15487
15488 subst = function() {
15489 var ac, ad, i, ref1, ref2;
15490 i = 0;
15491 save();
15492 p3 = pop();
15493 p2 = pop();
15494 if (p2 === symbol(NIL) || p3 === symbol(NIL)) {
15495 restore();
15496 return;
15497 }
15498 p1 = pop();
15499 if (istensor(p1)) {
15500 p4 = alloc_tensor(p1.tensor.nelem);
15501 p4.tensor.ndim = p1.tensor.ndim;
15502 for (i = ac = 0, ref1 = p1.tensor.ndim; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
15503 p4.tensor.dim[i] = p1.tensor.dim[i];
15504 }
15505 for (i = ad = 0, ref2 = p1.tensor.nelem; 0 <= ref2 ? ad < ref2 : ad > ref2; i = 0 <= ref2 ? ++ad : --ad) {
15506 push(p1.tensor.elem[i]);
15507 push(p2);
15508 push(p3);
15509 subst();
15510 p4.tensor.elem[i] = pop();
15511 if (p4.tensor.nelem !== p4.tensor.elem.length) {
15512 console.log("something wrong in tensor dimensions");
15513 debugger;
15514 }
15515 }
15516 push(p4);
15517 } else if (equal(p1, p2)) {
15518 push(p3);
15519 } else if (iscons(p1)) {
15520 push(car(p1));
15521 push(p2);
15522 push(p3);
15523 subst();
15524 push(cdr(p1));
15525 push(p2);
15526 push(p3);
15527 subst();
15528 cons();
15529 } else {
15530 push(p1);
15531 }
15532 return restore();
15533 };
15534
15535 Eval_tan = function() {
15536 push(cadr(p1));
15537 Eval();
15538 return tangent();
15539 };
15540
15541 tangent = function() {
15542 save();
15543 yytangent();
15544 return restore();
15545 };
15546
15547 yytangent = function() {
15548 var d, n;
15549 n = 0;
15550 d = 0.0;
15551 p1 = pop();
15552 if (car(p1) === symbol(ARCTAN)) {
15553 push(cadr(p1));
15554 return;
15555 }
15556 if (isdouble(p1)) {
15557 d = Math.tan(p1.d);
15558 if (Math.abs(d) < 1e-10) {
15559 d = 0.0;
15560 }
15561 push_double(d);
15562 return;
15563 }
15564 if (isnegative(p1)) {
15565 push(p1);
15566 negate();
15567 tangent();
15568 negate();
15569 return;
15570 }
15571 push(p1);
15572 push_integer(180);
15573 multiply();
15574 push_symbol(PI);
15575 divide();
15576 n = pop_integer();
15577 if (n < 0 || n === 0x80000000) {
15578 push(symbol(TAN));
15579 push(p1);
15580 list(2);
15581 return;
15582 }
15583 switch (n % 360) {
15584 case 0:
15585 case 180:
15586 return push_integer(0);
15587 case 30:
15588 case 210:
15589 push_rational(1, 3);
15590 push_integer(3);
15591 push_rational(1, 2);
15592 power();
15593 return multiply();
15594 case 150:
15595 case 330:
15596 push_rational(-1, 3);
15597 push_integer(3);
15598 push_rational(1, 2);
15599 power();
15600 return multiply();
15601 case 45:
15602 case 225:
15603 return push_integer(1);
15604 case 135:
15605 case 315:
15606 return push_integer(-1);
15607 case 60:
15608 case 240:
15609 push_integer(3);
15610 push_rational(1, 2);
15611 return power();
15612 case 120:
15613 case 300:
15614 push_integer(3);
15615 push_rational(1, 2);
15616 power();
15617 return negate();
15618 default:
15619 push(symbol(TAN));
15620 push(p1);
15621 return list(2);
15622 }
15623 };
15624
15625 Eval_tanh = function() {
15626 var d;
15627 d = 0.0;
15628 push(cadr(p1));
15629 Eval();
15630 p1 = pop();
15631 if (car(p1) === symbol(ARCTANH)) {
15632 push(cadr(p1));
15633 return;
15634 }
15635 if (isdouble(p1)) {
15636 d = Math.tanh(p1.d);
15637 if (Math.abs(d) < 1e-10) {
15638 d = 0.0;
15639 }
15640 push_double(d);
15641 return;
15642 }
15643 if (iszero(p1)) {
15644 push(zero);
15645 return;
15646 }
15647 push_symbol(TANH);
15648 push(p1);
15649 return list(2);
15650 };
15651
15652
15653 /*
15654 Taylor expansion of a function
15655
15656 push(F)
15657 push(X)
15658 push(N)
15659 push(A)
15660 taylor()
15661 */
15662
15663 Eval_taylor = function() {
15664 p1 = cdr(p1);
15665 push(car(p1));
15666 Eval();
15667 p1 = cdr(p1);
15668 push(car(p1));
15669 Eval();
15670 p2 = pop();
15671 if (p2 === symbol(NIL)) {
15672 guess();
15673 } else {
15674 push(p2);
15675 }
15676 p1 = cdr(p1);
15677 push(car(p1));
15678 Eval();
15679 p2 = pop();
15680 if (p2 === symbol(NIL)) {
15681 push_integer(24);
15682 } else {
15683 push(p2);
15684 }
15685 p1 = cdr(p1);
15686 push(car(p1));
15687 Eval();
15688 p2 = pop();
15689 if (p2 === symbol(NIL)) {
15690 push_integer(0);
15691 } else {
15692 push(p2);
15693 }
15694 return taylor();
15695 };
15696
15697 taylor = function() {
15698 var ac, i, k, ref1;
15699 i = 0;
15700 k = 0;
15701 save();
15702 p4 = pop();
15703 p3 = pop();
15704 p2 = pop();
15705 p1 = pop();
15706 push(p3);
15707 k = pop_integer();
15708 if (k === 0x80000000) {
15709 push_symbol(TAYLOR);
15710 push(p1);
15711 push(p2);
15712 push(p3);
15713 push(p4);
15714 list(5);
15715 restore();
15716 return;
15717 }
15718 push(p1);
15719 push(p2);
15720 push(p4);
15721 subst();
15722 Eval();
15723 push_integer(1);
15724 p5 = pop();
15725 for (i = ac = 1, ref1 = k; 1 <= ref1 ? ac <= ref1 : ac >= ref1; i = 1 <= ref1 ? ++ac : --ac) {
15726 push(p1);
15727 push(p2);
15728 derivative();
15729 p1 = pop();
15730 if (iszero(p1)) {
15731 break;
15732 }
15733 push(p5);
15734 push(p2);
15735 push(p4);
15736 subtract();
15737 multiply();
15738 p5 = pop();
15739 push(p1);
15740 push(p2);
15741 push(p4);
15742 subst();
15743 Eval();
15744 push(p5);
15745 multiply();
15746 push_integer(i);
15747 factorial();
15748 divide();
15749 add();
15750 }
15751 return restore();
15752 };
15753
15754 Eval_tensor = function() {
15755 var a, ac, ad, b, i, ndim, nelem, ref1, ref2;
15756 i = 0;
15757 ndim = 0;
15758 nelem = 0;
15759 if (p1.tensor.nelem !== p1.tensor.elem.length) {
15760 console.log("something wrong in tensor dimensions");
15761 debugger;
15762 }
15763 nelem = p1.tensor.nelem;
15764 ndim = p1.tensor.ndim;
15765 p2 = alloc_tensor(nelem);
15766 p2.tensor.ndim = ndim;
15767 for (i = ac = 0, ref1 = ndim; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
15768 p2.tensor.dim[i] = p1.tensor.dim[i];
15769 }
15770 a = p1.tensor.elem;
15771 b = p2.tensor.elem;
15772 if (p2.tensor.nelem !== p2.tensor.elem.length) {
15773 console.log("something wrong in tensor dimensions");
15774 debugger;
15775 }
15776 for (i = ad = 0, ref2 = nelem; 0 <= ref2 ? ad < ref2 : ad > ref2; i = 0 <= ref2 ? ++ad : --ad) {
15777 push(a[i]);
15778 Eval();
15779 b[i] = pop();
15780 }
15781 if (p1.tensor.nelem !== p1.tensor.elem.length) {
15782 console.log("something wrong in tensor dimensions");
15783 debugger;
15784 }
15785 if (p2.tensor.nelem !== p2.tensor.elem.length) {
15786 console.log("something wrong in tensor dimensions");
15787 debugger;
15788 }
15789 push(p2);
15790 return promote_tensor();
15791 };
15792
15793 tensor_plus_tensor = function() {
15794 var a, ac, ad, ae, b, c, i, ndim, nelem, ref1, ref2, ref3;
15795 i = 0;
15796 ndim = 0;
15797 nelem = 0;
15798 save();
15799 p2 = pop();
15800 p1 = pop();
15801 ndim = p1.tensor.ndim;
15802 if (ndim !== p2.tensor.ndim) {
15803 push(symbol(NIL));
15804 restore();
15805 return;
15806 }
15807 for (i = ac = 0, ref1 = ndim; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
15808 if (p1.tensor.dim[i] !== p2.tensor.dim[i]) {
15809 push(symbol(NIL));
15810 restore();
15811 return;
15812 }
15813 }
15814 nelem = p1.tensor.nelem;
15815 p3 = alloc_tensor(nelem);
15816 p3.tensor.ndim = ndim;
15817 for (i = ad = 0, ref2 = ndim; 0 <= ref2 ? ad < ref2 : ad > ref2; i = 0 <= ref2 ? ++ad : --ad) {
15818 p3.tensor.dim[i] = p1.tensor.dim[i];
15819 }
15820 a = p1.tensor.elem;
15821 b = p2.tensor.elem;
15822 c = p3.tensor.elem;
15823 for (i = ae = 0, ref3 = nelem; 0 <= ref3 ? ae < ref3 : ae > ref3; i = 0 <= ref3 ? ++ae : --ae) {
15824 push(a[i]);
15825 push(b[i]);
15826 add();
15827 c[i] = pop();
15828 }
15829 push(p3);
15830 return restore();
15831 };
15832
15833 tensor_times_scalar = function() {
15834 var a, ac, ad, b, i, ndim, nelem, ref1, ref2;
15835 i = 0;
15836 ndim = 0;
15837 nelem = 0;
15838 save();
15839 p2 = pop();
15840 p1 = pop();
15841 ndim = p1.tensor.ndim;
15842 nelem = p1.tensor.nelem;
15843 p3 = alloc_tensor(nelem);
15844 p3.tensor.ndim = ndim;
15845 for (i = ac = 0, ref1 = ndim; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
15846 p3.tensor.dim[i] = p1.tensor.dim[i];
15847 }
15848 a = p1.tensor.elem;
15849 b = p3.tensor.elem;
15850 for (i = ad = 0, ref2 = nelem; 0 <= ref2 ? ad < ref2 : ad > ref2; i = 0 <= ref2 ? ++ad : --ad) {
15851 push(a[i]);
15852 push(p2);
15853 multiply();
15854 b[i] = pop();
15855 }
15856 push(p3);
15857 return restore();
15858 };
15859
15860 scalar_times_tensor = function() {
15861 var a, ac, ad, b, i, ndim, nelem, ref1, ref2;
15862 i = 0;
15863 ndim = 0;
15864 nelem = 0;
15865 save();
15866 p2 = pop();
15867 p1 = pop();
15868 ndim = p2.tensor.ndim;
15869 nelem = p2.tensor.nelem;
15870 p3 = alloc_tensor(nelem);
15871 p3.tensor.ndim = ndim;
15872 for (i = ac = 0, ref1 = ndim; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
15873 p3.tensor.dim[i] = p2.tensor.dim[i];
15874 }
15875 a = p2.tensor.elem;
15876 b = p3.tensor.elem;
15877 for (i = ad = 0, ref2 = nelem; 0 <= ref2 ? ad < ref2 : ad > ref2; i = 0 <= ref2 ? ++ad : --ad) {
15878 push(p1);
15879 push(a[i]);
15880 multiply();
15881 b[i] = pop();
15882 }
15883 push(p3);
15884 return restore();
15885 };
15886
15887 is_square_matrix = function(p) {
15888 if (istensor(p) && p.tensor.ndim === 2 && p.tensor.dim[0] === p.tensor.dim[1]) {
15889 return 1;
15890 } else {
15891 return 0;
15892 }
15893 };
15894
15895 d_tensor_tensor = function() {
15896 var a, ac, ad, ae, b, c, i, j, ndim, nelem, ref1, ref2, ref3;
15897 i = 0;
15898 j = 0;
15899 ndim = 0;
15900 nelem = 0;
15901 ndim = p1.tensor.ndim;
15902 nelem = p1.tensor.nelem;
15903 if (ndim + 1 >= MAXDIM) {
15904 push_symbol(DERIVATIVE);
15905 push(p1);
15906 push(p2);
15907 list(3);
15908 return;
15909 }
15910 p3 = alloc_tensor(nelem * p2.tensor.nelem);
15911 p3.tensor.ndim = ndim + 1;
15912 for (i = ac = 0, ref1 = ndim; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
15913 p3.tensor.dim[i] = p1.tensor.dim[i];
15914 }
15915 p3.tensor.dim[ndim] = p2.tensor.dim[0];
15916 a = p1.tensor.elem;
15917 b = p2.tensor.elem;
15918 c = p3.tensor.elem;
15919 for (i = ad = 0, ref2 = nelem; 0 <= ref2 ? ad < ref2 : ad > ref2; i = 0 <= ref2 ? ++ad : --ad) {
15920 for (j = ae = 0, ref3 = p2.tensor.nelem; 0 <= ref3 ? ae < ref3 : ae > ref3; j = 0 <= ref3 ? ++ae : --ae) {
15921 push(a[i]);
15922 push(b[j]);
15923 derivative();
15924 c[i * p2.tensor.nelem + j] = pop();
15925 }
15926 }
15927 return push(p3);
15928 };
15929
15930 d_scalar_tensor = function() {
15931 var a, ac, b, i, ref1;
15932 p3 = alloc_tensor(p2.tensor.nelem);
15933 p3.tensor.ndim = 1;
15934 p3.tensor.dim[0] = p2.tensor.dim[0];
15935 a = p2.tensor.elem;
15936 b = p3.tensor.elem;
15937 for (i = ac = 0, ref1 = p2.tensor.nelem; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
15938 push(p1);
15939 push(a[i]);
15940 derivative();
15941 b[i] = pop();
15942 }
15943 return push(p3);
15944 };
15945
15946 d_tensor_scalar = function() {
15947 var a, ac, ad, b, i, ref1, ref2;
15948 i = 0;
15949 p3 = alloc_tensor(p1.tensor.nelem);
15950 p3.tensor.ndim = p1.tensor.ndim;
15951 for (i = ac = 0, ref1 = p1.tensor.ndim; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
15952 p3.tensor.dim[i] = p1.tensor.dim[i];
15953 }
15954 a = p1.tensor.elem;
15955 b = p3.tensor.elem;
15956 for (i = ad = 0, ref2 = p1.tensor.nelem; 0 <= ref2 ? ad < ref2 : ad > ref2; i = 0 <= ref2 ? ++ad : --ad) {
15957 push(a[i]);
15958 push(p2);
15959 derivative();
15960 b[i] = pop();
15961 }
15962 return push(p3);
15963 };
15964
15965 compare_tensors = function(p1, p2) {
15966 var ac, ad, i, ref1, ref2;
15967 i = 0;
15968 if (p1.tensor.ndim < p2.tensor.ndim) {
15969 return -1;
15970 }
15971 if (p1.tensor.ndim > p2.tensor.ndim) {
15972 return 1;
15973 }
15974 for (i = ac = 0, ref1 = p1.tensor.ndim; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
15975 if (p1.tensor.dim[i] < p2.tensor.dim[i]) {
15976 return -1;
15977 }
15978 if (p1.tensor.dim[i] > p2.tensor.dim[i]) {
15979 return 1;
15980 }
15981 }
15982 for (i = ad = 0, ref2 = p1.tensor.nelem; 0 <= ref2 ? ad < ref2 : ad > ref2; i = 0 <= ref2 ? ++ad : --ad) {
15983 if (equal(p1.tensor.elem[i], p2.tensor.elem[i])) {
15984 continue;
15985 }
15986 if (lessp(p1.tensor.elem[i], p2.tensor.elem[i])) {
15987 return -1;
15988 } else {
15989 return 1;
15990 }
15991 }
15992 return 0;
15993 };
15994
15995 power_tensor = function() {
15996 var ac, ad, i, k, n, ref1, ref2, results;
15997 i = 0;
15998 k = 0;
15999 n = 0;
16000 k = p1.tensor.ndim - 1;
16001 if (p1.tensor.dim[0] !== p1.tensor.dim[k]) {
16002 push_symbol(POWER);
16003 push(p1);
16004 push(p2);
16005 list(3);
16006 return;
16007 }
16008 push(p2);
16009 n = pop_integer();
16010 if (n === 0x80000000) {
16011 push_symbol(POWER);
16012 push(p1);
16013 push(p2);
16014 list(3);
16015 return;
16016 }
16017 if (n === 0) {
16018 if (p1.tensor.ndim !== 2) {
16019 stop("power(tensor,0) with tensor rank not equal to 2");
16020 }
16021 n = p1.tensor.dim[0];
16022 p1 = alloc_tensor(n * n);
16023 p1.tensor.ndim = 2;
16024 p1.tensor.dim[0] = n;
16025 p1.tensor.dim[1] = n;
16026 for (i = ac = 0, ref1 = n; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
16027 p1.tensor.elem[n * i + i] = one;
16028 }
16029 if (p1.tensor.nelem !== p1.tensor.elem.length) {
16030 console.log("something wrong in tensor dimensions");
16031 debugger;
16032 }
16033 push(p1);
16034 return;
16035 }
16036 if (n < 0) {
16037 n = -n;
16038 push(p1);
16039 inv();
16040 p1 = pop();
16041 }
16042 push(p1);
16043 results = [];
16044 for (i = ad = 1, ref2 = n; 1 <= ref2 ? ad < ref2 : ad > ref2; i = 1 <= ref2 ? ++ad : --ad) {
16045 push(p1);
16046 inner();
16047 if (iszero(stack[tos - 1])) {
16048 break;
16049 } else {
16050 results.push(void 0);
16051 }
16052 }
16053 return results;
16054 };
16055
16056 copy_tensor = function() {
16057 var ac, ad, i, ref1, ref2;
16058 i = 0;
16059 save();
16060 p1 = pop();
16061 p2 = alloc_tensor(p1.tensor.nelem);
16062 p2.tensor.ndim = p1.tensor.ndim;
16063 for (i = ac = 0, ref1 = p1.tensor.ndim; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
16064 p2.tensor.dim[i] = p1.tensor.dim[i];
16065 }
16066 for (i = ad = 0, ref2 = p1.tensor.nelem; 0 <= ref2 ? ad < ref2 : ad > ref2; i = 0 <= ref2 ? ++ad : --ad) {
16067 p2.tensor.elem[i] = p1.tensor.elem[i];
16068 }
16069 if (p1.tensor.nelem !== p1.tensor.elem.length) {
16070 console.log("something wrong in tensor dimensions");
16071 debugger;
16072 }
16073 if (p2.tensor.nelem !== p2.tensor.elem.length) {
16074 console.log("something wrong in tensor dimensions");
16075 debugger;
16076 }
16077 push(p2);
16078 return restore();
16079 };
16080
16081 promote_tensor = function() {
16082 var ac, ad, ae, af, ag, i, j, k, ndim, nelem, ref1, ref2, ref3, ref4, ref5;
16083 i = 0;
16084 j = 0;
16085 k = 0;
16086 nelem = 0;
16087 ndim = 0;
16088 save();
16089 p1 = pop();
16090 if (!istensor(p1)) {
16091 push(p1);
16092 restore();
16093 return;
16094 }
16095 p2 = p1.tensor.elem[0];
16096 for (i = ac = 1, ref1 = p1.tensor.nelem; 1 <= ref1 ? ac < ref1 : ac > ref1; i = 1 <= ref1 ? ++ac : --ac) {
16097 if (!compatible(p2, p1.tensor.elem[i])) {
16098 stop("Cannot promote tensor due to inconsistent tensor components.");
16099 }
16100 }
16101 if (!istensor(p2)) {
16102 push(p1);
16103 restore();
16104 return;
16105 }
16106 ndim = p1.tensor.ndim + p2.tensor.ndim;
16107 if (ndim > MAXDIM) {
16108 stop("tensor rank > 24");
16109 }
16110 nelem = p1.tensor.nelem * p2.tensor.nelem;
16111 p3 = alloc_tensor(nelem);
16112 p3.tensor.ndim = ndim;
16113 for (i = ad = 0, ref2 = p1.tensor.ndim; 0 <= ref2 ? ad < ref2 : ad > ref2; i = 0 <= ref2 ? ++ad : --ad) {
16114 p3.tensor.dim[i] = p1.tensor.dim[i];
16115 }
16116 for (j = ae = 0, ref3 = p2.tensor.ndim; 0 <= ref3 ? ae < ref3 : ae > ref3; j = 0 <= ref3 ? ++ae : --ae) {
16117 p3.tensor.dim[i + j] = p2.tensor.dim[j];
16118 }
16119 k = 0;
16120 for (i = af = 0, ref4 = p1.tensor.nelem; 0 <= ref4 ? af < ref4 : af > ref4; i = 0 <= ref4 ? ++af : --af) {
16121 p2 = p1.tensor.elem[i];
16122 for (j = ag = 0, ref5 = p2.tensor.nelem; 0 <= ref5 ? ag < ref5 : ag > ref5; j = 0 <= ref5 ? ++ag : --ag) {
16123 p3.tensor.elem[k++] = p2.tensor.elem[j];
16124 }
16125 }
16126 if (p2.tensor.nelem !== p2.tensor.elem.length) {
16127 console.log("something wrong in tensor dimensions");
16128 debugger;
16129 }
16130 if (p3.tensor.nelem !== p3.tensor.elem.length) {
16131 console.log("something wrong in tensor dimensions");
16132 debugger;
16133 }
16134 push(p3);
16135 return restore();
16136 };
16137
16138 compatible = function(p, q) {
16139 var ac, i, ref1;
16140 if (!istensor(p) && !istensor(q)) {
16141 return 1;
16142 }
16143 if (!istensor(p) || !istensor(q)) {
16144 return 0;
16145 }
16146 if (p.tensor.ndim !== q.tensor.ndim) {
16147 return 0;
16148 }
16149 for (i = ac = 0, ref1 = p.tensor.ndim; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
16150 if (p.tensor.dim[i] !== q.tensor.dim[i]) {
16151 return 0;
16152 }
16153 }
16154 return 1;
16155 };
16156
16157 Eval_test = function() {
16158 p1 = cdr(p1);
16159 while (iscons(p1)) {
16160 if (cdr(p1) === symbol(NIL)) {
16161 push(car(p1));
16162 Eval();
16163 return;
16164 }
16165 push(car(p1));
16166 Eval_predicate();
16167 p2 = pop();
16168 if (!iszero(p2)) {
16169 push(cadr(p1));
16170 Eval();
16171 return;
16172 }
16173 p1 = cddr(p1);
16174 }
16175 return push_integer(0);
16176 };
16177
16178 Eval_testeq = function() {
16179 push(cadr(p1));
16180 Eval();
16181 push(caddr(p1));
16182 Eval();
16183 subtract();
16184 p1 = pop();
16185 if (iszero(p1)) {
16186 return push_integer(1);
16187 } else {
16188 return push_integer(0);
16189 }
16190 };
16191
16192 Eval_testge = function() {
16193 if (cmp_args() >= 0) {
16194 return push_integer(1);
16195 } else {
16196 return push_integer(0);
16197 }
16198 };
16199
16200 Eval_testgt = function() {
16201 if (cmp_args() > 0) {
16202 return push_integer(1);
16203 } else {
16204 return push_integer(0);
16205 }
16206 };
16207
16208 Eval_testle = function() {
16209 if (cmp_args() <= 0) {
16210 return push_integer(1);
16211 } else {
16212 return push_integer(0);
16213 }
16214 };
16215
16216 Eval_testlt = function() {
16217 if (cmp_args() < 0) {
16218 return push_integer(1);
16219 } else {
16220 return push_integer(0);
16221 }
16222 };
16223
16224 Eval_not = function() {
16225 push(cadr(p1));
16226 Eval_predicate();
16227 p1 = pop();
16228 if (iszero(p1)) {
16229 return push_integer(1);
16230 } else {
16231 return push_integer(0);
16232 }
16233 };
16234
16235 Eval_and = function() {
16236 p1 = cdr(p1);
16237 while (iscons(p1)) {
16238 push(car(p1));
16239 Eval_predicate();
16240 p2 = pop();
16241 if (iszero(p2)) {
16242 push_integer(0);
16243 return;
16244 }
16245 p1 = cdr(p1);
16246 }
16247 return push_integer(1);
16248 };
16249
16250 Eval_or = function() {
16251 p1 = cdr(p1);
16252 while (iscons(p1)) {
16253 push(car(p1));
16254 Eval_predicate();
16255 p2 = pop();
16256 if (!iszero(p2)) {
16257 push_integer(1);
16258 return;
16259 }
16260 p1 = cdr(p1);
16261 }
16262 return push_integer(0);
16263 };
16264
16265 cmp_args = function() {
16266 var t;
16267 t = 0;
16268 push(cadr(p1));
16269 Eval();
16270 push(caddr(p1));
16271 Eval();
16272 subtract();
16273 p1 = pop();
16274 if (p1.k !== NUM && p1.k !== DOUBLE) {
16275 push(p1);
16276 yyfloat();
16277 Eval();
16278 p1 = pop();
16279 }
16280 if (iszero(p1)) {
16281 return 0;
16282 }
16283 switch (p1.k) {
16284 case NUM:
16285 if (MSIGN(p1.q.a) === -1) {
16286 t = -1;
16287 } else {
16288 t = 1;
16289 }
16290 break;
16291 case DOUBLE:
16292 if (p1.d < 0.0) {
16293 t = -1;
16294 } else {
16295 t = 1;
16296 }
16297 break;
16298 default:
16299 stop("relational operator: cannot determine due to non-numerical comparison");
16300 t = 0;
16301 }
16302 return t;
16303 };
16304
16305
16306 /*
16307 Transform an expression using table look-up
16308
16309 The expression and free variable are on the stack.
16310
16311 The argument s is a null terminated list of transform rules.
16312
16313 For example, see itab.cpp
16314
16315 Internally, the following symbols are used:
16316
16317 F input expression
16318
16319 X free variable, i.e. F of X
16320
16321 A template expression
16322
16323 B result expression
16324
16325 C list of conditional expressions
16326 */
16327
16328 transform = function(s) {
16329 var ac, eachEntry, h, len;
16330 h = 0;
16331 save();
16332 p4 = pop();
16333 p3 = pop();
16334 push(get_binding(symbol(METAA)));
16335 push(get_binding(symbol(METAB)));
16336 push(get_binding(symbol(METAX)));
16337 set_binding(symbol(METAX), p4);
16338 h = tos;
16339 push_integer(1);
16340 push(p3);
16341 push(p4);
16342 polyform();
16343 push(p4);
16344 decomp();
16345 for (ac = 0, len = s.length; ac < len; ac++) {
16346 eachEntry = s[ac];
16347 if (DEBUG) {
16348 console.log("scanning table entry " + eachEntry);
16349 }
16350 if (eachEntry) {
16351 scan_meta(eachEntry);
16352 p1 = pop();
16353 p5 = cadr(p1);
16354 p6 = caddr(p1);
16355 p7 = cdddr(p1);
16356 if (f_equals_a(h)) {
16357 break;
16358 }
16359 }
16360 }
16361 tos = h;
16362 if (eachEntry) {
16363 push(p6);
16364 Eval();
16365 p1 = pop();
16366 } else {
16367 p1 = symbol(NIL);
16368 }
16369 set_binding(symbol(METAX), pop());
16370 set_binding(symbol(METAB), pop());
16371 set_binding(symbol(METAA), pop());
16372 push(p1);
16373 return restore();
16374 };
16375
16376 f_equals_a = function(h) {
16377 var ac, ad, i, j, ref1, ref2, ref3, ref4;
16378 i = 0;
16379 j = 0;
16380 for (i = ac = ref1 = h, ref2 = tos; ref1 <= ref2 ? ac < ref2 : ac > ref2; i = ref1 <= ref2 ? ++ac : --ac) {
16381 set_binding(symbol(METAA), stack[i]);
16382 for (j = ad = ref3 = h, ref4 = tos; ref3 <= ref4 ? ad < ref4 : ad > ref4; j = ref3 <= ref4 ? ++ad : --ad) {
16383 set_binding(symbol(METAB), stack[j]);
16384 p1 = p7;
16385 while (iscons(p1)) {
16386 push(car(p1));
16387 Eval();
16388 p2 = pop();
16389 if (iszero(p2)) {
16390 break;
16391 }
16392 p1 = cdr(p1);
16393 }
16394 if (iscons(p1)) {
16395 continue;
16396 }
16397 push(p3);
16398 push(p5);
16399 Eval();
16400 subtract();
16401 p1 = pop();
16402 if (iszero(p1)) {
16403 return 1;
16404 }
16405 }
16406 }
16407 return 0;
16408 };
16409
16410 Eval_transpose = function() {
16411 push(cadr(p1));
16412 Eval();
16413 if (cddr(p1) === symbol(NIL)) {
16414 push_integer(1);
16415 push_integer(2);
16416 } else {
16417 push(caddr(p1));
16418 Eval();
16419 push(cadddr(p1));
16420 Eval();
16421 }
16422 return transpose();
16423 };
16424
16425 transpose = function() {
16426 var a, ac, ad, ae, af, ag, ah, ai, an, b, i, j, k, l, m, ndim, nelem, ref1, ref2, ref3, ref4, ref5, ref6, t;
16427 i = 0;
16428 j = 0;
16429 k = 0;
16430 l = 0;
16431 m = 0;
16432 ndim = 0;
16433 nelem = 0;
16434 t = 0;
16435 ai = [];
16436 an = [];
16437 for (i = ac = 0, ref1 = MAXDIM; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
16438 ai[i] = 0;
16439 an[i] = 0;
16440 }
16441 save();
16442 p3 = pop();
16443 p2 = pop();
16444 p1 = pop();
16445 if (!istensor(p1)) {
16446 if (!iszero(p1)) {
16447 stop("transpose: tensor expected, 1st arg is not a tensor");
16448 }
16449 push(zero);
16450 restore();
16451 return;
16452 }
16453 ndim = p1.tensor.ndim;
16454 nelem = p1.tensor.nelem;
16455 if (ndim === 1) {
16456 push(p1);
16457 restore();
16458 return;
16459 }
16460 push(p2);
16461 l = pop_integer();
16462 push(p3);
16463 m = pop_integer();
16464 if (l < 1 || l > ndim || m < 1 || m > ndim) {
16465 stop("transpose: index out of range");
16466 }
16467 l--;
16468 m--;
16469 p2 = alloc_tensor(nelem);
16470 p2.tensor.ndim = ndim;
16471 for (i = ad = 0, ref2 = ndim; 0 <= ref2 ? ad < ref2 : ad > ref2; i = 0 <= ref2 ? ++ad : --ad) {
16472 p2.tensor.dim[i] = p1.tensor.dim[i];
16473 }
16474 p2.tensor.dim[l] = p1.tensor.dim[m];
16475 p2.tensor.dim[m] = p1.tensor.dim[l];
16476 a = p1.tensor.elem;
16477 b = p2.tensor.elem;
16478 for (i = ae = 0, ref3 = ndim; 0 <= ref3 ? ae < ref3 : ae > ref3; i = 0 <= ref3 ? ++ae : --ae) {
16479 ai[i] = 0;
16480 an[i] = p1.tensor.dim[i];
16481 }
16482 for (i = af = 0, ref4 = nelem; 0 <= ref4 ? af < ref4 : af > ref4; i = 0 <= ref4 ? ++af : --af) {
16483 t = ai[l];
16484 ai[l] = ai[m];
16485 ai[m] = t;
16486 t = an[l];
16487 an[l] = an[m];
16488 an[m] = t;
16489 k = 0;
16490 for (j = ag = 0, ref5 = ndim; 0 <= ref5 ? ag < ref5 : ag > ref5; j = 0 <= ref5 ? ++ag : --ag) {
16491 k = (k * an[j]) + ai[j];
16492 }
16493 t = ai[l];
16494 ai[l] = ai[m];
16495 ai[m] = t;
16496 t = an[l];
16497 an[l] = an[m];
16498 an[m] = t;
16499 b[k] = a[i];
16500 for (j = ah = ref6 = ndim - 1; ref6 <= 0 ? ah <= 0 : ah >= 0; j = ref6 <= 0 ? ++ah : --ah) {
16501 if (++ai[j] < an[j]) {
16502 break;
16503 }
16504 ai[j] = 0;
16505 }
16506 }
16507 push(p2);
16508 return restore();
16509 };
16510
16511 Eval_user_function = function() {
16512 var h;
16513 if (car(p1) === symbol(SYMBOL_D) && get_arglist(symbol(SYMBOL_D)) === symbol(NIL)) {
16514 Eval_derivative();
16515 return;
16516 }
16517 p3 = get_binding(car(p1));
16518 p4 = get_arglist(car(p1));
16519 p5 = cdr(p1);
16520 if (p3 === car(p1)) {
16521 h = tos;
16522 push(p3);
16523 p1 = p5;
16524 while (iscons(p1)) {
16525 push(car(p1));
16526 Eval();
16527 p1 = cdr(p1);
16528 }
16529 list(tos - h);
16530 return;
16531 }
16532 p1 = p4;
16533 p2 = p5;
16534 h = tos;
16535 while (iscons(p1) && iscons(p2)) {
16536 push(car(p1));
16537 push(car(p2));
16538 Eval();
16539 p1 = cdr(p1);
16540 p2 = cdr(p2);
16541 }
16542 list(tos - h);
16543 p6 = pop();
16544 push(p3);
16545 if (iscons(p6)) {
16546 push(p6);
16547 rewrite_args();
16548 }
16549 return Eval();
16550 };
16551
16552 rewrite_args = function() {
16553 var h, n;
16554 n = 0;
16555 save();
16556 p2 = pop();
16557 p1 = pop();
16558 if (istensor(p1)) {
16559 n = rewrite_args_tensor();
16560 restore();
16561 return n;
16562 }
16563 if (iscons(p1)) {
16564 h = tos;
16565 push(car(p1));
16566 p1 = cdr(p1);
16567 while (iscons(p1)) {
16568 push(car(p1));
16569 push(p2);
16570 n += rewrite_args();
16571 p1 = cdr(p1);
16572 }
16573 list(tos - h);
16574 restore();
16575 return n;
16576 }
16577 if (!issymbol(p1)) {
16578 push(p1);
16579 restore();
16580 return 0;
16581 }
16582 p3 = p2;
16583 while (iscons(p3)) {
16584 if (p1 === car(p3)) {
16585 push(cadr(p3));
16586 restore();
16587 return 1;
16588 }
16589 p3 = cddr(p3);
16590 }
16591 p3 = get_binding(p1);
16592 push(p3);
16593 if (p1 !== p3) {
16594 push(p2);
16595 n = rewrite_args();
16596 if (n === 0) {
16597 pop();
16598 push(p1);
16599 }
16600 }
16601 restore();
16602 return n;
16603 };
16604
16605 rewrite_args_tensor = function() {
16606 var ac, i, n, ref1;
16607 n = 0;
16608 i = 0;
16609 push(p1);
16610 copy_tensor();
16611 p1 = pop();
16612 for (i = ac = 0, ref1 = p1.tensor.nelem; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
16613 push(p1.tensor.elem[i]);
16614 push(p2);
16615 n += rewrite_args();
16616 p1.tensor.elem[i] = pop();
16617 }
16618 if (p1.tensor.nelem !== p1.tensor.elem.length) {
16619 console.log("something wrong in tensor dimensions");
16620 debugger;
16621 }
16622 push(p1);
16623 return n;
16624 };
16625
16626 Eval_zero = function() {
16627 var ac, ad, i, k, m, n, ref1, ref2;
16628 i = 0;
16629 k = [];
16630 m = 0;
16631 n = 0;
16632 for (i = ac = 0, ref1 = MAXDIM; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
16633 k[i] = 0;
16634 }
16635 m = 1;
16636 n = 0;
16637 p2 = cdr(p1);
16638 while (iscons(p2)) {
16639 push(car(p2));
16640 Eval();
16641 i = pop_integer();
16642 if (i < 2) {
16643 push(zero);
16644 return;
16645 }
16646 m *= i;
16647 k[n++] = i;
16648 p2 = cdr(p2);
16649 }
16650 if (n === 0) {
16651 push(zero);
16652 return;
16653 }
16654 p1 = alloc_tensor(m);
16655 p1.tensor.ndim = n;
16656 for (i = ad = 0, ref2 = n; 0 <= ref2 ? ad < ref2 : ad > ref2; i = 0 <= ref2 ? ++ad : --ad) {
16657 p1.tensor.dim[i] = k[i];
16658 }
16659 return push(p1);
16660 };
16661
16662
16663 /*
16664 // up to 100 blocks of 100,000 atoms
16665
16666 #define M 100
16667 #define N 100000
16668
16669 U *mem[M]
16670 int mcount
16671
16672 U *free_list
16673 int free_count
16674
16675 U *
16676 alloc(void)
16677 {
16678 U *p
16679 if (free_count == 0) {
16680 if (mcount == 0)
16681 alloc_mem()
16682 else {
16683 gc()
16684 if (free_count < N * mcount / 2)
16685 alloc_mem()
16686 }
16687 if (free_count == 0)
16688 stop("atom space exhausted")
16689 }
16690 p = free_list
16691 free_list = free_list->u.cons.cdr
16692 free_count--
16693 return p
16694 }
16695 */
16696
16697 allocatedId = 0;
16698
16699 alloc_tensor = function(nelem) {
16700 var ac, i, p, ref1;
16701 i = 0;
16702 p = new U();
16703 p.k = TENSOR;
16704 p.tensor = new tensor();
16705 p.tensor.nelem = nelem;
16706 for (i = ac = 0, ref1 = nelem; 0 <= ref1 ? ac < ref1 : ac > ref1; i = 0 <= ref1 ? ++ac : --ac) {
16707 p.tensor.elem[i] = zero;
16708 }
16709 p.tensor.allocatedId = allocatedId;
16710 allocatedId++;
16711 if (p.tensor.nelem !== p.tensor.elem.length) {
16712 console.log("something wrong in tensor dimensions");
16713 debugger;
16714 }
16715 return p;
16716 };
16717
16718
16719 /*
16720 // garbage collector
16721
16722 void
16723 gc(void)
16724 {
16725 int i, j
16726 U *p
16727
16728 // tag everything
16729
16730 for (i = 0; i < mcount; i++) {
16731 p = mem[i]
16732 for (j = 0; j < N; j++)
16733 p[j].tag = 1
16734 }
16735
16736 // untag what's used
16737
16738 untag(p0)
16739 untag(p1)
16740 untag(p2)
16741 untag(p3)
16742 untag(p4)
16743 untag(p5)
16744 untag(p6)
16745 untag(p7)
16746 untag(p8)
16747 untag(p9)
16748
16749 untag(one)
16750 untag(zero)
16751 untag(imaginaryunit)
16752
16753 for (i = 0; i < NSYM; i++) {
16754 untag(binding[i])
16755 untag(arglist[i])
16756 }
16757
16758 for (i = 0; i < tos; i++)
16759 untag(stack[i])
16760
16761 for (i = (int) (frame - stack); i < TOS; i++)
16762 untag(stack[i])
16763
16764 // collect everything that's still tagged
16765
16766 free_count = 0
16767
16768 for (i = 0; i < mcount; i++) {
16769 p = mem[i]
16770 for (j = 0; j < N; j++) {
16771 if (p[j].tag == 0)
16772 continue
16773 // still tagged so it's unused, put on free list
16774 switch (p[j].k) {
16775 case TENSOR:
16776 free(p[j].u.tensor)
16777 break
16778 case STR:
16779 free(p[j].u.str)
16780 break
16781 case NUM:
16782 mfree(p[j].u.q.a)
16783 mfree(p[j].u.q.b)
16784 break
16785 }
16786 p[j].k = CONS; // so no double free occurs above
16787 p[j].u.cons.cdr = free_list
16788 free_list = p + j
16789 free_count++
16790 }
16791 }
16792 }
16793
16794 void
16795 untag(U *p)
16796 {
16797 int i
16798
16799 if (iscons(p)) {
16800 do {
16801 if (p->tag == 0)
16802 return
16803 p->tag = 0
16804 untag(p->u.cons.car)
16805 p = p->u.cons.cdr
16806 } while (iscons(p))
16807 untag(p)
16808 return
16809 }
16810
16811 if (p->tag) {
16812 p->tag = 0
16813 if (istensor(p)) {
16814 for (i = 0; i < p->u.tensor->nelem; i++)
16815 untag(p->u.tensor->elem[i])
16816 }
16817 }
16818 }
16819
16820 // get memory for 100,000 atoms
16821
16822 void
16823 alloc_mem(void)
16824 {
16825 int i
16826 U *p
16827 if (mcount == M)
16828 return
16829 p = (U *) malloc(N * sizeof (struct U))
16830 if (p == NULL)
16831 return
16832 mem[mcount++] = p
16833 for (i = 0; i < N; i++) {
16834 p[i].k = CONS; // so no free in gc
16835 p[i].u.cons.cdr = p + i + 1
16836 }
16837 p[N - 1].u.cons.cdr = free_list
16838 free_list = p
16839 free_count += N
16840 }
16841
16842 void
16843 print_mem_info(void)
16844 {
16845 char buf[100]
16846
16847 sprintf(buf, "%d blocks (%d bytes/block)\n", N * mcount, (int) sizeof (U))
16848 printstr(buf)
16849
16850 sprintf(buf, "%d free\n", free_count)
16851 printstr(buf)
16852
16853 sprintf(buf, "%d used\n", N * mcount - free_count)
16854 printstr(buf)
16855 }
16856 */
16857
16858 YMAX = 10000;
16859
16860 glyph = (function() {
16861 function glyph() {}
16862
16863 glyph.prototype.c = 0;
16864
16865 glyph.prototype.x = 0;
16866
16867 glyph.prototype.y = 0;
16868
16869 return glyph;
16870
16871 })();
16872
16873 chartab = [];
16874
16875 for (charTabIndex = ac = 0, ref1 = YMAX; 0 <= ref1 ? ac < ref1 : ac > ref1; charTabIndex = 0 <= ref1 ? ++ac : --ac) {
16876 chartab[charTabIndex] = new glyph();
16877 }
16878
16879 yindex = 0;
16880
16881 level = 0;
16882
16883 emit_x = 0;
16884
16885 expr_level = 0;
16886
16887 display_flag = 0;
16888
16889 printchar_nowrap = function(character, accumulator) {
16890 var topLevelCall;
16891 if (accumulator == null) {
16892 topLevelCall = true;
16893 accumulator = "";
16894 }
16895 accumulator += character;
16896 return accumulator;
16897 };
16898
16899 printchar = function(character, accumulator) {
16900 return printchar_nowrap(character, accumulator);
16901 };
16902
16903 display = function(p) {
16904 var h, ref2, w, y;
16905 h = 0;
16906 w = 0;
16907 y = 0;
16908 save();
16909 yindex = 0;
16910 level = 0;
16911 emit_x = 0;
16912 emit_top_expr(p);
16913 ref2 = get_size(0, yindex), h = ref2[0], w = ref2[1], y = ref2[2];
16914 if (w > 100) {
16915 printline(p);
16916 restore();
16917 return;
16918 }
16919 print_it();
16920 return restore();
16921 };
16922
16923 emit_top_expr = function(p) {
16924 if (car(p) === symbol(SETQ)) {
16925 emit_expr(cadr(p));
16926 __emit_str(" = ");
16927 emit_expr(caddr(p));
16928 return;
16929 }
16930 if (istensor(p)) {
16931 return emit_tensor(p);
16932 } else {
16933 return emit_expr(p);
16934 }
16935 };
16936
16937 will_be_displayed_as_fraction = function(p) {
16938 if (level > 0) {
16939 return 0;
16940 }
16941 if (isfraction(p)) {
16942 return 1;
16943 }
16944 if (car(p) !== symbol(MULTIPLY)) {
16945 return 0;
16946 }
16947 if (isfraction(cadr(p))) {
16948 return 1;
16949 }
16950 while (iscons(p)) {
16951 if (isdenominator(car(p))) {
16952 return 1;
16953 }
16954 p = cdr(p);
16955 }
16956 return 0;
16957 };
16958
16959 emit_expr = function(p) {
16960 expr_level++;
16961 if (car(p) === symbol(ADD)) {
16962 p = cdr(p);
16963 if (__is_negative(car(p))) {
16964 __emit_char('-');
16965 if (will_be_displayed_as_fraction(car(p))) {
16966 __emit_char(' ');
16967 }
16968 }
16969 emit_term(car(p));
16970 p = cdr(p);
16971 while (iscons(p)) {
16972 if (__is_negative(car(p))) {
16973 __emit_char(' ');
16974 __emit_char('-');
16975 __emit_char(' ');
16976 } else {
16977 __emit_char(' ');
16978 __emit_char('+');
16979 __emit_char(' ');
16980 }
16981 emit_term(car(p));
16982 p = cdr(p);
16983 }
16984 } else {
16985 if (__is_negative(p)) {
16986 __emit_char('-');
16987 if (will_be_displayed_as_fraction(p)) {
16988 __emit_char(' ');
16989 }
16990 }
16991 emit_term(p);
16992 }
16993 return expr_level--;
16994 };
16995
16996 emit_unsigned_expr = function(p) {
16997 var results;
16998 if (car(p) === symbol(ADD)) {
16999 p = cdr(p);
17000 emit_term(car(p));
17001 p = cdr(p);
17002 results = [];
17003 while (iscons(p)) {
17004 if (__is_negative(car(p))) {
17005 __emit_char(' ');
17006 __emit_char('-');
17007 __emit_char(' ');
17008 } else {
17009 __emit_char(' ');
17010 __emit_char('+');
17011 __emit_char(' ');
17012 }
17013 emit_term(car(p));
17014 results.push(p = cdr(p));
17015 }
17016 return results;
17017 } else {
17018 return emit_term(p);
17019 }
17020 };
17021
17022 __is_negative = function(p) {
17023 if (isnegativenumber(p)) {
17024 return 1;
17025 }
17026 if (car(p) === symbol(MULTIPLY) && isnegativenumber(cadr(p))) {
17027 return 1;
17028 }
17029 return 0;
17030 };
17031
17032 emit_term = function(p) {
17033 var n;
17034 if (car(p) === symbol(MULTIPLY)) {
17035 n = count_denominators(p);
17036 if (n && level === 0) {
17037 return emit_fraction(p, n);
17038 } else {
17039 return emit_multiply(p, n);
17040 }
17041 } else {
17042 return emit_factor(p);
17043 }
17044 };
17045
17046 isdenominator = function(p) {
17047 if (car(p) === symbol(POWER) && cadr(p) !== symbol(E) && __is_negative(caddr(p))) {
17048 return 1;
17049 } else {
17050 return 0;
17051 }
17052 };
17053
17054 count_denominators = function(p) {
17055 var q;
17056 count = 0;
17057 p = cdr(p);
17058 while (iscons(p)) {
17059 q = car(p);
17060 if (isdenominator(q)) {
17061 count++;
17062 }
17063 p = cdr(p);
17064 }
17065 return count;
17066 };
17067
17068 emit_multiply = function(p, n) {
17069 var results;
17070 if (n === 0) {
17071 p = cdr(p);
17072 if (isplusone(car(p)) || isminusone(car(p))) {
17073 p = cdr(p);
17074 }
17075 emit_factor(car(p));
17076 p = cdr(p);
17077 results = [];
17078 while (iscons(p)) {
17079 __emit_char(' ');
17080 emit_factor(car(p));
17081 results.push(p = cdr(p));
17082 }
17083 return results;
17084 } else {
17085 emit_numerators(p);
17086 __emit_char('/');
17087 if (n > 1 || isfraction(cadr(p))) {
17088 __emit_char('(');
17089 emit_denominators(p);
17090 return __emit_char(')');
17091 } else {
17092 return emit_denominators(p);
17093 }
17094 }
17095 };
17096
17097 emit_fraction = function(p, d) {
17098 var doNothing, k1, k2, n, x;
17099 count = 0;
17100 k1 = 0;
17101 k2 = 0;
17102 n = 0;
17103 x = 0;
17104 save();
17105 p3 = one;
17106 p4 = one;
17107 if (isrational(cadr(p))) {
17108 push(cadr(p));
17109 mp_numerator();
17110 absval();
17111 p3 = pop();
17112 push(cadr(p));
17113 mp_denominator();
17114 p4 = pop();
17115 }
17116 if (isdouble(cadr(p))) {
17117 push(cadr(p));
17118 absval();
17119 p3 = pop();
17120 }
17121 if (isplusone(p3)) {
17122 n = 0;
17123 } else {
17124 n = 1;
17125 }
17126 p1 = cdr(p);
17127 if (isnum(car(p1))) {
17128 p1 = cdr(p1);
17129 }
17130 while (iscons(p1)) {
17131 p2 = car(p1);
17132 if (isdenominator(p2)) {
17133 doNothing = 1;
17134 } else {
17135 n++;
17136 }
17137 p1 = cdr(p1);
17138 }
17139 x = emit_x;
17140 k1 = yindex;
17141 count = 0;
17142 if (!isplusone(p3)) {
17143 emit_number(p3, 0);
17144 count++;
17145 }
17146 p1 = cdr(p);
17147 if (isnum(car(p1))) {
17148 p1 = cdr(p1);
17149 }
17150 while (iscons(p1)) {
17151 p2 = car(p1);
17152 if (isdenominator(p2)) {
17153 doNothing = 1;
17154 } else {
17155 if (count > 0) {
17156 __emit_char(' ');
17157 }
17158 if (n === 1) {
17159 emit_expr(p2);
17160 } else {
17161 emit_factor(p2);
17162 }
17163 count++;
17164 }
17165 p1 = cdr(p1);
17166 }
17167 if (count === 0) {
17168 __emit_char('1');
17169 }
17170 k2 = yindex;
17171 count = 0;
17172 if (!isplusone(p4)) {
17173 emit_number(p4, 0);
17174 count++;
17175 d++;
17176 }
17177 p1 = cdr(p);
17178 if (isrational(car(p1))) {
17179 p1 = cdr(p1);
17180 }
17181 while (iscons(p1)) {
17182 p2 = car(p1);
17183 if (isdenominator(p2)) {
17184 if (count > 0) {
17185 __emit_char(' ');
17186 }
17187 emit_denominator(p2, d);
17188 count++;
17189 }
17190 p1 = cdr(p1);
17191 }
17192 fixup_fraction(x, k1, k2);
17193 return restore();
17194 };
17195
17196 emit_numerators = function(p) {
17197 var doNothing, n;
17198 int(n);
17199 save();
17200 p1 = one;
17201 p = cdr(p);
17202 if (isrational(car(p))) {
17203 push(car(p));
17204 mp_numerator();
17205 absval();
17206 p1 = pop();
17207 p = cdr(p);
17208 } else if (isdouble(car(p))) {
17209 push(car(p));
17210 absval();
17211 p1 = pop();
17212 p = cdr(p);
17213 }
17214 n = 0;
17215 if (!isplusone(p1)) {
17216 emit_number(p1, 0);
17217 n++;
17218 }
17219 while (iscons(p)) {
17220 if (isdenominator(car(p))) {
17221 doNothing = 1;
17222 } else {
17223 if (n > 0) {
17224 __emit_char(' ');
17225 }
17226 emit_factor(car(p));
17227 n++;
17228 }
17229 p = cdr(p);
17230 }
17231 if (n === 0) {
17232 __emit_char('1');
17233 }
17234 return restore();
17235 };
17236
17237 emit_denominators = function(p) {
17238 var n;
17239 int(n);
17240 save();
17241 n = 0;
17242 p = cdr(p);
17243 if (isfraction(car(p))) {
17244 push(car(p));
17245 mp_denominator();
17246 p1 = pop();
17247 emit_number(p1, 0);
17248 n++;
17249 p = cdr(p);
17250 }
17251 while (iscons(p)) {
17252 if (isdenominator(car(p))) {
17253 if (n > 0) {
17254 __emit_char(' ');
17255 }
17256 emit_denominator(car(p), 0);
17257 n++;
17258 }
17259 p = cdr(p);
17260 }
17261 return restore();
17262 };
17263
17264 emit_factor = function(p) {
17265 if (istensor(p)) {
17266 if (level === 0) {
17267 emit_flat_tensor(p);
17268 } else {
17269 emit_flat_tensor(p);
17270 }
17271 return;
17272 }
17273 if (isdouble(p)) {
17274 emit_number(p, 0);
17275 return;
17276 }
17277 if (car(p) === symbol(ADD) || car(p) === symbol(MULTIPLY)) {
17278 emit_subexpr(p);
17279 return;
17280 }
17281 if (car(p) === symbol(POWER)) {
17282 emit_power(p);
17283 return;
17284 }
17285 if (iscons(p)) {
17286 emit_function(p);
17287 return;
17288 }
17289 if (isnum(p)) {
17290 if (level === 0) {
17291 emit_numerical_fraction(p);
17292 } else {
17293 emit_number(p, 0);
17294 }
17295 return;
17296 }
17297 if (issymbol(p)) {
17298 emit_symbol(p);
17299 return;
17300 }
17301 if (isstr(p)) {
17302 emit_string(p);
17303 }
17304 };
17305
17306 emit_numerical_fraction = function(p) {
17307 var k1, k2, x;
17308 k1 = 0;
17309 k2 = 0;
17310 x = 0;
17311 save();
17312 push(p);
17313 mp_numerator();
17314 absval();
17315 p3 = pop();
17316 push(p);
17317 mp_denominator();
17318 p4 = pop();
17319 if (isplusone(p4)) {
17320 emit_number(p3, 0);
17321 restore();
17322 return;
17323 }
17324 x = emit_x;
17325 k1 = yindex;
17326 emit_number(p3, 0);
17327 k2 = yindex;
17328 emit_number(p4, 0);
17329 fixup_fraction(x, k1, k2);
17330 return restore();
17331 };
17332
17333 isfactor = function(p) {
17334 if (iscons(p) && car(p) !== symbol(ADD) && car(p) !== symbol(MULTIPLY) && car(p) !== symbol(POWER)) {
17335 return 1;
17336 }
17337 if (issymbol(p)) {
17338 return 1;
17339 }
17340 if (isfraction(p)) {
17341 return 0;
17342 }
17343 if (isnegativenumber(p)) {
17344 return 0;
17345 }
17346 if (isnum(p)) {
17347 return 1;
17348 }
17349 return 0;
17350 };
17351
17352 emit_power = function(p) {
17353 var k1, k2, x;
17354 k1 = 0;
17355 k2 = 0;
17356 x = 0;
17357 if (cadr(p) === symbol(E)) {
17358 __emit_str("exp(");
17359 emit_expr(caddr(p));
17360 __emit_char(')');
17361 return;
17362 }
17363 if (level > 0) {
17364 if (isminusone(caddr(p))) {
17365 __emit_char('1');
17366 __emit_char('/');
17367 if (isfactor(cadr(p))) {
17368 emit_factor(cadr(p));
17369 } else {
17370 emit_subexpr(cadr(p));
17371 }
17372 } else {
17373 if (isfactor(cadr(p))) {
17374 emit_factor(cadr(p));
17375 } else {
17376 emit_subexpr(cadr(p));
17377 }
17378 __emit_char('^');
17379 if (isfactor(caddr(p))) {
17380 emit_factor(caddr(p));
17381 } else {
17382 emit_subexpr(caddr(p));
17383 }
17384 }
17385 return;
17386 }
17387 if (__is_negative(caddr(p))) {
17388 x = emit_x;
17389 k1 = yindex;
17390 __emit_char('1');
17391 k2 = yindex;
17392 emit_denominator(p, 1);
17393 fixup_fraction(x, k1, k2);
17394 return;
17395 }
17396 k1 = yindex;
17397 if (isfactor(cadr(p))) {
17398 emit_factor(cadr(p));
17399 } else {
17400 emit_subexpr(cadr(p));
17401 }
17402 k2 = yindex;
17403 level++;
17404 emit_expr(caddr(p));
17405 level--;
17406 return fixup_power(k1, k2);
17407 };
17408
17409 emit_denominator = function(p, n) {
17410 var k1, k2;
17411 k1 = 0;
17412 k2 = 0;
17413 if (isminusone(caddr(p))) {
17414 if (n === 1) {
17415 emit_expr(cadr(p));
17416 } else {
17417 emit_factor(cadr(p));
17418 }
17419 return;
17420 }
17421 k1 = yindex;
17422 if (isfactor(cadr(p))) {
17423 emit_factor(cadr(p));
17424 } else {
17425 emit_subexpr(cadr(p));
17426 }
17427 k2 = yindex;
17428 level++;
17429 emit_unsigned_expr(caddr(p));
17430 level--;
17431 return fixup_power(k1, k2);
17432 };
17433
17434 emit_function = function(p) {
17435 if (car(p) === symbol(INDEX) && issymbol(cadr(p))) {
17436 emit_index_function(p);
17437 return;
17438 }
17439 if (car(p) === symbol(FACTORIAL)) {
17440 emit_factorial_function(p);
17441 return;
17442 }
17443 if (car(p) === symbol(DERIVATIVE)) {
17444 __emit_char('d');
17445 } else {
17446 emit_symbol(car(p));
17447 }
17448 __emit_char('(');
17449 p = cdr(p);
17450 if (iscons(p)) {
17451 emit_expr(car(p));
17452 p = cdr(p);
17453 while (iscons(p)) {
17454 __emit_char(',');
17455 emit_expr(car(p));
17456 p = cdr(p);
17457 }
17458 }
17459 return __emit_char(')');
17460 };
17461
17462 emit_index_function = function(p) {
17463 p = cdr(p);
17464 if (caar(p) === symbol(ADD) || caar(p) === symbol(MULTIPLY) || caar(p) === symbol(POWER) || caar(p) === symbol(FACTORIAL)) {
17465 emit_subexpr(car(p));
17466 } else {
17467 emit_expr(car(p));
17468 }
17469 __emit_char('[');
17470 p = cdr(p);
17471 if (iscons(p)) {
17472 emit_expr(car(p));
17473 p = cdr(p);
17474 while (iscons(p)) {
17475 __emit_char(',');
17476 emit_expr(car(p));
17477 p = cdr(p);
17478 }
17479 }
17480 return __emit_char(']');
17481 };
17482
17483 emit_factorial_function = function(p) {
17484 p = cadr(p);
17485 if (car(p) === symbol(ADD) || car(p) === symbol(MULTIPLY) || car(p) === symbol(POWER) || car(p) === symbol(FACTORIAL)) {
17486 emit_subexpr(p);
17487 } else {
17488 emit_expr(p);
17489 }
17490 return __emit_char('!');
17491 };
17492
17493 emit_subexpr = function(p) {
17494 __emit_char('(');
17495 emit_expr(p);
17496 return __emit_char(')');
17497 };
17498
17499 emit_symbol = function(p) {
17500 var ad, i, pPrintName, ref2, results;
17501 i = 0;
17502 if (p === symbol(E)) {
17503 __emit_str("exp(1)");
17504 return;
17505 }
17506 pPrintName = get_printname(p);
17507 results = [];
17508 for (i = ad = 0, ref2 = pPrintName.length; 0 <= ref2 ? ad < ref2 : ad > ref2; i = 0 <= ref2 ? ++ad : --ad) {
17509 results.push(__emit_char(pPrintName[i]));
17510 }
17511 return results;
17512 };
17513
17514 emit_string = function(p) {
17515 var ad, i, pString, ref2;
17516 i = 0;
17517 pString = p.str;
17518 __emit_char('"');
17519 for (i = ad = 0, ref2 = pString.length; 0 <= ref2 ? ad < ref2 : ad > ref2; i = 0 <= ref2 ? ++ad : --ad) {
17520 __emit_char(pString[i]);
17521 }
17522 return __emit_char('"');
17523 };
17524
17525 fixup_fraction = function(x, k1, k2) {
17526 var ad, dx, dy, h1, h2, i, ref2, ref3, ref4, results, w, w1, w2, y, y1, y2;
17527 dx = 0;
17528 dy = 0;
17529 i = 0;
17530 w = 0;
17531 y = 0;
17532 h1 = 0;
17533 w1 = 0;
17534 y1 = 0;
17535 h2 = 0;
17536 w2 = 0;
17537 y2 = 0;
17538 ref2 = get_size(k1, k2), h1 = ref2[0], w1 = ref2[1], y1 = ref2[2];
17539 ref3 = get_size(k2, yindex), h2 = ref3[0], w2 = ref3[1], y2 = ref3[2];
17540 if (w2 > w1) {
17541 dx = (w2 - w1) / 2;
17542 } else {
17543 dx = 0;
17544 }
17545 dx++;
17546 y = y1 + h1 - 1;
17547 dy = -y - 1;
17548 move(k1, k2, dx, dy);
17549 if (w2 > w1) {
17550 dx = -w1;
17551 } else {
17552 dx = -w1 + (w1 - w2) / 2;
17553 }
17554 dx++;
17555 dy = -y2 + 1;
17556 move(k2, yindex, dx, dy);
17557 if (w2 > w1) {
17558 w = w2;
17559 } else {
17560 w = w1;
17561 }
17562 w += 2;
17563 emit_x = x;
17564 results = [];
17565 for (i = ad = 0, ref4 = w; 0 <= ref4 ? ad < ref4 : ad > ref4; i = 0 <= ref4 ? ++ad : --ad) {
17566 results.push(__emit_char('-'));
17567 }
17568 return results;
17569 };
17570
17571 fixup_power = function(k1, k2) {
17572 var dy, h1, h2, ref2, ref3, w1, w2, y1, y2;
17573 dy = 0;
17574 h1 = 0;
17575 w1 = 0;
17576 y1 = 0;
17577 h2 = 0;
17578 w2 = 0;
17579 y2 = 0;
17580 ref2 = get_size(k1, k2), h1 = ref2[0], w1 = ref2[1], y1 = ref2[2];
17581 ref3 = get_size(k2, yindex), h2 = ref3[0], w2 = ref3[1], y2 = ref3[2];
17582 dy = -y2 - h2 + 1;
17583 dy += y1 - 1;
17584 return move(k2, yindex, 0, dy);
17585 };
17586
17587 move = function(j, k, dx, dy) {
17588 var ad, i, ref2, ref3, results;
17589 i = 0;
17590 results = [];
17591 for (i = ad = ref2 = j, ref3 = k; ref2 <= ref3 ? ad < ref3 : ad > ref3; i = ref2 <= ref3 ? ++ad : --ad) {
17592 chartab[i].x += dx;
17593 results.push(chartab[i].y += dy);
17594 }
17595 return results;
17596 };
17597
17598 get_size = function(j, k) {
17599 var ad, h, i, max_x, max_y, min_x, min_y, ref2, ref3, w, y;
17600 i = 0;
17601 min_x = chartab[j].x;
17602 max_x = chartab[j].x;
17603 min_y = chartab[j].y;
17604 max_y = chartab[j].y;
17605 for (i = ad = ref2 = j + 1, ref3 = k; ref2 <= ref3 ? ad < ref3 : ad > ref3; i = ref2 <= ref3 ? ++ad : --ad) {
17606 if (chartab[i].x < min_x) {
17607 min_x = chartab[i].x;
17608 }
17609 if (chartab[i].x > max_x) {
17610 max_x = chartab[i].x;
17611 }
17612 if (chartab[i].y < min_y) {
17613 min_y = chartab[i].y;
17614 }
17615 if (chartab[i].y > max_y) {
17616 max_y = chartab[i].y;
17617 }
17618 }
17619 h = max_y - min_y + 1;
17620 w = max_x - min_x + 1;
17621 y = min_y;
17622 return [h, w, y];
17623 };
17624
17625 displaychar = function(c) {
17626 return __emit_char(c);
17627 };
17628
17629 __emit_char = function(c) {
17630 if (yindex === YMAX) {
17631 return;
17632 }
17633 if (chartab[yindex] == null) {
17634 debugger;
17635 }
17636 chartab[yindex].c = c;
17637 chartab[yindex].x = emit_x;
17638 chartab[yindex].y = 0;
17639 yindex++;
17640 return emit_x++;
17641 };
17642
17643 __emit_str = function(s) {
17644 var ad, i, ref2, results;
17645 i = 0;
17646 results = [];
17647 for (i = ad = 0, ref2 = s.length; 0 <= ref2 ? ad < ref2 : ad > ref2; i = 0 <= ref2 ? ++ad : --ad) {
17648 results.push(__emit_char(s[i]));
17649 }
17650 return results;
17651 };
17652
17653 emit_number = function(p, emit_sign) {
17654 var ad, ae, af, i, ref2, ref3, ref4, results, results1, tmpString;
17655 tmpString = "";
17656 i = 0;
17657 switch (p.k) {
17658 case NUM:
17659 tmpString = p.q.a.toString();
17660 if (tmpString[0] === '-' && emit_sign === 0) {
17661 tmpString = tmpString.substring(1);
17662 }
17663 for (i = ad = 0, ref2 = tmpString.length; 0 <= ref2 ? ad < ref2 : ad > ref2; i = 0 <= ref2 ? ++ad : --ad) {
17664 __emit_char(tmpString[i]);
17665 }
17666 tmpString = p.q.b.toString();
17667 if (tmpString === "1") {
17668 break;
17669 }
17670 __emit_char('/');
17671 results = [];
17672 for (i = ae = 0, ref3 = tmpString.length; 0 <= ref3 ? ae < ref3 : ae > ref3; i = 0 <= ref3 ? ++ae : --ae) {
17673 results.push(__emit_char(tmpString[i]));
17674 }
17675 return results;
17676 break;
17677 case DOUBLE:
17678 tmpString = doubleToReasonableString(p.d);
17679 if (tmpString[0] === '-' && emit_sign === 0) {
17680 tmpString = tmpString.substring(1);
17681 }
17682 results1 = [];
17683 for (i = af = 0, ref4 = tmpString.length; 0 <= ref4 ? af < ref4 : af > ref4; i = 0 <= ref4 ? ++af : --af) {
17684 results1.push(__emit_char(tmpString[i]));
17685 }
17686 return results1;
17687 }
17688 };
17689
17690 cmpGlyphs = function(a, b) {
17691 if (a.y < b.y) {
17692 return -1;
17693 }
17694 if (a.y > b.y) {
17695 return 1;
17696 }
17697 if (a.x < b.x) {
17698 return -1;
17699 }
17700 if (a.x > b.x) {
17701 return 1;
17702 }
17703 return 0;
17704 };
17705
17706 print_it = function() {
17707 var accumulatedPrint, ad, i, ref2, subsetOfStack, x, y;
17708 i = 0;
17709 accumulatedPrint = "";
17710 subsetOfStack = chartab.slice(0, yindex);
17711 subsetOfStack.sort(cmpGlyphs);
17712 chartab = [].concat(subsetOfStack).concat(chartab.slice(yindex));
17713 x = 0;
17714 y = chartab[0].y;
17715 for (i = ad = 0, ref2 = yindex; 0 <= ref2 ? ad < ref2 : ad > ref2; i = 0 <= ref2 ? ++ad : --ad) {
17716 while (chartab[i].y > y) {
17717 accumulatedPrint = printchar('\n', accumulatedPrint);
17718 x = 0;
17719 y++;
17720 }
17721 while (chartab[i].x > x) {
17722 accumulatedPrint = printchar_nowrap(' ', accumulatedPrint);
17723 x++;
17724 }
17725 accumulatedPrint = printchar_nowrap(chartab[i].c, accumulatedPrint);
17726 x++;
17727 }
17728 if (PRINTOUTRESULT) {
17729 return console.log(accumulatedPrint);
17730 }
17731 };
17732
17733 buffer = "";
17734
17735 getdisplaystr = function() {
17736 yindex = 0;
17737 level = 0;
17738 emit_x = 0;
17739 emit_expr(pop());
17740 fill_buf();
17741 return buffer;
17742 };
17743
17744 fill_buf = function() {
17745 var ad, i, ref2, sIndex, subsetOfStack, tmpBuffer, x, y;
17746 tmpBuffer = buffer;
17747 sIndex = 0;
17748 i = 0;
17749 subsetOfStack = chartab.slice(0, yindex);
17750 subsetOfStack.sort(cmpGlyphs);
17751 chartab = [].concat(subsetOfStack).concat(chartab.slice(yindex));
17752 x = 0;
17753 y = chartab[0].y;
17754 for (i = ad = 0, ref2 = yindex; 0 <= ref2 ? ad < ref2 : ad > ref2; i = 0 <= ref2 ? ++ad : --ad) {
17755 while (chartab[i].y > y) {
17756 tmpBuffer[sIndex++] = '\n';
17757 x = 0;
17758 y++;
17759 }
17760 while (chartab[i].x > x) {
17761 tmpBuffer[sIndex++] = ' ';
17762 x++;
17763 }
17764 tmpBuffer[sIndex++] = chartab[i].c;
17765 x++;
17766 }
17767 return tmpBuffer[sIndex++] = '\n';
17768 };
17769
17770 N = 100;
17771
17772 oneElement = (function() {
17773 function oneElement() {}
17774
17775 oneElement.prototype.x = 0;
17776
17777 oneElement.prototype.y = 0;
17778
17779 oneElement.prototype.h = 0;
17780
17781 oneElement.prototype.w = 0;
17782
17783 oneElement.prototype.index = 0;
17784
17785 oneElement.prototype.count = 0;
17786
17787 return oneElement;
17788
17789 })();
17790
17791 elem = [];
17792
17793 for (elelmIndex = ad = 0; ad < 10000; elelmIndex = ++ad) {
17794 elem[elelmIndex] = new oneElement;
17795 }
17796
17797 SPACE_BETWEEN_COLUMNS = 3;
17798
17799 SPACE_BETWEEN_ROWS = 1;
17800
17801 emit_tensor = function(p) {
17802 var ae, af, ag, ah, col, dx, dy, eh, ew, h, i, n, ncol, nrow, ref2, ref3, ref4, ref5, ref6, row, w, x, y;
17803 i = 0;
17804 n = 0;
17805 nrow = 0;
17806 ncol = 0;
17807 x = 0;
17808 y = 0;
17809 h = 0;
17810 w = 0;
17811 dx = 0;
17812 dy = 0;
17813 eh = 0;
17814 ew = 0;
17815 row = 0;
17816 col = 0;
17817 if (p.tensor.ndim > 2) {
17818 emit_flat_tensor(p);
17819 return;
17820 }
17821 nrow = p.tensor.dim[0];
17822 if (p.tensor.ndim === 2) {
17823 ncol = p.tensor.dim[1];
17824 } else {
17825 ncol = 1;
17826 }
17827 n = nrow * ncol;
17828 if (n > N) {
17829 emit_flat_tensor(p);
17830 return;
17831 }
17832 x = emit_x;
17833 for (i = ae = 0, ref2 = n; 0 <= ref2 ? ae < ref2 : ae > ref2; i = 0 <= ref2 ? ++ae : --ae) {
17834 elem[i].index = yindex;
17835 elem[i].x = emit_x;
17836 emit_expr(p.tensor.elem[i]);
17837 elem[i].count = yindex - elem[i].index;
17838 ref3 = get_size(elem[i].index, yindex), elem[i].h = ref3[0], elem[i].w = ref3[1], elem[i].y = ref3[2];
17839 }
17840 eh = 0;
17841 ew = 0;
17842 for (i = af = 0, ref4 = n; 0 <= ref4 ? af < ref4 : af > ref4; i = 0 <= ref4 ? ++af : --af) {
17843 if (elem[i].h > eh) {
17844 eh = elem[i].h;
17845 }
17846 if (elem[i].w > ew) {
17847 ew = elem[i].w;
17848 }
17849 }
17850 h = nrow * eh + (nrow - 1) * SPACE_BETWEEN_ROWS;
17851 w = ncol * ew + (ncol - 1) * SPACE_BETWEEN_COLUMNS;
17852 y = -(h / 2);
17853 for (row = ag = 0, ref5 = nrow; 0 <= ref5 ? ag < ref5 : ag > ref5; row = 0 <= ref5 ? ++ag : --ag) {
17854 for (col = ah = 0, ref6 = ncol; 0 <= ref6 ? ah < ref6 : ah > ref6; col = 0 <= ref6 ? ++ah : --ah) {
17855 i = row * ncol + col;
17856 dx = x - elem[i].x;
17857 dy = y - elem[i].y;
17858 move(elem[i].index, elem[i].index + elem[i].count, dx, dy);
17859 dx = 0;
17860 if (col > 0) {
17861 dx = col * (ew + SPACE_BETWEEN_COLUMNS);
17862 }
17863 dy = 0;
17864 if (row > 0) {
17865 dy = row * (eh + SPACE_BETWEEN_ROWS);
17866 }
17867 dx += (ew - elem[i].w) / 2;
17868 dy += (eh - elem[i].h) / 2;
17869 move(elem[i].index, elem[i].index + elem[i].count, dx, dy);
17870 }
17871 }
17872 return emit_x = x + w;
17873
17874 /*
17875 if 0
17876
17877 * left brace
17878
17879 for (i = 0; i < h; i++) {
17880 if (yindex == YMAX)
17881 break
17882 chartab[yindex].c = '|'
17883 chartab[yindex].x = x - 2
17884 chartab[yindex].y = y + i
17885 yindex++
17886 }
17887
17888 * right brace
17889
17890 emit_x++
17891
17892 for (i = 0; i < h; i++) {
17893 if (yindex == YMAX)
17894 break
17895 chartab[yindex].c = '|'
17896 chartab[yindex].x = emit_x
17897 chartab[yindex].y = y + i
17898 yindex++
17899 }
17900
17901 emit_x++
17902
17903 endif
17904 */
17905 };
17906
17907 emit_flat_tensor = function(p) {
17908 return emit_tensor_inner(p, 0, 0);
17909 };
17910
17911 emit_tensor_inner = function(p, j, k) {
17912 var ae, i, ref2;
17913 i = 0;
17914 __emit_char('(');
17915 for (i = ae = 0, ref2 = p.tensor.dim[j]; 0 <= ref2 ? ae < ref2 : ae > ref2; i = 0 <= ref2 ? ++ae : --ae) {
17916 if (j + 1 === p.tensor.ndim) {
17917 emit_expr(p.tensor.elem[k]);
17918 k = k + 1;
17919 } else {
17920 k = emit_tensor_inner(p, j + 1, k);
17921 }
17922 if (i + 1 < p.tensor.dim[j]) {
17923 __emit_char(',');
17924 }
17925 }
17926 __emit_char(')');
17927 return k;
17928 };
17929
17930
17931 /*
17932 void
17933 test_display(void)
17934 {
17935 test(__FILE__, s, sizeof s / sizeof (char *))
17936 }
17937
17938 #endif
17939 */
17940
17941 Find = function(p, q) {
17942 var ae, i, ref2;
17943 i = 0;
17944 if (equal(p, q)) {
17945 return 1;
17946 }
17947 if (istensor(p)) {
17948 for (i = ae = 0, ref2 = p.tensor.nelem; 0 <= ref2 ? ae < ref2 : ae > ref2; i = 0 <= ref2 ? ++ae : --ae) {
17949 if (Find(p.tensor.elem[i], q)) {
17950 return 1;
17951 }
17952 }
17953 return 0;
17954 }
17955 while (iscons(p)) {
17956 if (Find(car(p), q)) {
17957 return 1;
17958 }
17959 p = cdr(p);
17960 }
17961 return 0;
17962 };
17963
17964 $.Find = Find;
17965
17966 init = function() {
17967 var ae, af, i, ref2, ref3;
17968 i = 0;
17969 flag = 0;
17970 tos = 0;
17971 esc_flag = 0;
17972 draw_flag = 0;
17973 frame = TOS;
17974 if (flag) {
17975 return;
17976 }
17977 flag = 1;
17978 for (i = ae = 0, ref2 = NSYM; 0 <= ref2 ? ae < ref2 : ae > ref2; i = 0 <= ref2 ? ++ae : --ae) {
17979 symtab[i] = new U();
17980 }
17981 for (i = af = 0, ref3 = NSYM; 0 <= ref3 ? af < ref3 : af > ref3; i = 0 <= ref3 ? ++af : --af) {
17982 symtab[i].k = SYM;
17983 binding[i] = symtab[i];
17984 arglist[i] = symbol(NIL);
17985 }
17986 p0 = symbol(NIL);
17987 p1 = symbol(NIL);
17988 p2 = symbol(NIL);
17989 p3 = symbol(NIL);
17990 p4 = symbol(NIL);
17991 p5 = symbol(NIL);
17992 p6 = symbol(NIL);
17993 p7 = symbol(NIL);
17994 p8 = symbol(NIL);
17995 p9 = symbol(NIL);
17996 std_symbol("abs", ABS);
17997 std_symbol("add", ADD);
17998 std_symbol("adj", ADJ);
17999 std_symbol("and", AND);
18000 std_symbol("arccos", ARCCOS);
18001 std_symbol("arccosh", ARCCOSH);
18002 std_symbol("arcsin", ARCSIN);
18003 std_symbol("arcsinh", ARCSINH);
18004 std_symbol("arctan", ARCTAN);
18005 std_symbol("arctanh", ARCTANH);
18006 std_symbol("arg", ARG);
18007 std_symbol("atomize", ATOMIZE);
18008 std_symbol("besselj", BESSELJ);
18009 std_symbol("bessely", BESSELY);
18010 std_symbol("binding", BINDING);
18011 std_symbol("binomial", BINOMIAL);
18012 std_symbol("ceiling", CEILING);
18013 std_symbol("check", CHECK);
18014 std_symbol("choose", CHOOSE);
18015 std_symbol("circexp", CIRCEXP);
18016 std_symbol("clear", CLEAR);
18017 std_symbol("clock", CLOCK);
18018 std_symbol("coeff", COEFF);
18019 std_symbol("cofactor", COFACTOR);
18020 std_symbol("condense", CONDENSE);
18021 std_symbol("conj", CONJ);
18022 std_symbol("contract", CONTRACT);
18023 std_symbol("cos", COS);
18024 std_symbol("cosh", COSH);
18025 std_symbol("decomp", DECOMP);
18026 std_symbol("defint", DEFINT);
18027 std_symbol("deg", DEGREE);
18028 std_symbol("denominator", DENOMINATOR);
18029 std_symbol("det", DET);
18030 std_symbol("derivative", DERIVATIVE);
18031 std_symbol("dim", DIM);
18032 std_symbol("dirac", DIRAC);
18033 std_symbol("display", DISPLAY);
18034 std_symbol("divisors", DIVISORS);
18035 std_symbol("do", DO);
18036 std_symbol("dot", DOT);
18037 std_symbol("draw", DRAW);
18038 std_symbol("dsolve", DSOLVE);
18039 std_symbol("erf", ERF);
18040 std_symbol("erfc", ERFC);
18041 std_symbol("eigen", EIGEN);
18042 std_symbol("eigenval", EIGENVAL);
18043 std_symbol("eigenvec", EIGENVEC);
18044 std_symbol("eval", EVAL);
18045 std_symbol("exp", EXP);
18046 std_symbol("expand", EXPAND);
18047 std_symbol("expcos", EXPCOS);
18048 std_symbol("expsin", EXPSIN);
18049 std_symbol("factor", FACTOR);
18050 std_symbol("factorial", FACTORIAL);
18051 std_symbol("factorpoly", FACTORPOLY);
18052 std_symbol("filter", FILTER);
18053 std_symbol("float", FLOATF);
18054 std_symbol("floor", FLOOR);
18055 std_symbol("for", FOR);
18056 std_symbol("Gamma", GAMMA);
18057 std_symbol("gcd", GCD);
18058 std_symbol("hermite", HERMITE);
18059 std_symbol("hilbert", HILBERT);
18060 std_symbol("imag", IMAG);
18061 std_symbol("component", INDEX);
18062 std_symbol("inner", INNER);
18063 std_symbol("integral", INTEGRAL);
18064 std_symbol("inv", INV);
18065 std_symbol("invg", INVG);
18066 std_symbol("isinteger", ISINTEGER);
18067 std_symbol("isprime", ISPRIME);
18068 std_symbol("laguerre", LAGUERRE);
18069 std_symbol("lcm", LCM);
18070 std_symbol("leading", LEADING);
18071 std_symbol("legendre", LEGENDRE);
18072 std_symbol("log", LOG);
18073 std_symbol("mag", MAG);
18074 std_symbol("mod", MOD);
18075 std_symbol("multiply", MULTIPLY);
18076 std_symbol("not", NOT);
18077 std_symbol("nroots", NROOTS);
18078 std_symbol("number", NUMBER);
18079 std_symbol("numerator", NUMERATOR);
18080 std_symbol("operator", OPERATOR);
18081 std_symbol("or", OR);
18082 std_symbol("outer", OUTER);
18083 std_symbol("polar", POLAR);
18084 std_symbol("power", POWER);
18085 std_symbol("prime", PRIME);
18086 std_symbol("print", PRINT);
18087 std_symbol("product", PRODUCT);
18088 std_symbol("quote", QUOTE);
18089 std_symbol("quotient", QUOTIENT);
18090 std_symbol("rank", RANK);
18091 std_symbol("rationalize", RATIONALIZE);
18092 std_symbol("real", REAL);
18093 std_symbol("rect", YYRECT);
18094 std_symbol("roots", ROOTS);
18095 std_symbol("equals", SETQ);
18096 std_symbol("sgn", SGN);
18097 std_symbol("simplify", SIMPLIFY);
18098 std_symbol("sin", SIN);
18099 std_symbol("sinh", SINH);
18100 std_symbol("shape", SHAPE);
18101 std_symbol("sqrt", SQRT);
18102 std_symbol("stop", STOP);
18103 std_symbol("subst", SUBST);
18104 std_symbol("sum", SUM);
18105 std_symbol("tan", TAN);
18106 std_symbol("tanh", TANH);
18107 std_symbol("taylor", TAYLOR);
18108 std_symbol("test", TEST);
18109 std_symbol("testeq", TESTEQ);
18110 std_symbol("testge", TESTGE);
18111 std_symbol("testgt", TESTGT);
18112 std_symbol("testle", TESTLE);
18113 std_symbol("testlt", TESTLT);
18114 std_symbol("transpose", TRANSPOSE);
18115 std_symbol("unit", UNIT);
18116 std_symbol("zero", ZERO);
18117 std_symbol("nil", NIL);
18118 std_symbol("autoexpand", AUTOEXPAND);
18119 std_symbol("bake", BAKE);
18120 std_symbol("last", LAST);
18121 std_symbol("trace", TRACE);
18122 std_symbol("tty", TTY);
18123 std_symbol("~", YYE);
18124 std_symbol("$DRAWX", DRAWX);
18125 std_symbol("$METAA", METAA);
18126 std_symbol("$METAB", METAB);
18127 std_symbol("$METAX", METAX);
18128 std_symbol("$SECRETX", SECRETX);
18129 std_symbol("pi", PI);
18130 std_symbol("a", SYMBOL_A);
18131 std_symbol("b", SYMBOL_B);
18132 std_symbol("c", SYMBOL_C);
18133 std_symbol("d", SYMBOL_D);
18134 std_symbol("i", SYMBOL_I);
18135 std_symbol("j", SYMBOL_J);
18136 std_symbol("n", SYMBOL_N);
18137 std_symbol("r", SYMBOL_R);
18138 std_symbol("s", SYMBOL_S);
18139 std_symbol("t", SYMBOL_T);
18140 std_symbol("x", SYMBOL_X);
18141 std_symbol("y", SYMBOL_Y);
18142 std_symbol("z", SYMBOL_Z);
18143 std_symbol("$C1", C1);
18144 std_symbol("$C2", C2);
18145 std_symbol("$C3", C3);
18146 std_symbol("$C4", C4);
18147 std_symbol("$C5", C5);
18148 std_symbol("$C6", C6);
18149 push_integer(0);
18150 zero = pop();
18151 push_integer(1);
18152 one = pop();
18153 push_symbol(POWER);
18154 if (DEBUG) {
18155 print1(stack[tos - 1]);
18156 }
18157 push_integer(-1);
18158 if (DEBUG) {
18159 print1(stack[tos - 1]);
18160 }
18161 push_rational(1, 2);
18162 if (DEBUG) {
18163 print1(stack[tos - 1]);
18164 }
18165 list(3);
18166 if (DEBUG) {
18167 print1(stack[tos - 1]);
18168 }
18169 imaginaryunit = pop();
18170 return defn();
18171 };
18172
18173 defn_str = ["e=exp(1)", "i=sqrt(-1)", "autoexpand=1", "trange=(-pi,pi)", "xrange=(-10,10)", "yrange=(-10,10)", "last=0", "trace=0", "tty=0", "cross(u,v)=(u[2]*v[3]-u[3]*v[2],u[3]*v[1]-u[1]*v[3],u[1]*v[2]-u[2]*v[1])", "curl(v)=(d(v[3],y)-d(v[2],z),d(v[1],z)-d(v[3],x),d(v[2],x)-d(v[1],y))", "div(v)=d(v[1],x)+d(v[2],y)+d(v[3],z)", "ln(x)=log(x)"];
18174
18175 defn = function() {
18176 var ae, definitionOfInterest, defn_i, ref2, results;
18177 results = [];
18178 for (defn_i = ae = 0, ref2 = defn_str.length; 0 <= ref2 ? ae < ref2 : ae > ref2; defn_i = 0 <= ref2 ? ++ae : --ae) {
18179 definitionOfInterest = defn_str[defn_i];
18180 scan(definitionOfInterest);
18181 if (DEBUG) {
18182 console.log("... evaling " + definitionOfInterest);
18183 console.log("top of stack:");
18184 print1(stack[tos - 1]);
18185 }
18186 Eval();
18187 results.push(pop());
18188 }
18189 return results;
18190 };
18191
18192 mcmp = function(a, b) {
18193 return a.compare(b);
18194 };
18195
18196 mcmpint = function(a, n) {
18197 var b, t;
18198 b = bigInt(n);
18199 t = mcmp(a, b);
18200 return t;
18201 };
18202
18203
18204 /*
18205 #if SELFTEST
18206
18207 void
18208 test_mcmp(void)
18209 {
18210 int i, j, k
18211 unsigned int *x, *y
18212 logout("testing mcmp\n")
18213 for (i = -1000; i < 1000; i++) {
18214 x = mint(i)
18215 for (j = -1000; j < 1000; j++) {
18216 y = mint(j)
18217 k = mcmp(x, y)
18218 if (i == j && k != 0) {
18219 logout("failed\n")
18220 errout()
18221 }
18222 if (i < j && k != -1) {
18223 logout("failed\n")
18224 errout()
18225 }
18226 if (i > j && k != 1) {
18227 logout("failed\n")
18228 errout()
18229 }
18230 mfree(y)
18231 }
18232 mfree(x)
18233 }
18234 logout("ok\n")
18235 }
18236
18237 #endif
18238 */
18239
18240 strcmp = function(str1, str2) {
18241 if (str1 === str2) {
18242 return 0;
18243 } else if (str1 > str2) {
18244 return 1;
18245 } else {
18246 return -1;
18247 }
18248 };
18249
18250 doubleToReasonableString = function(d) {
18251 return parseFloat(d.toPrecision(6));
18252 };
18253
18254 clear_term = function() {};
18255
18256 isspace = function(s) {
18257 if (s == null) {
18258 return false;
18259 }
18260 return s === ' ' || s === '\t' || s === '\n' || s === '\v' || s === '\f' || s === '\r';
18261 };
18262
18263 isdigit = function(str) {
18264 if (str == null) {
18265 return false;
18266 }
18267 return /^\d+$/.test(str);
18268 };
18269
18270 isalpha = function(str) {
18271 if (str == null) {
18272 return false;
18273 }
18274 if (str == null) {
18275 debugger;
18276 }
18277 return str.search(/[^A-Za-z]/) === -1;
18278 };
18279
18280 isalnum = function(str) {
18281 if (str == null) {
18282 return false;
18283 }
18284 return isalpha(str) || isdigit(str);
18285 };
18286
18287 stop = function(s) {
18288 var message;
18289 errorMessage += "Stop: ";
18290 errorMessage += s;
18291 message = errorMessage;
18292 errorMessage = '';
18293 tos = 0;
18294 throw new Error(message);
18295 };
18296
18297 inited = false;
18298
18299 run = function(stringToBeRun) {
18300 var allReturnedStrings, collectedResult, error, error1, error2, i, indexOfPartRemainingToBeParsed, n;
18301 stringToBeRun = stringToBeRun;
18302 if (stringToBeRun === "selftest") {
18303 selftest();
18304 return;
18305 }
18306 if (!inited) {
18307 inited = true;
18308 init();
18309 }
18310 i = 0;
18311 n = 0;
18312 indexOfPartRemainingToBeParsed = 0;
18313 allReturnedStrings = "";
18314 while (1.) {
18315 try {
18316 errorMessage = "";
18317 check_stack();
18318 n = scan(stringToBeRun.substring(indexOfPartRemainingToBeParsed));
18319 p1 = pop();
18320 check_stack();
18321 } catch (error1) {
18322 error = error1;
18323 if (PRINTOUTRESULT) {
18324 console.log(error);
18325 }
18326 allReturnedStrings += error.message;
18327 init();
18328 break;
18329 }
18330 if (n === 0) {
18331 break;
18332 }
18333 indexOfPartRemainingToBeParsed += n;
18334 push(p1);
18335 try {
18336 top_level_eval();
18337 p2 = pop();
18338 check_stack();
18339 if (p2 === symbol(NIL)) {
18340 continue;
18341 }
18342 if (isstr(p2)) {
18343 console.log(p2.str);
18344 console.log("\n");
18345 continue;
18346 }
18347 collectedResult = collectResultLine(p2);
18348 allReturnedStrings += collectedResult;
18349 if (PRINTOUTRESULT) {
18350 console.log("printline");
18351 console.log(collectedResult);
18352 }
18353 if (PRINTOUTRESULT) {
18354 console.log("display:");
18355 display(p2);
18356 }
18357 allReturnedStrings += "\n";
18358 } catch (error2) {
18359 error = error2;
18360 collectedResult = error.message;
18361 if (PRINTOUTRESULT) {
18362 console.log(collectedResult);
18363 }
18364 allReturnedStrings += collectedResult;
18365 allReturnedStrings += "\n";
18366 init();
18367 }
18368 }
18369 if (allReturnedStrings[allReturnedStrings.length - 1] === "\n") {
18370 allReturnedStrings = allReturnedStrings.substring(0, allReturnedStrings.length - 1);
18371 }
18372 return allReturnedStrings;
18373 };
18374
18375 check_stack = function() {
18376 if (tos !== 0) {
18377 debugger;
18378 stop("stack error");
18379 }
18380 if (frame !== TOS) {
18381 debugger;
18382 return stop("frame error");
18383 }
18384 };
18385
18386 echo_input = function(s) {
18387 console.log(s);
18388 return console.log("\n");
18389 };
18390
18391 top_level_eval = function() {
18392 var doNothing;
18393 if (DEBUG) {
18394 console.log("#### top level eval");
18395 }
18396 save();
18397 trigmode = 0;
18398 p1 = symbol(AUTOEXPAND);
18399 if (iszero(get_binding(p1))) {
18400 expanding = 0;
18401 } else {
18402 expanding = 1;
18403 }
18404 p1 = pop();
18405 push(p1);
18406 Eval();
18407 p2 = pop();
18408 if (p2 === symbol(NIL)) {
18409 push(p2);
18410 restore();
18411 return;
18412 }
18413 set_binding(symbol(LAST), p2);
18414 if (!iszero(get_binding(symbol(BAKE)))) {
18415 push(p2);
18416 bake();
18417 p2 = pop();
18418 }
18419 if ((p1 === symbol(SYMBOL_I) || p1 === symbol(SYMBOL_J)) && isimaginaryunit(p2)) {
18420 doNothing = 0;
18421 } else if (isimaginaryunit(get_binding(symbol(SYMBOL_J)))) {
18422 push(p2);
18423 push(imaginaryunit);
18424 push_symbol(SYMBOL_J);
18425 subst();
18426 p2 = pop();
18427 } else if (isimaginaryunit(get_binding(symbol(SYMBOL_I)))) {
18428 push(p2);
18429 push(imaginaryunit);
18430 push_symbol(SYMBOL_I);
18431 subst();
18432 p2 = pop();
18433 }
18434 push(p2);
18435 return restore();
18436 };
18437
18438 check_esc_flag = function() {
18439 if (esc_flag) {
18440 return stop("esc key");
18441 }
18442 };
18443
18444 (typeof exports !== "undefined" && exports !== null ? exports : this).run = run;
18445
18446 tos = 0;
18447
18448 nil_symbols = 0;
18449
18450 push = function(p) {
18451 if (p == null) {
18452 debugger;
18453 }
18454 if (p.isZero != null) {
18455 debugger;
18456 }
18457 if (p === symbol(NIL)) {
18458 nil_symbols++;
18459 if (DEBUG) {
18460 console.log("pushing symbol(NIL) #" + nil_symbols);
18461 }
18462 }
18463 if (tos >= frame) {
18464 stop("stack overflow");
18465 }
18466 return stack[tos++] = p;
18467 };
18468
18469 pop = function() {
18470 var elementToBeReturned;
18471 if (tos === 0) {
18472 debugger;
18473 stop("stack underflow");
18474 }
18475 if (stack[tos - 1] == null) {
18476 debugger;
18477 }
18478 elementToBeReturned = stack[--tos];
18479 return elementToBeReturned;
18480 };
18481
18482 push_frame = function(n) {
18483 var ae, i, ref2, results;
18484 i = 0;
18485 frame -= n;
18486 if (frame < tos) {
18487 debugger;
18488 stop("frame overflow, circular reference?");
18489 }
18490 results = [];
18491 for (i = ae = 0, ref2 = n; 0 <= ref2 ? ae < ref2 : ae > ref2; i = 0 <= ref2 ? ++ae : --ae) {
18492 results.push(stack[frame + i] = symbol(NIL));
18493 }
18494 return results;
18495 };
18496
18497 pop_frame = function(n) {
18498 frame += n;
18499 if (frame > TOS) {
18500 return stop("frame underflow");
18501 }
18502 };
18503
18504 save = function() {
18505 frame -= 10;
18506 if (frame < tos) {
18507 debugger;
18508 stop("frame overflow, circular reference?");
18509 }
18510 stack[frame + 0] = p0;
18511 stack[frame + 1] = p1;
18512 stack[frame + 2] = p2;
18513 stack[frame + 3] = p3;
18514 stack[frame + 4] = p4;
18515 stack[frame + 5] = p5;
18516 stack[frame + 6] = p6;
18517 stack[frame + 7] = p7;
18518 stack[frame + 8] = p8;
18519 return stack[frame + 9] = p9;
18520 };
18521
18522 restore = function() {
18523 if (frame > TOS - 10) {
18524 stop("frame underflow");
18525 }
18526 p0 = stack[frame + 0];
18527 p1 = stack[frame + 1];
18528 p2 = stack[frame + 2];
18529 p3 = stack[frame + 3];
18530 p4 = stack[frame + 4];
18531 p5 = stack[frame + 5];
18532 p6 = stack[frame + 6];
18533 p7 = stack[frame + 7];
18534 p8 = stack[frame + 8];
18535 p9 = stack[frame + 9];
18536 return frame += 10;
18537 };
18538
18539 swap = function() {
18540 var p, q;
18541 p = pop();
18542 q = pop();
18543 push(p);
18544 return push(q);
18545 };
18546
18547 dupl = function() {
18548 var p;
18549 p = pop();
18550 push(p);
18551 return push(p);
18552 };
18553
18554 $.dupl = dupl;
18555
18556 $.swap = swap;
18557
18558 $.restore = restore;
18559
18560 $.save = save;
18561
18562 $.push = push;
18563
18564 $.pop = pop;
18565
18566 std_symbol = function(s, n) {
18567 var p;
18568 p = symtab[n];
18569 if (p == null) {
18570 debugger;
18571 }
18572 return p.printname = s;
18573 };
18574
18575 usr_symbol = function(s) {
18576 var ae, i, p, ref2;
18577 i = 0;
18578 for (i = ae = 0, ref2 = NSYM; 0 <= ref2 ? ae < ref2 : ae > ref2; i = 0 <= ref2 ? ++ae : --ae) {
18579 if (symtab[i].printname === "") {
18580 break;
18581 }
18582 if (s === symtab[i].printname) {
18583 return symtab[i];
18584 }
18585 }
18586 if (i === NSYM) {
18587 stop("symbol table overflow");
18588 }
18589 p = symtab[i];
18590 p.printname = s;
18591 return p;
18592 };
18593
18594 get_printname = function(p) {
18595 if (p.k !== SYM) {
18596 stop("symbol error");
18597 }
18598 return p.printname;
18599 };
18600
18601 set_binding = function(p, q) {
18602 var indexFound;
18603 if (p.k !== SYM) {
18604 stop("symbol error");
18605 }
18606 indexFound = symtab.indexOf(p);
18607 if (symtab.indexOf(p, indexFound + 1) !== -1) {
18608 console.log("ops, more than one element!");
18609 debugger;
18610 }
18611 if (DEBUG) {
18612 console.log("lookup >> set_binding lookup " + indexFound);
18613 }
18614 binding[indexFound] = q;
18615 return arglist[indexFound] = symbol(NIL);
18616 };
18617
18618 get_binding = function(p) {
18619 var indexFound;
18620 if (p.k !== SYM) {
18621 stop("symbol error");
18622 }
18623 indexFound = symtab.indexOf(p);
18624 if (symtab.indexOf(p, indexFound + 1) !== -1) {
18625 console.log("ops, more than one element!");
18626 debugger;
18627 }
18628 if (DEBUG) {
18629 console.log("lookup >> get_binding lookup " + indexFound);
18630 }
18631 return binding[indexFound];
18632 };
18633
18634 set_binding_and_arglist = function(p, q, r) {
18635 var indexFound;
18636 if (p.k !== SYM) {
18637 stop("symbol error");
18638 }
18639 indexFound = symtab.indexOf(p);
18640 if (symtab.indexOf(p, indexFound + 1) !== -1) {
18641 console.log("ops, more than one element!");
18642 debugger;
18643 }
18644 if (DEBUG) {
18645 console.log("lookup >> set_binding_and_arglist lookup " + indexFound);
18646 }
18647 binding[indexFound] = q;
18648 return arglist[indexFound] = r;
18649 };
18650
18651 get_arglist = function(p) {
18652 var indexFound;
18653 if (p.k !== SYM) {
18654 stop("symbol error");
18655 }
18656 indexFound = symtab.indexOf(p);
18657 if (symtab.indexOf(p, indexFound + 1) !== -1) {
18658 console.log("ops, more than one element!");
18659 debugger;
18660 }
18661 if (DEBUG) {
18662 console.log("lookup >> get_arglist lookup " + indexFound);
18663 }
18664 return arglist[indexFound];
18665 };
18666
18667 lookupsTotal = 0;
18668
18669 symnum = function(p) {
18670 var indexFound;
18671 lookupsTotal++;
18672 if (p.k !== SYM) {
18673 stop("symbol error");
18674 }
18675 indexFound = symtab.indexOf(p);
18676 if (symtab.indexOf(p, indexFound + 1) !== -1) {
18677 console.log("ops, more than one element!");
18678 debugger;
18679 }
18680 if (DEBUG) {
18681 console.log("lookup >> symnum lookup " + indexFound + " lookup # " + lookupsTotal);
18682 }
18683 return indexFound;
18684 };
18685
18686 push_symbol = function(k) {
18687 return push(symtab[k]);
18688 };
18689
18690 clear_symbols = function() {
18691 var ae, i, ref2, results;
18692 i = 0;
18693 results = [];
18694 for (i = ae = 0, ref2 = NSYM; 0 <= ref2 ? ae < ref2 : ae > ref2; i = 0 <= ref2 ? ++ae : --ae) {
18695 binding[i] = symtab[i];
18696 results.push(arglist[i] = symbol(NIL));
18697 }
18698 return results;
18699 };
18700
18701 $.get_binding = get_binding;
18702
18703 $.set_binding = set_binding;
18704
18705 $.usr_symbol = usr_symbol;
18706
18707 if (!inited) {
18708 inited = true;
18709 init();
18710 }
18711
18712 $.init = init;
18713
18714 parse_internal = function(argu) {
18715 if (typeof argu === 'string') {
18716 return scan(argu);
18717 } else if (typeof argu === 'number') {
18718 if (argu % 1 === 0) {
18719 return push_integer(argu);
18720 } else {
18721 return push_double(argu);
18722 }
18723 } else if (argu instanceof U) {
18724 return push(argu);
18725 } else {
18726 console.warn('unknown argument type', argu);
18727 return push(symbol(NIL));
18728 }
18729 };
18730
18731 parse = function(argu) {
18732 var data, error, error1;
18733 try {
18734 parse_internal(argu);
18735 data = pop();
18736 check_stack();
18737 } catch (error1) {
18738 error = error1;
18739 reset_after_error();
18740 throw error;
18741 }
18742 return data;
18743 };
18744
18745 exec = function() {
18746 var ae, argu, argus, error, error1, fn, len, name, result;
18747 name = arguments[0], argus = 2 <= arguments.length ? slice.call(arguments, 1) : [];
18748 fn = get_binding(usr_symbol(name));
18749 check_stack();
18750 push(fn);
18751 for (ae = 0, len = argus.length; ae < len; ae++) {
18752 argu = argus[ae];
18753 parse_internal(argu);
18754 }
18755 list(1 + argus.length);
18756 p1 = pop();
18757 push(p1);
18758 try {
18759 fixed_top_level_eval();
18760 result = pop();
18761 check_stack();
18762 } catch (error1) {
18763 error = error1;
18764 reset_after_error();
18765 throw error;
18766 }
18767 return result;
18768 };
18769
18770 reset_after_error = function() {
18771 tos = 0;
18772 esc_flag = 0;
18773 draw_flag = 0;
18774 return frame = TOS;
18775 };
18776
18777 fixed_top_level_eval = function() {
18778 save();
18779 trigmode = 0;
18780 p1 = symbol(AUTOEXPAND);
18781 if (iszero(get_binding(p1))) {
18782 expanding = 0;
18783 } else {
18784 expanding = 1;
18785 }
18786 p1 = pop();
18787 push(p1);
18788 Eval();
18789 p2 = pop();
18790 if (p2 === symbol(NIL)) {
18791 push(p2);
18792 restore();
18793 return;
18794 }
18795 if (!iszero(get_binding(symbol(BAKE)))) {
18796 push(p2);
18797 bake();
18798 p2 = pop();
18799 }
18800 push(p2);
18801 return restore();
18802 };
18803
18804 $.exec = exec;
18805
18806 $.parse = parse;
18807
18808 (function() {
18809 var ae, builtin_fns, fn, len, results;
18810 builtin_fns = ["abs", "add", "adj", "and", "arccos", "arccosh", "arcsin", "arcsinh", "arctan", "arctanh", "arg", "atomize", "besselj", "bessely", "binding", "binomial", "ceiling", "check", "choose", "circexp", "clear", "clock", "coeff", "cofactor", "condense", "conj", "contract", "cos", "cosh", "decomp", "defint", "deg", "denominator", "det", "derivative", "dim", "dirac", "display", "divisors", "do", "dot", "draw", "dsolve", "erf", "erfc", "eigen", "eigenval", "eigenvec", "eval", "exp", "expand", "expcos", "expsin", "factor", "factorial", "factorpoly", "filter", "float", "floor", "for", "Gamma", "gcd", "hermite", "hilbert", "imag", "component", "inner", "integral", "inv", "invg", "isinteger", "isprime", "laguerre", "lcm", "leading", "legendre", "log", "mag", "mod", "multiply", "not", "nroots", "number", "numerator", "operator", "or", "outer", "polar", "power", "prime", "print", "product", "quote", "quotient", "rank", "rationalize", "real", "rect", "roots", "equals", "sgn", "simplify", "sin", "sinh", "sqrt", "stop", "subst", "sum", "tan", "tanh", "taylor", "test", "testeq", "testge", "testgt", "testle", "testlt", "transpose", "unit", "zero"];
18811 results = [];
18812 for (ae = 0, len = builtin_fns.length; ae < len; ae++) {
18813 fn = builtin_fns[ae];
18814 results.push($[fn] = exec.bind(this, fn));
18815 }
18816 return results;
18817 })();
18818
18819}).call(this);
18820
18821},{"big-integer":13}],13:[function(require,module,exports){
18822var bigInt = (function (undefined) {
18823 "use strict";
18824
18825 var BASE = 1e7,
18826 LOG_BASE = 7,
18827 MAX_INT = 9007199254740992,
18828 MAX_INT_ARR = smallToArray(MAX_INT),
18829 LOG_MAX_INT = Math.log(MAX_INT);
18830
18831 function Integer(v, radix) {
18832 if (typeof v === "undefined") return Integer[0];
18833 if (typeof radix !== "undefined") return +radix === 10 ? parseValue(v) : parseBase(v, radix);
18834 return parseValue(v);
18835 }
18836
18837 function BigInteger(value, sign) {
18838 this.value = value;
18839 this.sign = sign;
18840 this.isSmall = false;
18841 }
18842 BigInteger.prototype = Object.create(Integer.prototype);
18843
18844 function SmallInteger(value) {
18845 this.value = value;
18846 this.sign = value < 0;
18847 this.isSmall = true;
18848 }
18849 SmallInteger.prototype = Object.create(Integer.prototype);
18850
18851 function isPrecise(n) {
18852 return -MAX_INT < n && n < MAX_INT;
18853 }
18854
18855 function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes
18856 if (n < 1e7)
18857 return [n];
18858 if (n < 1e14)
18859 return [n % 1e7, Math.floor(n / 1e7)];
18860 return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)];
18861 }
18862
18863 function arrayToSmall(arr) { // If BASE changes this function may need to change
18864 trim(arr);
18865 var length = arr.length;
18866 if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) {
18867 switch (length) {
18868 case 0: return 0;
18869 case 1: return arr[0];
18870 case 2: return arr[0] + arr[1] * BASE;
18871 default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE;
18872 }
18873 }
18874 return arr;
18875 }
18876
18877 function trim(v) {
18878 var i = v.length;
18879 while (v[--i] === 0);
18880 v.length = i + 1;
18881 }
18882
18883 function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger
18884 var x = new Array(length);
18885 var i = -1;
18886 while (++i < length) {
18887 x[i] = 0;
18888 }
18889 return x;
18890 }
18891
18892 function truncate(n) {
18893 if (n > 0) return Math.floor(n);
18894 return Math.ceil(n);
18895 }
18896
18897 function add(a, b) { // assumes a and b are arrays with a.length >= b.length
18898 var l_a = a.length,
18899 l_b = b.length,
18900 r = new Array(l_a),
18901 carry = 0,
18902 base = BASE,
18903 sum, i;
18904 for (i = 0; i < l_b; i++) {
18905 sum = a[i] + b[i] + carry;
18906 carry = sum >= base ? 1 : 0;
18907 r[i] = sum - carry * base;
18908 }
18909 while (i < l_a) {
18910 sum = a[i] + carry;
18911 carry = sum === base ? 1 : 0;
18912 r[i++] = sum - carry * base;
18913 }
18914 if (carry > 0) r.push(carry);
18915 return r;
18916 }
18917
18918 function addAny(a, b) {
18919 if (a.length >= b.length) return add(a, b);
18920 return add(b, a);
18921 }
18922
18923 function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT
18924 var l = a.length,
18925 r = new Array(l),
18926 base = BASE,
18927 sum, i;
18928 for (i = 0; i < l; i++) {
18929 sum = a[i] - base + carry;
18930 carry = Math.floor(sum / base);
18931 r[i] = sum - carry * base;
18932 carry += 1;
18933 }
18934 while (carry > 0) {
18935 r[i++] = carry % base;
18936 carry = Math.floor(carry / base);
18937 }
18938 return r;
18939 }
18940
18941 BigInteger.prototype.add = function (v) {
18942 var value, n = parseValue(v);
18943 if (this.sign !== n.sign) {
18944 return this.subtract(n.negate());
18945 }
18946 var a = this.value, b = n.value;
18947 if (n.isSmall) {
18948 return new BigInteger(addSmall(a, Math.abs(b)), this.sign);
18949 }
18950 return new BigInteger(addAny(a, b), this.sign);
18951 };
18952 BigInteger.prototype.plus = BigInteger.prototype.add;
18953
18954 SmallInteger.prototype.add = function (v) {
18955 var n = parseValue(v);
18956 var a = this.value;
18957 if (a < 0 !== n.sign) {
18958 return this.subtract(n.negate());
18959 }
18960 var b = n.value;
18961 if (n.isSmall) {
18962 if (isPrecise(a + b)) return new SmallInteger(a + b);
18963 b = smallToArray(Math.abs(b));
18964 }
18965 return new BigInteger(addSmall(b, Math.abs(a)), a < 0);
18966 };
18967 SmallInteger.prototype.plus = SmallInteger.prototype.add;
18968
18969 function subtract(a, b) { // assumes a and b are arrays with a >= b
18970 var a_l = a.length,
18971 b_l = b.length,
18972 r = new Array(a_l),
18973 borrow = 0,
18974 base = BASE,
18975 i, difference;
18976 for (i = 0; i < b_l; i++) {
18977 difference = a[i] - borrow - b[i];
18978 if (difference < 0) {
18979 difference += base;
18980 borrow = 1;
18981 } else borrow = 0;
18982 r[i] = difference;
18983 }
18984 for (i = b_l; i < a_l; i++) {
18985 difference = a[i] - borrow;
18986 if (difference < 0) difference += base;
18987 else {
18988 r[i++] = difference;
18989 break;
18990 }
18991 r[i] = difference;
18992 }
18993 for (; i < a_l; i++) {
18994 r[i] = a[i];
18995 }
18996 trim(r);
18997 return r;
18998 }
18999
19000 function subtractAny(a, b, sign) {
19001 var value, isSmall;
19002 if (compareAbs(a, b) >= 0) {
19003 value = subtract(a,b);
19004 } else {
19005 value = subtract(b, a);
19006 sign = !sign;
19007 }
19008 value = arrayToSmall(value);
19009 if (typeof value === "number") {
19010 if (sign) value = -value;
19011 return new SmallInteger(value);
19012 }
19013 return new BigInteger(value, sign);
19014 }
19015
19016 function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT
19017 var l = a.length,
19018 r = new Array(l),
19019 carry = -b,
19020 base = BASE,
19021 i, difference;
19022 for (i = 0; i < l; i++) {
19023 difference = a[i] + carry;
19024 carry = Math.floor(difference / base);
19025 difference %= base;
19026 r[i] = difference < 0 ? difference + base : difference;
19027 }
19028 r = arrayToSmall(r);
19029 if (typeof r === "number") {
19030 if (sign) r = -r;
19031 return new SmallInteger(r);
19032 } return new BigInteger(r, sign);
19033 }
19034
19035 BigInteger.prototype.subtract = function (v) {
19036 var n = parseValue(v);
19037 if (this.sign !== n.sign) {
19038 return this.add(n.negate());
19039 }
19040 var a = this.value, b = n.value;
19041 if (n.isSmall)
19042 return subtractSmall(a, Math.abs(b), this.sign);
19043 return subtractAny(a, b, this.sign);
19044 };
19045 BigInteger.prototype.minus = BigInteger.prototype.subtract;
19046
19047 SmallInteger.prototype.subtract = function (v) {
19048 var n = parseValue(v);
19049 var a = this.value;
19050 if (a < 0 !== n.sign) {
19051 return this.add(n.negate());
19052 }
19053 var b = n.value;
19054 if (n.isSmall) {
19055 return new SmallInteger(a - b);
19056 }
19057 return subtractSmall(b, Math.abs(a), a >= 0);
19058 };
19059 SmallInteger.prototype.minus = SmallInteger.prototype.subtract;
19060
19061 BigInteger.prototype.negate = function () {
19062 return new BigInteger(this.value, !this.sign);
19063 };
19064 SmallInteger.prototype.negate = function () {
19065 var sign = this.sign;
19066 var small = new SmallInteger(-this.value);
19067 small.sign = !sign;
19068 return small;
19069 };
19070
19071 BigInteger.prototype.abs = function () {
19072 return new BigInteger(this.value, false);
19073 };
19074 SmallInteger.prototype.abs = function () {
19075 return new SmallInteger(Math.abs(this.value));
19076 };
19077
19078 function multiplyLong(a, b) {
19079 var a_l = a.length,
19080 b_l = b.length,
19081 l = a_l + b_l,
19082 r = createArray(l),
19083 base = BASE,
19084 product, carry, i, a_i, b_j;
19085 for (i = 0; i < a_l; ++i) {
19086 a_i = a[i];
19087 for (var j = 0; j < b_l; ++j) {
19088 b_j = b[j];
19089 product = a_i * b_j + r[i + j];
19090 carry = Math.floor(product / base);
19091 r[i + j] = product - carry * base;
19092 r[i + j + 1] += carry;
19093 }
19094 }
19095 trim(r);
19096 return r;
19097 }
19098
19099 function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE
19100 var l = a.length,
19101 r = new Array(l),
19102 base = BASE,
19103 carry = 0,
19104 product, i;
19105 for (i = 0; i < l; i++) {
19106 product = a[i] * b + carry;
19107 carry = Math.floor(product / base);
19108 r[i] = product - carry * base;
19109 }
19110 while (carry > 0) {
19111 r[i++] = carry % base;
19112 carry = Math.floor(carry / base);
19113 }
19114 return r;
19115 }
19116
19117 function shiftLeft(x, n) {
19118 var r = [];
19119 while (n-- > 0) r.push(0);
19120 return r.concat(x);
19121 }
19122
19123 function multiplyKaratsuba(x, y) {
19124 var n = Math.max(x.length, y.length);
19125
19126 if (n <= 30) return multiplyLong(x, y);
19127 n = Math.ceil(n / 2);
19128
19129 var b = x.slice(n),
19130 a = x.slice(0, n),
19131 d = y.slice(n),
19132 c = y.slice(0, n);
19133
19134 var ac = multiplyKaratsuba(a, c),
19135 bd = multiplyKaratsuba(b, d),
19136 abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d));
19137
19138 var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n));
19139 trim(product);
19140 return product;
19141 }
19142
19143 // The following function is derived from a surface fit of a graph plotting the performance difference
19144 // between long multiplication and karatsuba multiplication versus the lengths of the two arrays.
19145 function useKaratsuba(l1, l2) {
19146 return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0;
19147 }
19148
19149 BigInteger.prototype.multiply = function (v) {
19150 var value, n = parseValue(v),
19151 a = this.value, b = n.value,
19152 sign = this.sign !== n.sign,
19153 abs;
19154 if (n.isSmall) {
19155 if (b === 0) return Integer[0];
19156 if (b === 1) return this;
19157 if (b === -1) return this.negate();
19158 abs = Math.abs(b);
19159 if (abs < BASE) {
19160 return new BigInteger(multiplySmall(a, abs), sign);
19161 }
19162 b = smallToArray(abs);
19163 }
19164 if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes
19165 return new BigInteger(multiplyKaratsuba(a, b), sign);
19166 return new BigInteger(multiplyLong(a, b), sign);
19167 };
19168
19169 BigInteger.prototype.times = BigInteger.prototype.multiply;
19170
19171 function multiplySmallAndArray(a, b, sign) { // a >= 0
19172 if (a < BASE) {
19173 return new BigInteger(multiplySmall(b, a), sign);
19174 }
19175 return new BigInteger(multiplyLong(b, smallToArray(a)), sign);
19176 }
19177 SmallInteger.prototype._multiplyBySmall = function (a) {
19178 if (isPrecise(a.value * this.value)) {
19179 return new SmallInteger(a.value * this.value);
19180 }
19181 return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign);
19182 };
19183 BigInteger.prototype._multiplyBySmall = function (a) {
19184 if (a.value === 0) return Integer[0];
19185 if (a.value === 1) return this;
19186 if (a.value === -1) return this.negate();
19187 return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign);
19188 };
19189 SmallInteger.prototype.multiply = function (v) {
19190 return parseValue(v)._multiplyBySmall(this);
19191 };
19192 SmallInteger.prototype.times = SmallInteger.prototype.multiply;
19193
19194 function square(a) {
19195 var l = a.length,
19196 r = createArray(l + l),
19197 base = BASE,
19198 product, carry, i, a_i, a_j;
19199 for (i = 0; i < l; i++) {
19200 a_i = a[i];
19201 for (var j = 0; j < l; j++) {
19202 a_j = a[j];
19203 product = a_i * a_j + r[i + j];
19204 carry = Math.floor(product / base);
19205 r[i + j] = product - carry * base;
19206 r[i + j + 1] += carry;
19207 }
19208 }
19209 trim(r);
19210 return r;
19211 }
19212
19213 BigInteger.prototype.square = function () {
19214 return new BigInteger(square(this.value), false);
19215 };
19216
19217 SmallInteger.prototype.square = function () {
19218 var value = this.value * this.value;
19219 if (isPrecise(value)) return new SmallInteger(value);
19220 return new BigInteger(square(smallToArray(Math.abs(this.value))), false);
19221 };
19222
19223 function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes.
19224 var a_l = a.length,
19225 b_l = b.length,
19226 base = BASE,
19227 result = createArray(b.length),
19228 divisorMostSignificantDigit = b[b_l - 1],
19229 // normalization
19230 lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)),
19231 remainder = multiplySmall(a, lambda),
19232 divisor = multiplySmall(b, lambda),
19233 quotientDigit, shift, carry, borrow, i, l, q;
19234 if (remainder.length <= a_l) remainder.push(0);
19235 divisor.push(0);
19236 divisorMostSignificantDigit = divisor[b_l - 1];
19237 for (shift = a_l - b_l; shift >= 0; shift--) {
19238 quotientDigit = base - 1;
19239 if (remainder[shift + b_l] !== divisorMostSignificantDigit) {
19240 quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit);
19241 }
19242 // quotientDigit <= base - 1
19243 carry = 0;
19244 borrow = 0;
19245 l = divisor.length;
19246 for (i = 0; i < l; i++) {
19247 carry += quotientDigit * divisor[i];
19248 q = Math.floor(carry / base);
19249 borrow += remainder[shift + i] - (carry - q * base);
19250 carry = q;
19251 if (borrow < 0) {
19252 remainder[shift + i] = borrow + base;
19253 borrow = -1;
19254 } else {
19255 remainder[shift + i] = borrow;
19256 borrow = 0;
19257 }
19258 }
19259 while (borrow !== 0) {
19260 quotientDigit -= 1;
19261 carry = 0;
19262 for (i = 0; i < l; i++) {
19263 carry += remainder[shift + i] - base + divisor[i];
19264 if (carry < 0) {
19265 remainder[shift + i] = carry + base;
19266 carry = 0;
19267 } else {
19268 remainder[shift + i] = carry;
19269 carry = 1;
19270 }
19271 }
19272 borrow += carry;
19273 }
19274 result[shift] = quotientDigit;
19275 }
19276 // denormalization
19277 remainder = divModSmall(remainder, lambda)[0];
19278 return [arrayToSmall(result), arrayToSmall(remainder)];
19279 }
19280
19281 function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/
19282 // Performs faster than divMod1 on larger input sizes.
19283 var a_l = a.length,
19284 b_l = b.length,
19285 result = [],
19286 part = [],
19287 base = BASE,
19288 guess, xlen, highx, highy, check;
19289 while (a_l) {
19290 part.unshift(a[--a_l]);
19291 if (compareAbs(part, b) < 0) {
19292 result.push(0);
19293 continue;
19294 }
19295 xlen = part.length;
19296 highx = part[xlen - 1] * base + part[xlen - 2];
19297 highy = b[b_l - 1] * base + b[b_l - 2];
19298 if (xlen > b_l) {
19299 highx = (highx + 1) * base;
19300 }
19301 guess = Math.ceil(highx / highy);
19302 do {
19303 check = multiplySmall(b, guess);
19304 if (compareAbs(check, part) <= 0) break;
19305 guess--;
19306 } while (guess);
19307 result.push(guess);
19308 part = subtract(part, check);
19309 }
19310 result.reverse();
19311 return [arrayToSmall(result), arrayToSmall(part)];
19312 }
19313
19314 function divModSmall(value, lambda) {
19315 var length = value.length,
19316 quotient = createArray(length),
19317 base = BASE,
19318 i, q, remainder, divisor;
19319 remainder = 0;
19320 for (i = length - 1; i >= 0; --i) {
19321 divisor = remainder * base + value[i];
19322 q = truncate(divisor / lambda);
19323 remainder = divisor - q * lambda;
19324 quotient[i] = q | 0;
19325 }
19326 return [quotient, remainder | 0];
19327 }
19328
19329 function divModAny(self, v) {
19330 var value, n = parseValue(v);
19331 var a = self.value, b = n.value;
19332 var quotient;
19333 if (b === 0) throw new Error("Cannot divide by zero");
19334 if (self.isSmall) {
19335 if (n.isSmall) {
19336 return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)];
19337 }
19338 return [Integer[0], self];
19339 }
19340 if (n.isSmall) {
19341 if (b === 1) return [self, Integer[0]];
19342 if (b == -1) return [self.negate(), Integer[0]];
19343 var abs = Math.abs(b);
19344 if (abs < BASE) {
19345 value = divModSmall(a, abs);
19346 quotient = arrayToSmall(value[0]);
19347 var remainder = value[1];
19348 if (self.sign) remainder = -remainder;
19349 if (typeof quotient === "number") {
19350 if (self.sign !== n.sign) quotient = -quotient;
19351 return [new SmallInteger(quotient), new SmallInteger(remainder)];
19352 }
19353 return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)];
19354 }
19355 b = smallToArray(abs);
19356 }
19357 var comparison = compareAbs(a, b);
19358 if (comparison === -1) return [Integer[0], self];
19359 if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]];
19360
19361 // divMod1 is faster on smaller input sizes
19362 if (a.length + b.length <= 200)
19363 value = divMod1(a, b);
19364 else value = divMod2(a, b);
19365
19366 quotient = value[0];
19367 var qSign = self.sign !== n.sign,
19368 mod = value[1],
19369 mSign = self.sign;
19370 if (typeof quotient === "number") {
19371 if (qSign) quotient = -quotient;
19372 quotient = new SmallInteger(quotient);
19373 } else quotient = new BigInteger(quotient, qSign);
19374 if (typeof mod === "number") {
19375 if (mSign) mod = -mod;
19376 mod = new SmallInteger(mod);
19377 } else mod = new BigInteger(mod, mSign);
19378 return [quotient, mod];
19379 }
19380
19381 BigInteger.prototype.divmod = function (v) {
19382 var result = divModAny(this, v);
19383 return {
19384 quotient: result[0],
19385 remainder: result[1]
19386 };
19387 };
19388 SmallInteger.prototype.divmod = BigInteger.prototype.divmod;
19389
19390 BigInteger.prototype.divide = function (v) {
19391 return divModAny(this, v)[0];
19392 };
19393 SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide;
19394
19395 BigInteger.prototype.mod = function (v) {
19396 return divModAny(this, v)[1];
19397 };
19398 SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod;
19399
19400 BigInteger.prototype.pow = function (v) {
19401 var n = parseValue(v),
19402 a = this.value,
19403 b = n.value,
19404 value, x, y;
19405 if (b === 0) return Integer[1];
19406 if (a === 0) return Integer[0];
19407 if (a === 1) return Integer[1];
19408 if (a === -1) return n.isEven() ? Integer[1] : Integer[-1];
19409 if (n.sign) {
19410 return Integer[0];
19411 }
19412 if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large.");
19413 if (this.isSmall) {
19414 if (isPrecise(value = Math.pow(a, b)))
19415 return new SmallInteger(truncate(value));
19416 }
19417 x = this;
19418 y = Integer[1];
19419 while (true) {
19420 if (b & 1 === 1) {
19421 y = y.times(x);
19422 --b;
19423 }
19424 if (b === 0) break;
19425 b /= 2;
19426 x = x.square();
19427 }
19428 return y;
19429 };
19430 SmallInteger.prototype.pow = BigInteger.prototype.pow;
19431
19432 BigInteger.prototype.modPow = function (exp, mod) {
19433 exp = parseValue(exp);
19434 mod = parseValue(mod);
19435 if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0");
19436 var r = Integer[1],
19437 base = this.mod(mod);
19438 while (exp.isPositive()) {
19439 if (base.isZero()) return Integer[0];
19440 if (exp.isOdd()) r = r.multiply(base).mod(mod);
19441 exp = exp.divide(2);
19442 base = base.square().mod(mod);
19443 }
19444 return r;
19445 };
19446 SmallInteger.prototype.modPow = BigInteger.prototype.modPow;
19447
19448 function compareAbs(a, b) {
19449 if (a.length !== b.length) {
19450 return a.length > b.length ? 1 : -1;
19451 }
19452 for (var i = a.length - 1; i >= 0; i--) {
19453 if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1;
19454 }
19455 return 0;
19456 }
19457
19458 BigInteger.prototype.compareAbs = function (v) {
19459 var n = parseValue(v),
19460 a = this.value,
19461 b = n.value;
19462 if (n.isSmall) return 1;
19463 return compareAbs(a, b);
19464 };
19465 SmallInteger.prototype.compareAbs = function (v) {
19466 var n = parseValue(v),
19467 a = Math.abs(this.value),
19468 b = n.value;
19469 if (n.isSmall) {
19470 b = Math.abs(b);
19471 return a === b ? 0 : a > b ? 1 : -1;
19472 }
19473 return -1;
19474 };
19475
19476 BigInteger.prototype.compare = function (v) {
19477 // See discussion about comparison with Infinity:
19478 // https://github.com/peterolson/BigInteger.js/issues/61
19479 if (v === Infinity) {
19480 return -1;
19481 }
19482 if (v === -Infinity) {
19483 return 1;
19484 }
19485
19486 var n = parseValue(v),
19487 a = this.value,
19488 b = n.value;
19489 if (this.sign !== n.sign) {
19490 return n.sign ? 1 : -1;
19491 }
19492 if (n.isSmall) {
19493 return this.sign ? -1 : 1;
19494 }
19495 return compareAbs(a, b) * (this.sign ? -1 : 1);
19496 };
19497 BigInteger.prototype.compareTo = BigInteger.prototype.compare;
19498
19499 SmallInteger.prototype.compare = function (v) {
19500 if (v === Infinity) {
19501 return -1;
19502 }
19503 if (v === -Infinity) {
19504 return 1;
19505 }
19506
19507 var n = parseValue(v),
19508 a = this.value,
19509 b = n.value;
19510 if (n.isSmall) {
19511 return a == b ? 0 : a > b ? 1 : -1;
19512 }
19513 if (a < 0 !== n.sign) {
19514 return a < 0 ? -1 : 1;
19515 }
19516 return a < 0 ? 1 : -1;
19517 };
19518 SmallInteger.prototype.compareTo = SmallInteger.prototype.compare;
19519
19520 BigInteger.prototype.equals = function (v) {
19521 return this.compare(v) === 0;
19522 };
19523 SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals;
19524
19525 BigInteger.prototype.notEquals = function (v) {
19526 return this.compare(v) !== 0;
19527 };
19528 SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals;
19529
19530 BigInteger.prototype.greater = function (v) {
19531 return this.compare(v) > 0;
19532 };
19533 SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater;
19534
19535 BigInteger.prototype.lesser = function (v) {
19536 return this.compare(v) < 0;
19537 };
19538 SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser;
19539
19540 BigInteger.prototype.greaterOrEquals = function (v) {
19541 return this.compare(v) >= 0;
19542 };
19543 SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals;
19544
19545 BigInteger.prototype.lesserOrEquals = function (v) {
19546 return this.compare(v) <= 0;
19547 };
19548 SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals;
19549
19550 BigInteger.prototype.isEven = function () {
19551 return (this.value[0] & 1) === 0;
19552 };
19553 SmallInteger.prototype.isEven = function () {
19554 return (this.value & 1) === 0;
19555 };
19556
19557 BigInteger.prototype.isOdd = function () {
19558 return (this.value[0] & 1) === 1;
19559 };
19560 SmallInteger.prototype.isOdd = function () {
19561 return (this.value & 1) === 1;
19562 };
19563
19564 BigInteger.prototype.isPositive = function () {
19565 return !this.sign;
19566 };
19567 SmallInteger.prototype.isPositive = function () {
19568 return this.value > 0;
19569 };
19570
19571 BigInteger.prototype.isNegative = function () {
19572 return this.sign;
19573 };
19574 SmallInteger.prototype.isNegative = function () {
19575 return this.value < 0;
19576 };
19577
19578 BigInteger.prototype.isUnit = function () {
19579 return false;
19580 };
19581 SmallInteger.prototype.isUnit = function () {
19582 return Math.abs(this.value) === 1;
19583 };
19584
19585 BigInteger.prototype.isZero = function () {
19586 return false;
19587 };
19588 SmallInteger.prototype.isZero = function () {
19589 return this.value === 0;
19590 };
19591 BigInteger.prototype.isDivisibleBy = function (v) {
19592 var n = parseValue(v);
19593 var value = n.value;
19594 if (value === 0) return false;
19595 if (value === 1) return true;
19596 if (value === 2) return this.isEven();
19597 return this.mod(n).equals(Integer[0]);
19598 };
19599 SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy;
19600
19601 function isBasicPrime(v) {
19602 var n = v.abs();
19603 if (n.isUnit()) return false;
19604 if (n.equals(2) || n.equals(3) || n.equals(5)) return true;
19605 if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false;
19606 if (n.lesser(25)) return true;
19607 // we don't know if it's prime: let the other functions figure it out
19608 }
19609
19610 BigInteger.prototype.isPrime = function () {
19611 var isPrime = isBasicPrime(this);
19612 if (isPrime !== undefined) return isPrime;
19613 var n = this.abs(),
19614 nPrev = n.prev();
19615 var a = [2, 3, 5, 7, 11, 13, 17, 19],
19616 b = nPrev,
19617 d, t, i, x;
19618 while (b.isEven()) b = b.divide(2);
19619 for (i = 0; i < a.length; i++) {
19620 x = bigInt(a[i]).modPow(b, n);
19621 if (x.equals(Integer[1]) || x.equals(nPrev)) continue;
19622 for (t = true, d = b; t && d.lesser(nPrev) ; d = d.multiply(2)) {
19623 x = x.square().mod(n);
19624 if (x.equals(nPrev)) t = false;
19625 }
19626 if (t) return false;
19627 }
19628 return true;
19629 };
19630 SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime;
19631
19632 BigInteger.prototype.isProbablePrime = function (iterations) {
19633 var isPrime = isBasicPrime(this);
19634 if (isPrime !== undefined) return isPrime;
19635 var n = this.abs();
19636 var t = iterations === undefined ? 5 : iterations;
19637 // use the Fermat primality test
19638 for (var i = 0; i < t; i++) {
19639 var a = bigInt.randBetween(2, n.minus(2));
19640 if (!a.modPow(n.prev(), n).isUnit()) return false; // definitely composite
19641 }
19642 return true; // large chance of being prime
19643 };
19644 SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime;
19645
19646 BigInteger.prototype.next = function () {
19647 var value = this.value;
19648 if (this.sign) {
19649 return subtractSmall(value, 1, this.sign);
19650 }
19651 return new BigInteger(addSmall(value, 1), this.sign);
19652 };
19653 SmallInteger.prototype.next = function () {
19654 var value = this.value;
19655 if (value + 1 < MAX_INT) return new SmallInteger(value + 1);
19656 return new BigInteger(MAX_INT_ARR, false);
19657 };
19658
19659 BigInteger.prototype.prev = function () {
19660 var value = this.value;
19661 if (this.sign) {
19662 return new BigInteger(addSmall(value, 1), true);
19663 }
19664 return subtractSmall(value, 1, this.sign);
19665 };
19666 SmallInteger.prototype.prev = function () {
19667 var value = this.value;
19668 if (value - 1 > -MAX_INT) return new SmallInteger(value - 1);
19669 return new BigInteger(MAX_INT_ARR, true);
19670 };
19671
19672 var powersOfTwo = [1];
19673 while (powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]);
19674 var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1];
19675
19676 function shift_isSmall(n) {
19677 return ((typeof n === "number" || typeof n === "string") && +Math.abs(n) <= BASE) ||
19678 (n instanceof BigInteger && n.value.length <= 1);
19679 }
19680
19681 BigInteger.prototype.shiftLeft = function (n) {
19682 if (!shift_isSmall(n)) {
19683 throw new Error(String(n) + " is too large for shifting.");
19684 }
19685 n = +n;
19686 if (n < 0) return this.shiftRight(-n);
19687 var result = this;
19688 while (n >= powers2Length) {
19689 result = result.multiply(highestPower2);
19690 n -= powers2Length - 1;
19691 }
19692 return result.multiply(powersOfTwo[n]);
19693 };
19694 SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft;
19695
19696 BigInteger.prototype.shiftRight = function (n) {
19697 var remQuo;
19698 if (!shift_isSmall(n)) {
19699 throw new Error(String(n) + " is too large for shifting.");
19700 }
19701 n = +n;
19702 if (n < 0) return this.shiftLeft(-n);
19703 var result = this;
19704 while (n >= powers2Length) {
19705 if (result.isZero()) return result;
19706 remQuo = divModAny(result, highestPower2);
19707 result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];
19708 n -= powers2Length - 1;
19709 }
19710 remQuo = divModAny(result, powersOfTwo[n]);
19711 return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];
19712 };
19713 SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight;
19714
19715 function bitwise(x, y, fn) {
19716 y = parseValue(y);
19717 var xSign = x.isNegative(), ySign = y.isNegative();
19718 var xRem = xSign ? x.not() : x,
19719 yRem = ySign ? y.not() : y;
19720 var xBits = [], yBits = [];
19721 var xStop = false, yStop = false;
19722 while (!xStop || !yStop) {
19723 if (xRem.isZero()) { // virtual sign extension for simulating two's complement
19724 xStop = true;
19725 xBits.push(xSign ? 1 : 0);
19726 }
19727 else if (xSign) xBits.push(xRem.isEven() ? 1 : 0); // two's complement for negative numbers
19728 else xBits.push(xRem.isEven() ? 0 : 1);
19729
19730 if (yRem.isZero()) {
19731 yStop = true;
19732 yBits.push(ySign ? 1 : 0);
19733 }
19734 else if (ySign) yBits.push(yRem.isEven() ? 1 : 0);
19735 else yBits.push(yRem.isEven() ? 0 : 1);
19736
19737 xRem = xRem.over(2);
19738 yRem = yRem.over(2);
19739 }
19740 var result = [];
19741 for (var i = 0; i < xBits.length; i++) result.push(fn(xBits[i], yBits[i]));
19742 var sum = bigInt(result.pop()).negate().times(bigInt(2).pow(result.length));
19743 while (result.length) {
19744 sum = sum.add(bigInt(result.pop()).times(bigInt(2).pow(result.length)));
19745 }
19746 return sum;
19747 }
19748
19749 BigInteger.prototype.not = function () {
19750 return this.negate().prev();
19751 };
19752 SmallInteger.prototype.not = BigInteger.prototype.not;
19753
19754 BigInteger.prototype.and = function (n) {
19755 return bitwise(this, n, function (a, b) { return a & b; });
19756 };
19757 SmallInteger.prototype.and = BigInteger.prototype.and;
19758
19759 BigInteger.prototype.or = function (n) {
19760 return bitwise(this, n, function (a, b) { return a | b; });
19761 };
19762 SmallInteger.prototype.or = BigInteger.prototype.or;
19763
19764 BigInteger.prototype.xor = function (n) {
19765 return bitwise(this, n, function (a, b) { return a ^ b; });
19766 };
19767 SmallInteger.prototype.xor = BigInteger.prototype.xor;
19768
19769 var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I;
19770 function roughLOB(n) { // get lowestOneBit (rough)
19771 // SmallInteger: return Min(lowestOneBit(n), 1 << 30)
19772 // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7]
19773 var v = n.value, x = typeof v === "number" ? v | LOBMASK_I : v[0] + v[1] * BASE | LOBMASK_BI;
19774 return x & -x;
19775 }
19776
19777 function max(a, b) {
19778 a = parseValue(a);
19779 b = parseValue(b);
19780 return a.greater(b) ? a : b;
19781 }
19782 function min(a,b) {
19783 a = parseValue(a);
19784 b = parseValue(b);
19785 return a.lesser(b) ? a : b;
19786 }
19787 function gcd(a, b) {
19788 a = parseValue(a).abs();
19789 b = parseValue(b).abs();
19790 if (a.equals(b)) return a;
19791 if (a.isZero()) return b;
19792 if (b.isZero()) return a;
19793 var c = Integer[1], d, t;
19794 while (a.isEven() && b.isEven()) {
19795 d = Math.min(roughLOB(a), roughLOB(b));
19796 a = a.divide(d);
19797 b = b.divide(d);
19798 c = c.multiply(d);
19799 }
19800 while (a.isEven()) {
19801 a = a.divide(roughLOB(a));
19802 }
19803 do {
19804 while (b.isEven()) {
19805 b = b.divide(roughLOB(b));
19806 }
19807 if (a.greater(b)) {
19808 t = b; b = a; a = t;
19809 }
19810 b = b.subtract(a);
19811 } while (!b.isZero());
19812 return c.isUnit() ? a : a.multiply(c);
19813 }
19814 function lcm(a, b) {
19815 a = parseValue(a).abs();
19816 b = parseValue(b).abs();
19817 return a.divide(gcd(a, b)).multiply(b);
19818 }
19819 function randBetween(a, b) {
19820 a = parseValue(a);
19821 b = parseValue(b);
19822 var low = min(a, b), high = max(a, b);
19823 var range = high.subtract(low);
19824 if (range.isSmall) return low.add(Math.round(Math.random() * range));
19825 var length = range.value.length - 1;
19826 var result = [], restricted = true;
19827 for (var i = length; i >= 0; i--) {
19828 var top = restricted ? range.value[i] : BASE;
19829 var digit = truncate(Math.random() * top);
19830 result.unshift(digit);
19831 if (digit < top) restricted = false;
19832 }
19833 result = arrayToSmall(result);
19834 return low.add(typeof result === "number" ? new SmallInteger(result) : new BigInteger(result, false));
19835 }
19836 var parseBase = function (text, base) {
19837 var val = Integer[0], pow = Integer[1],
19838 length = text.length;
19839 if (2 <= base && base <= 36) {
19840 if (length <= LOG_MAX_INT / Math.log(base)) {
19841 return new SmallInteger(parseInt(text, base));
19842 }
19843 }
19844 base = parseValue(base);
19845 var digits = [];
19846 var i;
19847 var isNegative = text[0] === "-";
19848 for (i = isNegative ? 1 : 0; i < text.length; i++) {
19849 var c = text[i].toLowerCase(),
19850 charCode = c.charCodeAt(0);
19851 if (48 <= charCode && charCode <= 57) digits.push(parseValue(c));
19852 else if (97 <= charCode && charCode <= 122) digits.push(parseValue(c.charCodeAt(0) - 87));
19853 else if (c === "<") {
19854 var start = i;
19855 do { i++; } while (text[i] !== ">");
19856 digits.push(parseValue(text.slice(start + 1, i)));
19857 }
19858 else throw new Error(c + " is not a valid character");
19859 }
19860 digits.reverse();
19861 for (i = 0; i < digits.length; i++) {
19862 val = val.add(digits[i].times(pow));
19863 pow = pow.times(base);
19864 }
19865 return isNegative ? val.negate() : val;
19866 };
19867
19868 function stringify(digit) {
19869 var v = digit.value;
19870 if (typeof v === "number") v = [v];
19871 if (v.length === 1 && v[0] <= 35) {
19872 return "0123456789abcdefghijklmnopqrstuvwxyz".charAt(v[0]);
19873 }
19874 return "<" + v + ">";
19875 }
19876 function toBase(n, base) {
19877 base = bigInt(base);
19878 if (base.isZero()) {
19879 if (n.isZero()) return "0";
19880 throw new Error("Cannot convert nonzero numbers to base 0.");
19881 }
19882 if (base.equals(-1)) {
19883 if (n.isZero()) return "0";
19884 if (n.isNegative()) return new Array(1 - n).join("10");
19885 return "1" + new Array(+n).join("01");
19886 }
19887 var minusSign = "";
19888 if (n.isNegative() && base.isPositive()) {
19889 minusSign = "-";
19890 n = n.abs();
19891 }
19892 if (base.equals(1)) {
19893 if (n.isZero()) return "0";
19894 return minusSign + new Array(+n + 1).join(1);
19895 }
19896 var out = [];
19897 var left = n, divmod;
19898 while (left.isNegative() || left.compareAbs(base) >= 0) {
19899 divmod = left.divmod(base);
19900 left = divmod.quotient;
19901 var digit = divmod.remainder;
19902 if (digit.isNegative()) {
19903 digit = base.minus(digit).abs();
19904 left = left.next();
19905 }
19906 out.push(stringify(digit));
19907 }
19908 out.push(stringify(left));
19909 return minusSign + out.reverse().join("");
19910 }
19911
19912 BigInteger.prototype.toString = function (radix) {
19913 if (radix === undefined) radix = 10;
19914 if (radix !== 10) return toBase(this, radix);
19915 var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit;
19916 while (--l >= 0) {
19917 digit = String(v[l]);
19918 str += zeros.slice(digit.length) + digit;
19919 }
19920 var sign = this.sign ? "-" : "";
19921 return sign + str;
19922 };
19923 SmallInteger.prototype.toString = function (radix) {
19924 if (radix === undefined) radix = 10;
19925 if (radix != 10) return toBase(this, radix);
19926 return String(this.value);
19927 };
19928
19929 BigInteger.prototype.valueOf = function () {
19930 return +this.toString();
19931 };
19932 BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf;
19933
19934 SmallInteger.prototype.valueOf = function () {
19935 return this.value;
19936 };
19937 SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf;
19938
19939 function parseStringValue(v) {
19940 if (isPrecise(+v)) {
19941 var x = +v;
19942 if (x === truncate(x))
19943 return new SmallInteger(x);
19944 throw "Invalid integer: " + v;
19945 }
19946 var sign = v[0] === "-";
19947 if (sign) v = v.slice(1);
19948 var split = v.split(/e/i);
19949 if (split.length > 2) throw new Error("Invalid integer: " + split.join("e"));
19950 if (split.length === 2) {
19951 var exp = split[1];
19952 if (exp[0] === "+") exp = exp.slice(1);
19953 exp = +exp;
19954 if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent.");
19955 var text = split[0];
19956 var decimalPlace = text.indexOf(".");
19957 if (decimalPlace >= 0) {
19958 exp -= text.length - decimalPlace - 1;
19959 text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1);
19960 }
19961 if (exp < 0) throw new Error("Cannot include negative exponent part for integers");
19962 text += (new Array(exp + 1)).join("0");
19963 v = text;
19964 }
19965 var isValid = /^([0-9][0-9]*)$/.test(v);
19966 if (!isValid) throw new Error("Invalid integer: " + v);
19967 var r = [], max = v.length, l = LOG_BASE, min = max - l;
19968 while (max > 0) {
19969 r.push(+v.slice(min, max));
19970 min -= l;
19971 if (min < 0) min = 0;
19972 max -= l;
19973 }
19974 trim(r);
19975 return new BigInteger(r, sign);
19976 }
19977
19978 function parseNumberValue(v) {
19979 if (isPrecise(v)) {
19980 if (v !== truncate(v)) throw new Error(v + " is not an integer.");
19981 return new SmallInteger(v);
19982 }
19983 return parseStringValue(v.toString());
19984 }
19985
19986 function parseValue(v) {
19987 if (typeof v === "number") {
19988 return parseNumberValue(v);
19989 }
19990 if (typeof v === "string") {
19991 return parseStringValue(v);
19992 }
19993 return v;
19994 }
19995 // Pre-define numbers in range [-999,999]
19996 for (var i = 0; i < 1000; i++) {
19997 Integer[i] = new SmallInteger(i);
19998 if (i > 0) Integer[-i] = new SmallInteger(-i);
19999 }
20000 // Backwards compatibility
20001 Integer.one = Integer[1];
20002 Integer.zero = Integer[0];
20003 Integer.minusOne = Integer[-1];
20004 Integer.max = max;
20005 Integer.min = min;
20006 Integer.gcd = gcd;
20007 Integer.lcm = lcm;
20008 Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger; };
20009 Integer.randBetween = randBetween;
20010 return Integer;
20011})();
20012
20013// Node.js check
20014if (typeof module !== "undefined" && module.hasOwnProperty("exports")) {
20015 module.exports = bigInt;
20016}
20017
20018},{}],14:[function(require,module,exports){
20019this.j$ = this.jStat = (function(Math, undefined) {
20020
20021// For quick reference.
20022var concat = Array.prototype.concat;
20023var slice = Array.prototype.slice;
20024var toString = Object.prototype.toString;
20025
20026// Calculate correction for IEEE error
20027// TODO: This calculation can be improved.
20028function calcRdx(n, m) {
20029 var val = n > m ? n : m;
20030 return Math.pow(10,
20031 17 - ~~(Math.log(((val > 0) ? val : -val)) * Math.LOG10E));
20032}
20033
20034
20035var isArray = Array.isArray || function isArray(arg) {
20036 return toString.call(arg) === '[object Array]';
20037};
20038
20039
20040function isFunction(arg) {
20041 return toString.call(arg) === '[object Function]';
20042}
20043
20044
20045function isNumber(arg) {
20046 return typeof arg === 'number' && arg === arg;
20047}
20048
20049
20050// Converts the jStat matrix to vector.
20051function toVector(arr) {
20052 return concat.apply([], arr);
20053}
20054
20055
20056// The one and only jStat constructor.
20057function jStat() {
20058 return new jStat._init(arguments);
20059}
20060
20061
20062// TODO: Remove after all references in src files have been removed.
20063jStat.fn = jStat.prototype;
20064
20065
20066// By separating the initializer from the constructor it's easier to handle
20067// always returning a new instance whether "new" was used or not.
20068jStat._init = function _init(args) {
20069 var i;
20070
20071 // If first argument is an array, must be vector or matrix.
20072 if (isArray(args[0])) {
20073 // Check if matrix.
20074 if (isArray(args[0][0])) {
20075 // See if a mapping function was also passed.
20076 if (isFunction(args[1]))
20077 args[0] = jStat.map(args[0], args[1]);
20078 // Iterate over each is faster than this.push.apply(this, args[0].
20079 for (i = 0; i < args[0].length; i++)
20080 this[i] = args[0][i];
20081 this.length = args[0].length;
20082
20083 // Otherwise must be a vector.
20084 } else {
20085 this[0] = isFunction(args[1]) ? jStat.map(args[0], args[1]) : args[0];
20086 this.length = 1;
20087 }
20088
20089 // If first argument is number, assume creation of sequence.
20090 } else if (isNumber(args[0])) {
20091 this[0] = jStat.seq.apply(null, args);
20092 this.length = 1;
20093
20094 // Handle case when jStat object is passed to jStat.
20095 } else if (args[0] instanceof jStat) {
20096 // Duplicate the object and pass it back.
20097 return jStat(args[0].toArray());
20098
20099 // Unexpected argument value, return empty jStat object.
20100 // TODO: This is strange behavior. Shouldn't this throw or some such to let
20101 // the user know they had bad arguments?
20102 } else {
20103 this[0] = [];
20104 this.length = 1;
20105 }
20106
20107 return this;
20108};
20109jStat._init.prototype = jStat.prototype;
20110jStat._init.constructor = jStat;
20111
20112
20113// Utility functions.
20114// TODO: for internal use only?
20115jStat.utils = {
20116 calcRdx: calcRdx,
20117 isArray: isArray,
20118 isFunction: isFunction,
20119 isNumber: isNumber,
20120 toVector: toVector
20121};
20122
20123
20124// Easily extend the jStat object.
20125// TODO: is this seriously necessary?
20126jStat.extend = function extend(obj) {
20127 var i, j;
20128
20129 if (arguments.length === 1) {
20130 for (j in obj)
20131 jStat[j] = obj[j];
20132 return this;
20133 }
20134
20135 for (i = 1; i < arguments.length; i++) {
20136 for (j in arguments[i])
20137 obj[j] = arguments[i][j];
20138 }
20139
20140 return obj;
20141};
20142
20143
20144// Returns the number of rows in the matrix.
20145jStat.rows = function rows(arr) {
20146 return arr.length || 1;
20147};
20148
20149
20150// Returns the number of columns in the matrix.
20151jStat.cols = function cols(arr) {
20152 return arr[0].length || 1;
20153};
20154
20155
20156// Returns the dimensions of the object { rows: i, cols: j }
20157jStat.dimensions = function dimensions(arr) {
20158 return {
20159 rows: jStat.rows(arr),
20160 cols: jStat.cols(arr)
20161 };
20162};
20163
20164
20165// Returns a specified row as a vector
20166jStat.row = function row(arr, index) {
20167 return arr[index];
20168};
20169
20170
20171// Returns the specified column as a vector
20172jStat.col = function cols(arr, index) {
20173 var column = new Array(arr.length);
20174 for (var i = 0; i < arr.length; i++)
20175 column[i] = [arr[i][index]];
20176 return column;
20177};
20178
20179
20180// Returns the diagonal of the matrix
20181jStat.diag = function diag(arr) {
20182 var nrow = jStat.rows(arr);
20183 var res = new Array(nrow);
20184 for (var row = 0; row < nrow; row++)
20185 res[row] = [arr[row][row]];
20186 return res;
20187};
20188
20189
20190// Returns the anti-diagonal of the matrix
20191jStat.antidiag = function antidiag(arr) {
20192 var nrow = jStat.rows(arr) - 1;
20193 var res = new Array(nrow);
20194 for (var i = 0; nrow >= 0; nrow--, i++)
20195 res[i] = [arr[i][nrow]];
20196 return res;
20197};
20198
20199// Transpose a matrix or array.
20200jStat.transpose = function transpose(arr) {
20201 var obj = [];
20202 var objArr, rows, cols, j, i;
20203
20204 // Make sure arr is in matrix format.
20205 if (!isArray(arr[0]))
20206 arr = [arr];
20207
20208 rows = arr.length;
20209 cols = arr[0].length;
20210
20211 for (i = 0; i < cols; i++) {
20212 objArr = new Array(rows);
20213 for (j = 0; j < rows; j++)
20214 objArr[j] = arr[j][i];
20215 obj.push(objArr);
20216 }
20217
20218 // If obj is vector, return only single array.
20219 return obj.length === 1 ? obj[0] : obj;
20220};
20221
20222
20223// Map a function to an array or array of arrays.
20224// "toAlter" is an internal variable.
20225jStat.map = function map(arr, func, toAlter) {
20226 var row, nrow, ncol, res, col;
20227
20228 if (!isArray(arr[0]))
20229 arr = [arr];
20230
20231 nrow = arr.length;
20232 ncol = arr[0].length;
20233 res = toAlter ? arr : new Array(nrow);
20234
20235 for (row = 0; row < nrow; row++) {
20236 // if the row doesn't exist, create it
20237 if (!res[row])
20238 res[row] = new Array(ncol);
20239 for (col = 0; col < ncol; col++)
20240 res[row][col] = func(arr[row][col], row, col);
20241 }
20242
20243 return res.length === 1 ? res[0] : res;
20244};
20245
20246
20247// Cumulatively combine the elements of an array or array of arrays using a function.
20248jStat.cumreduce = function cumreduce(arr, func, toAlter) {
20249 var row, nrow, ncol, res, col;
20250
20251 if (!isArray(arr[0]))
20252 arr = [arr];
20253
20254 nrow = arr.length;
20255 ncol = arr[0].length;
20256 res = toAlter ? arr : new Array(nrow);
20257
20258 for (row = 0; row < nrow; row++) {
20259 // if the row doesn't exist, create it
20260 if (!res[row])
20261 res[row] = new Array(ncol);
20262 if (ncol > 0)
20263 res[row][0] = arr[row][0];
20264 for (col = 1; col < ncol; col++)
20265 res[row][col] = func(res[row][col-1], arr[row][col]);
20266 }
20267 return res.length === 1 ? res[0] : res;
20268};
20269
20270
20271// Destructively alter an array.
20272jStat.alter = function alter(arr, func) {
20273 return jStat.map(arr, func, true);
20274};
20275
20276
20277// Generate a rows x cols matrix according to the supplied function.
20278jStat.create = function create(rows, cols, func) {
20279 var res = new Array(rows);
20280 var i, j;
20281
20282 if (isFunction(cols)) {
20283 func = cols;
20284 cols = rows;
20285 }
20286
20287 for (i = 0; i < rows; i++) {
20288 res[i] = new Array(cols);
20289 for (j = 0; j < cols; j++)
20290 res[i][j] = func(i, j);
20291 }
20292
20293 return res;
20294};
20295
20296
20297function retZero() { return 0; }
20298
20299
20300// Generate a rows x cols matrix of zeros.
20301jStat.zeros = function zeros(rows, cols) {
20302 if (!isNumber(cols))
20303 cols = rows;
20304 return jStat.create(rows, cols, retZero);
20305};
20306
20307
20308function retOne() { return 1; }
20309
20310
20311// Generate a rows x cols matrix of ones.
20312jStat.ones = function ones(rows, cols) {
20313 if (!isNumber(cols))
20314 cols = rows;
20315 return jStat.create(rows, cols, retOne);
20316};
20317
20318
20319// Generate a rows x cols matrix of uniformly random numbers.
20320jStat.rand = function rand(rows, cols) {
20321 if (!isNumber(cols))
20322 cols = rows;
20323 return jStat.create(rows, cols, Math.random);
20324};
20325
20326
20327function retIdent(i, j) { return i === j ? 1 : 0; }
20328
20329
20330// Generate an identity matrix of size row x cols.
20331jStat.identity = function identity(rows, cols) {
20332 if (!isNumber(cols))
20333 cols = rows;
20334 return jStat.create(rows, cols, retIdent);
20335};
20336
20337
20338// Tests whether a matrix is symmetric
20339jStat.symmetric = function symmetric(arr) {
20340 var issymmetric = true;
20341 var size = arr.length;
20342 var row, col;
20343
20344 if (arr.length !== arr[0].length)
20345 return false;
20346
20347 for (row = 0; row < size; row++) {
20348 for (col = 0; col < size; col++)
20349 if (arr[col][row] !== arr[row][col])
20350 return false;
20351 }
20352
20353 return true;
20354};
20355
20356
20357// Set all values to zero.
20358jStat.clear = function clear(arr) {
20359 return jStat.alter(arr, retZero);
20360};
20361
20362
20363// Generate sequence.
20364jStat.seq = function seq(min, max, length, func) {
20365 if (!isFunction(func))
20366 func = false;
20367
20368 var arr = [];
20369 var hival = calcRdx(min, max);
20370 var step = (max * hival - min * hival) / ((length - 1) * hival);
20371 var current = min;
20372 var cnt;
20373
20374 // Current is assigned using a technique to compensate for IEEE error.
20375 // TODO: Needs better implementation.
20376 for (cnt = 0;
20377 current <= max;
20378 cnt++, current = (min * hival + step * hival * cnt) / hival) {
20379 arr.push((func ? func(current, cnt) : current));
20380 }
20381
20382 return arr;
20383};
20384
20385
20386// TODO: Go over this entire implementation. Seems a tragic waste of resources
20387// doing all this work. Instead, and while ugly, use new Function() to generate
20388// a custom function for each static method.
20389
20390// Quick reference.
20391var jProto = jStat.prototype;
20392
20393// Default length.
20394jProto.length = 0;
20395
20396// For internal use only.
20397// TODO: Check if they're actually used, and if they are then rename them
20398// to _*
20399jProto.push = Array.prototype.push;
20400jProto.sort = Array.prototype.sort;
20401jProto.splice = Array.prototype.splice;
20402jProto.slice = Array.prototype.slice;
20403
20404
20405// Return a clean array.
20406jProto.toArray = function toArray() {
20407 return this.length > 1 ? slice.call(this) : slice.call(this)[0];
20408};
20409
20410
20411// Map a function to a matrix or vector.
20412jProto.map = function map(func, toAlter) {
20413 return jStat(jStat.map(this, func, toAlter));
20414};
20415
20416
20417// Cumulatively combine the elements of a matrix or vector using a function.
20418jProto.cumreduce = function cumreduce(func, toAlter) {
20419 return jStat(jStat.cumreduce(this, func, toAlter));
20420};
20421
20422
20423// Destructively alter an array.
20424jProto.alter = function alter(func) {
20425 jStat.alter(this, func);
20426 return this;
20427};
20428
20429
20430// Extend prototype with methods that have no argument.
20431(function(funcs) {
20432 for (var i = 0; i < funcs.length; i++) (function(passfunc) {
20433 jProto[passfunc] = function(func) {
20434 var self = this,
20435 results;
20436 // Check for callback.
20437 if (func) {
20438 setTimeout(function() {
20439 func.call(self, jProto[passfunc].call(self));
20440 });
20441 return this;
20442 }
20443 results = jStat[passfunc](this);
20444 return isArray(results) ? jStat(results) : results;
20445 };
20446 })(funcs[i]);
20447})('transpose clear symmetric rows cols dimensions diag antidiag'.split(' '));
20448
20449
20450// Extend prototype with methods that have one argument.
20451(function(funcs) {
20452 for (var i = 0; i < funcs.length; i++) (function(passfunc) {
20453 jProto[passfunc] = function(index, func) {
20454 var self = this;
20455 // check for callback
20456 if (func) {
20457 setTimeout(function() {
20458 func.call(self, jProto[passfunc].call(self, index));
20459 });
20460 return this;
20461 }
20462 return jStat(jStat[passfunc](this, index));
20463 };
20464 })(funcs[i]);
20465})('row col'.split(' '));
20466
20467
20468// Extend prototype with simple shortcut methods.
20469(function(funcs) {
20470 for (var i = 0; i < funcs.length; i++) (function(passfunc) {
20471 jProto[passfunc] = new Function(
20472 'return jStat(jStat.' + passfunc + '.apply(null, arguments));');
20473 })(funcs[i]);
20474})('create zeros ones rand identity'.split(' '));
20475
20476
20477// Exposing jStat.
20478return jStat;
20479
20480}(Math));
20481(function(jStat, Math) {
20482
20483var isFunction = jStat.utils.isFunction;
20484
20485// Ascending functions for sort
20486function ascNum(a, b) { return a - b; }
20487
20488function clip(arg, min, max) {
20489 return Math.max(min, Math.min(arg, max));
20490}
20491
20492
20493// sum of an array
20494jStat.sum = function sum(arr) {
20495 var sum = 0;
20496 var i = arr.length;
20497 while (--i >= 0)
20498 sum += arr[i];
20499 return sum;
20500};
20501
20502
20503// sum squared
20504jStat.sumsqrd = function sumsqrd(arr) {
20505 var sum = 0;
20506 var i = arr.length;
20507 while (--i >= 0)
20508 sum += arr[i] * arr[i];
20509 return sum;
20510};
20511
20512
20513// sum of squared errors of prediction (SSE)
20514jStat.sumsqerr = function sumsqerr(arr) {
20515 var mean = jStat.mean(arr);
20516 var sum = 0;
20517 var i = arr.length;
20518 var tmp;
20519 while (--i >= 0) {
20520 tmp = arr[i] - mean;
20521 sum += tmp * tmp;
20522 }
20523 return sum;
20524};
20525
20526// sum of an array in each row
20527jStat.sumrow = function sumrow(arr) {
20528 var sum = 0;
20529 var i = arr.length;
20530 while (--i >= 0)
20531 sum += arr[i];
20532 return sum;
20533};
20534
20535// product of an array
20536jStat.product = function product(arr) {
20537 var prod = 1;
20538 var i = arr.length;
20539 while (--i >= 0)
20540 prod *= arr[i];
20541 return prod;
20542};
20543
20544
20545// minimum value of an array
20546jStat.min = function min(arr) {
20547 var low = arr[0];
20548 var i = 0;
20549 while (++i < arr.length)
20550 if (arr[i] < low)
20551 low = arr[i];
20552 return low;
20553};
20554
20555
20556// maximum value of an array
20557jStat.max = function max(arr) {
20558 var high = arr[0];
20559 var i = 0;
20560 while (++i < arr.length)
20561 if (arr[i] > high)
20562 high = arr[i];
20563 return high;
20564};
20565
20566
20567// unique values of an array
20568jStat.unique = function unique(arr) {
20569 var hash = {}, _arr = [];
20570 for(var i = 0; i < arr.length; i++) {
20571 if (!hash[arr[i]]) {
20572 hash[arr[i]] = true;
20573 _arr.push(arr[i]);
20574 }
20575 }
20576 return _arr;
20577};
20578
20579
20580// mean value of an array
20581jStat.mean = function mean(arr) {
20582 return jStat.sum(arr) / arr.length;
20583};
20584
20585
20586// mean squared error (MSE)
20587jStat.meansqerr = function meansqerr(arr) {
20588 return jStat.sumsqerr(arr) / arr.length;
20589};
20590
20591
20592// geometric mean of an array
20593jStat.geomean = function geomean(arr) {
20594 return Math.pow(jStat.product(arr), 1 / arr.length);
20595};
20596
20597
20598// median of an array
20599jStat.median = function median(arr) {
20600 var arrlen = arr.length;
20601 var _arr = arr.slice().sort(ascNum);
20602 // check if array is even or odd, then return the appropriate
20603 return !(arrlen & 1)
20604 ? (_arr[(arrlen / 2) - 1 ] + _arr[(arrlen / 2)]) / 2
20605 : _arr[(arrlen / 2) | 0 ];
20606};
20607
20608
20609// cumulative sum of an array
20610jStat.cumsum = function cumsum(arr) {
20611 return jStat.cumreduce(arr, function (a, b) { return a + b; });
20612};
20613
20614
20615// cumulative product of an array
20616jStat.cumprod = function cumprod(arr) {
20617 return jStat.cumreduce(arr, function (a, b) { return a * b; });
20618};
20619
20620
20621// successive differences of a sequence
20622jStat.diff = function diff(arr) {
20623 var diffs = [];
20624 var arrLen = arr.length;
20625 var i;
20626 for (i = 1; i < arrLen; i++)
20627 diffs.push(arr[i] - arr[i - 1]);
20628 return diffs;
20629};
20630
20631
20632// ranks of an array
20633jStat.rank = function (arr) {
20634 var arrlen = arr.length;
20635 var sorted = arr.slice().sort(ascNum);
20636 var ranks = new Array(arrlen);
20637 for (var i = 0; i < arrlen; i++) {
20638 var first = sorted.indexOf(arr[i]);
20639 var last = sorted.lastIndexOf(arr[i]);
20640 if (first === last) {
20641 var val = first;
20642 } else {
20643 var val = (first + last) / 2;
20644 }
20645 ranks[i] = val + 1;
20646 }
20647 return ranks;
20648};
20649
20650
20651// mode of an array
20652// if there are multiple modes of an array, return all of them
20653// is this the appropriate way of handling it?
20654jStat.mode = function mode(arr) {
20655 var arrLen = arr.length;
20656 var _arr = arr.slice().sort(ascNum);
20657 var count = 1;
20658 var maxCount = 0;
20659 var numMaxCount = 0;
20660 var mode_arr = [];
20661 var i;
20662
20663 for (i = 0; i < arrLen; i++) {
20664 if (_arr[i] === _arr[i + 1]) {
20665 count++;
20666 } else {
20667 if (count > maxCount) {
20668 mode_arr = [_arr[i]];
20669 maxCount = count;
20670 numMaxCount = 0;
20671 }
20672 // are there multiple max counts
20673 else if (count === maxCount) {
20674 mode_arr.push(_arr[i]);
20675 numMaxCount++;
20676 }
20677 // resetting count for new value in array
20678 count = 1;
20679 }
20680 }
20681
20682 return numMaxCount === 0 ? mode_arr[0] : mode_arr;
20683};
20684
20685
20686// range of an array
20687jStat.range = function range(arr) {
20688 return jStat.max(arr) - jStat.min(arr);
20689};
20690
20691// variance of an array
20692// flag = true indicates sample instead of population
20693jStat.variance = function variance(arr, flag) {
20694 return jStat.sumsqerr(arr) / (arr.length - (flag ? 1 : 0));
20695};
20696
20697// deviation of an array
20698jStat.deviation = function (arr) {
20699 var mean = jStat.mean(arr);
20700 var arrlen = arr.length;
20701 var dev = new Array(arrlen);
20702 for (var i = 0; i < arrlen; i++) {
20703 dev[i] = arr[i] - mean;
20704 }
20705 return dev;
20706};
20707
20708// standard deviation of an array
20709// flag = true indicates sample instead of population
20710jStat.stdev = function stdev(arr, flag) {
20711 return Math.sqrt(jStat.variance(arr, flag));
20712};
20713
20714
20715// mean deviation (mean absolute deviation) of an array
20716jStat.meandev = function meandev(arr) {
20717 var devSum = 0;
20718 var mean = jStat.mean(arr);
20719 var i;
20720 for (i = arr.length - 1; i >= 0; i--)
20721 devSum += Math.abs(arr[i] - mean);
20722 return devSum / arr.length;
20723};
20724
20725
20726// median deviation (median absolute deviation) of an array
20727jStat.meddev = function meddev(arr) {
20728 var devSum = 0;
20729 var median = jStat.median(arr);
20730 var i;
20731 for (i = arr.length - 1; i >= 0; i--)
20732 devSum += Math.abs(arr[i] - median);
20733 return devSum / arr.length;
20734};
20735
20736
20737// coefficient of variation
20738jStat.coeffvar = function coeffvar(arr) {
20739 return jStat.stdev(arr) / jStat.mean(arr);
20740};
20741
20742
20743// quartiles of an array
20744jStat.quartiles = function quartiles(arr) {
20745 var arrlen = arr.length;
20746 var _arr = arr.slice().sort(ascNum);
20747 return [
20748 _arr[ Math.round((arrlen) / 4) - 1 ],
20749 _arr[ Math.round((arrlen) / 2) - 1 ],
20750 _arr[ Math.round((arrlen) * 3 / 4) - 1 ]
20751 ];
20752};
20753
20754
20755// Arbitary quantiles of an array. Direct port of the scipy.stats
20756// implementation by Pierre GF Gerard-Marchant.
20757jStat.quantiles = function quantiles(arr, quantilesArray, alphap, betap) {
20758 var sortedArray = arr.slice().sort(ascNum);
20759 var quantileVals = [quantilesArray.length];
20760 var n = arr.length;
20761 var i, p, m, aleph, k, gamma;
20762
20763 if (typeof alphap === 'undefined')
20764 alphap = 3 / 8;
20765 if (typeof betap === 'undefined')
20766 betap = 3 / 8;
20767
20768 for (i = 0; i < quantilesArray.length; i++) {
20769 p = quantilesArray[i];
20770 m = alphap + p * (1 - alphap - betap);
20771 aleph = n * p + m;
20772 k = Math.floor(clip(aleph, 1, n - 1));
20773 gamma = clip(aleph - k, 0, 1);
20774 quantileVals[i] = (1 - gamma) * sortedArray[k - 1] + gamma * sortedArray[k];
20775 }
20776
20777 return quantileVals;
20778};
20779
20780// Returns the k-th percentile of values in a range, where k is in the
20781// range 0..1, exclusive.
20782jStat.percentile = function percentile(arr, k) {
20783 var _arr = arr.slice().sort(ascNum);
20784 var realIndex = k * (_arr.length - 1);
20785 var index = parseInt(realIndex);
20786 var frac = realIndex - index;
20787
20788 if (index + 1 < _arr.length) {
20789 return _arr[index] * (1 - frac) + _arr[index + 1] * frac;
20790 } else {
20791 return _arr[index];
20792 }
20793}
20794
20795
20796// The percentile rank of score in a given array. Returns the percentage
20797// of all values in the input array that are less than (kind='strict') or
20798// less or equal than (kind='weak') score. Default is weak.
20799jStat.percentileOfScore = function percentileOfScore(arr, score, kind) {
20800 var counter = 0;
20801 var len = arr.length;
20802 var strict = false;
20803 var value, i;
20804
20805 if (kind === 'strict')
20806 strict = true;
20807
20808 for (i = 0; i < len; i++) {
20809 value = arr[i];
20810 if ((strict && value < score) ||
20811 (!strict && value <= score)) {
20812 counter++;
20813 }
20814 }
20815
20816 return counter / len;
20817};
20818
20819
20820// Histogram (bin count) data
20821jStat.histogram = function histogram(arr, bins) {
20822 var first = jStat.min(arr);
20823 var binCnt = bins || 4;
20824 var binWidth = (jStat.max(arr) - first) / binCnt;
20825 var len = arr.length;
20826 var bins = [];
20827 var i;
20828
20829 for (i = 0; i < binCnt; i++)
20830 bins[i] = 0;
20831 for (i = 0; i < len; i++)
20832 bins[Math.min(Math.floor(((arr[i] - first) / binWidth)), binCnt - 1)] += 1;
20833
20834 return bins;
20835};
20836
20837
20838// covariance of two arrays
20839jStat.covariance = function covariance(arr1, arr2) {
20840 var u = jStat.mean(arr1);
20841 var v = jStat.mean(arr2);
20842 var arr1Len = arr1.length;
20843 var sq_dev = new Array(arr1Len);
20844 var i;
20845
20846 for (i = 0; i < arr1Len; i++)
20847 sq_dev[i] = (arr1[i] - u) * (arr2[i] - v);
20848
20849 return jStat.sum(sq_dev) / (arr1Len - 1);
20850};
20851
20852
20853// (pearson's) population correlation coefficient, rho
20854jStat.corrcoeff = function corrcoeff(arr1, arr2) {
20855 return jStat.covariance(arr1, arr2) /
20856 jStat.stdev(arr1, 1) /
20857 jStat.stdev(arr2, 1);
20858};
20859
20860 // (spearman's) rank correlation coefficient, sp
20861jStat.spearmancoeff = function (arr1, arr2) {
20862 arr1 = jStat.rank(arr1);
20863 arr2 = jStat.rank(arr2);
20864 var arr1dev = jStat.deviation(arr1);
20865 var arr2dev = jStat.deviation(arr2);
20866 return jStat.sum(arr1dev.map(function (x, i) {
20867 return x * arr2dev[i];
20868 })) /
20869 Math.sqrt(jStat.sum(arr1dev.map(function (x) {
20870 return Math.pow(x, 2);
20871 })) * jStat.sum(arr2dev.map(function (x) {
20872 return Math.pow(x, 2);
20873 }))
20874 );
20875}
20876
20877
20878// statistical standardized moments (general form of skew/kurt)
20879jStat.stanMoment = function stanMoment(arr, n) {
20880 var mu = jStat.mean(arr);
20881 var sigma = jStat.stdev(arr);
20882 var len = arr.length;
20883 var skewSum = 0;
20884
20885 for (i = 0; i < len; i++)
20886 skewSum += Math.pow((arr[i] - mu) / sigma, n);
20887
20888 return skewSum / arr.length;
20889};
20890
20891// (pearson's) moment coefficient of skewness
20892jStat.skewness = function skewness(arr) {
20893 return jStat.stanMoment(arr, 3);
20894};
20895
20896// (pearson's) (excess) kurtosis
20897jStat.kurtosis = function kurtosis(arr) {
20898 return jStat.stanMoment(arr, 4) - 3;
20899};
20900
20901
20902var jProto = jStat.prototype;
20903
20904
20905// Extend jProto with method for calculating cumulative sums and products.
20906// This differs from the similar extension below as cumsum and cumprod should
20907// not be run again in the case fullbool === true.
20908// If a matrix is passed, automatically assume operation should be done on the
20909// columns.
20910(function(funcs) {
20911 for (var i = 0; i < funcs.length; i++) (function(passfunc) {
20912 // If a matrix is passed, automatically assume operation should be done on
20913 // the columns.
20914 jProto[passfunc] = function(fullbool, func) {
20915 var arr = [];
20916 var i = 0;
20917 var tmpthis = this;
20918 // Assignment reassignation depending on how parameters were passed in.
20919 if (isFunction(fullbool)) {
20920 func = fullbool;
20921 fullbool = false;
20922 }
20923 // Check if a callback was passed with the function.
20924 if (func) {
20925 setTimeout(function() {
20926 func.call(tmpthis, jProto[passfunc].call(tmpthis, fullbool));
20927 });
20928 return this;
20929 }
20930 // Check if matrix and run calculations.
20931 if (this.length > 1) {
20932 tmpthis = fullbool === true ? this : this.transpose();
20933 for (; i < tmpthis.length; i++)
20934 arr[i] = jStat[passfunc](tmpthis[i]);
20935 return arr;
20936 }
20937 // Pass fullbool if only vector, not a matrix. for variance and stdev.
20938 return jStat[passfunc](this[0], fullbool);
20939 };
20940 })(funcs[i]);
20941})(('cumsum cumprod').split(' '));
20942
20943
20944// Extend jProto with methods which don't require arguments and work on columns.
20945(function(funcs) {
20946 for (var i = 0; i < funcs.length; i++) (function(passfunc) {
20947 // If a matrix is passed, automatically assume operation should be done on
20948 // the columns.
20949 jProto[passfunc] = function(fullbool, func) {
20950 var arr = [];
20951 var i = 0;
20952 var tmpthis = this;
20953 // Assignment reassignation depending on how parameters were passed in.
20954 if (isFunction(fullbool)) {
20955 func = fullbool;
20956 fullbool = false;
20957 }
20958 // Check if a callback was passed with the function.
20959 if (func) {
20960 setTimeout(function() {
20961 func.call(tmpthis, jProto[passfunc].call(tmpthis, fullbool));
20962 });
20963 return this;
20964 }
20965 // Check if matrix and run calculations.
20966 if (this.length > 1) {
20967 if (passfunc !== 'sumrow')
20968 tmpthis = fullbool === true ? this : this.transpose();
20969 for (; i < tmpthis.length; i++)
20970 arr[i] = jStat[passfunc](tmpthis[i]);
20971 return fullbool === true
20972 ? jStat[passfunc](jStat.utils.toVector(arr))
20973 : arr;
20974 }
20975 // Pass fullbool if only vector, not a matrix. for variance and stdev.
20976 return jStat[passfunc](this[0], fullbool);
20977 };
20978 })(funcs[i]);
20979})(('sum sumsqrd sumsqerr sumrow product min max unique mean meansqerr ' +
20980 'geomean median diff rank mode range variance deviation stdev meandev ' +
20981 'meddev coeffvar quartiles histogram skewness kurtosis').split(' '));
20982
20983
20984// Extend jProto with functions that take arguments. Operations on matrices are
20985// done on columns.
20986(function(funcs) {
20987 for (var i = 0; i < funcs.length; i++) (function(passfunc) {
20988 jProto[passfunc] = function() {
20989 var arr = [];
20990 var i = 0;
20991 var tmpthis = this;
20992 var args = Array.prototype.slice.call(arguments);
20993
20994 // If the last argument is a function, we assume it's a callback; we
20995 // strip the callback out and call the function again.
20996 if (isFunction(args[args.length - 1])) {
20997 var callbackFunction = args[args.length - 1];
20998 var argsToPass = args.slice(0, args.length - 1);
20999
21000 setTimeout(function() {
21001 callbackFunction.call(tmpthis,
21002 jProto[passfunc].apply(tmpthis, argsToPass));
21003 });
21004 return this;
21005
21006 // Otherwise we curry the function args and call normally.
21007 } else {
21008 var callbackFunction = undefined;
21009 var curriedFunction = function curriedFunction(vector) {
21010 return jStat[passfunc].apply(tmpthis, [vector].concat(args));
21011 }
21012 }
21013
21014 // If this is a matrix, run column-by-column.
21015 if (this.length > 1) {
21016 tmpthis = tmpthis.transpose();
21017 for (; i < tmpthis.length; i++)
21018 arr[i] = curriedFunction(tmpthis[i]);
21019 return arr;
21020 }
21021
21022 // Otherwise run on the vector.
21023 return curriedFunction(this[0]);
21024 };
21025 })(funcs[i]);
21026})('quantiles percentileOfScore'.split(' '));
21027
21028}(this.jStat, Math));
21029// Special functions //
21030(function(jStat, Math) {
21031
21032// Log-gamma function
21033jStat.gammaln = function gammaln(x) {
21034 var j = 0;
21035 var cof = [
21036 76.18009172947146, -86.50532032941677, 24.01409824083091,
21037 -1.231739572450155, 0.1208650973866179e-2, -0.5395239384953e-5
21038 ];
21039 var ser = 1.000000000190015;
21040 var xx, y, tmp;
21041 tmp = (y = xx = x) + 5.5;
21042 tmp -= (xx + 0.5) * Math.log(tmp);
21043 for (; j < 6; j++)
21044 ser += cof[j] / ++y;
21045 return Math.log(2.5066282746310005 * ser / xx) - tmp;
21046};
21047
21048
21049// gamma of x
21050jStat.gammafn = function gammafn(x) {
21051 var p = [-1.716185138865495, 24.76565080557592, -379.80425647094563,
21052 629.3311553128184, 866.9662027904133, -31451.272968848367,
21053 -36144.413418691176, 66456.14382024054
21054 ];
21055 var q = [-30.8402300119739, 315.35062697960416, -1015.1563674902192,
21056 -3107.771671572311, 22538.118420980151, 4755.8462775278811,
21057 -134659.9598649693, -115132.2596755535];
21058 var fact = false;
21059 var n = 0;
21060 var xden = 0;
21061 var xnum = 0;
21062 var y = x;
21063 var i, z, yi, res, sum, ysq;
21064 if (y <= 0) {
21065 res = y % 1 + 3.6e-16;
21066 if (res) {
21067 fact = (!(y & 1) ? 1 : -1) * Math.PI / Math.sin(Math.PI * res);
21068 y = 1 - y;
21069 } else {
21070 return Infinity;
21071 }
21072 }
21073 yi = y;
21074 if (y < 1) {
21075 z = y++;
21076 } else {
21077 z = (y -= n = (y | 0) - 1) - 1;
21078 }
21079 for (i = 0; i < 8; ++i) {
21080 xnum = (xnum + p[i]) * z;
21081 xden = xden * z + q[i];
21082 }
21083 res = xnum / xden + 1;
21084 if (yi < y) {
21085 res /= yi;
21086 } else if (yi > y) {
21087 for (i = 0; i < n; ++i) {
21088 res *= y;
21089 y++;
21090 }
21091 }
21092 if (fact) {
21093 res = fact / res;
21094 }
21095 return res;
21096};
21097
21098
21099// lower incomplete gamma function, which is usually typeset with a
21100// lower-case greek gamma as the function symbol
21101jStat.gammap = function gammap(a, x) {
21102 return jStat.lowRegGamma(a, x) * jStat.gammafn(a);
21103};
21104
21105
21106// The lower regularized incomplete gamma function, usually written P(a,x)
21107jStat.lowRegGamma = function lowRegGamma(a, x) {
21108 var aln = jStat.gammaln(a);
21109 var ap = a;
21110 var sum = 1 / a;
21111 var del = sum;
21112 var b = x + 1 - a;
21113 var c = 1 / 1.0e-30;
21114 var d = 1 / b;
21115 var h = d;
21116 var i = 1;
21117 // calculate maximum number of itterations required for a
21118 var ITMAX = -~(Math.log((a >= 1) ? a : 1 / a) * 8.5 + a * 0.4 + 17);
21119 var an, endval;
21120
21121 if (x < 0 || a <= 0) {
21122 return NaN;
21123 } else if (x < a + 1) {
21124 for (; i <= ITMAX; i++) {
21125 sum += del *= x / ++ap;
21126 }
21127 return (sum * Math.exp(-x + a * Math.log(x) - (aln)));
21128 }
21129
21130 for (; i <= ITMAX; i++) {
21131 an = -i * (i - a);
21132 b += 2;
21133 d = an * d + b;
21134 c = b + an / c;
21135 d = 1 / d;
21136 h *= d * c;
21137 }
21138
21139 return (1 - h * Math.exp(-x + a * Math.log(x) - (aln)));
21140};
21141
21142// natural log factorial of n
21143jStat.factorialln = function factorialln(n) {
21144 return n < 0 ? NaN : jStat.gammaln(n + 1);
21145};
21146
21147// factorial of n
21148jStat.factorial = function factorial(n) {
21149 return n < 0 ? NaN : jStat.gammafn(n + 1);
21150};
21151
21152// combinations of n, m
21153jStat.combination = function combination(n, m) {
21154 // make sure n or m don't exceed the upper limit of usable values
21155 return (n > 170 || m > 170)
21156 ? Math.exp(jStat.combinationln(n, m))
21157 : (jStat.factorial(n) / jStat.factorial(m)) / jStat.factorial(n - m);
21158};
21159
21160
21161jStat.combinationln = function combinationln(n, m){
21162 return jStat.factorialln(n) - jStat.factorialln(m) - jStat.factorialln(n - m);
21163};
21164
21165
21166// permutations of n, m
21167jStat.permutation = function permutation(n, m) {
21168 return jStat.factorial(n) / jStat.factorial(n - m);
21169};
21170
21171
21172// beta function
21173jStat.betafn = function betafn(x, y) {
21174 // ensure arguments are positive
21175 if (x <= 0 || y <= 0)
21176 return undefined;
21177 // make sure x + y doesn't exceed the upper limit of usable values
21178 return (x + y > 170)
21179 ? Math.exp(jStat.betaln(x, y))
21180 : jStat.gammafn(x) * jStat.gammafn(y) / jStat.gammafn(x + y);
21181};
21182
21183
21184// natural logarithm of beta function
21185jStat.betaln = function betaln(x, y) {
21186 return jStat.gammaln(x) + jStat.gammaln(y) - jStat.gammaln(x + y);
21187};
21188
21189
21190// Evaluates the continued fraction for incomplete beta function by modified
21191// Lentz's method.
21192jStat.betacf = function betacf(x, a, b) {
21193 var fpmin = 1e-30;
21194 var m = 1;
21195 var qab = a + b;
21196 var qap = a + 1;
21197 var qam = a - 1;
21198 var c = 1;
21199 var d = 1 - qab * x / qap;
21200 var m2, aa, del, h;
21201
21202 // These q's will be used in factors that occur in the coefficients
21203 if (Math.abs(d) < fpmin)
21204 d = fpmin;
21205 d = 1 / d;
21206 h = d;
21207
21208 for (; m <= 100; m++) {
21209 m2 = 2 * m;
21210 aa = m * (b - m) * x / ((qam + m2) * (a + m2));
21211 // One step (the even one) of the recurrence
21212 d = 1 + aa * d;
21213 if (Math.abs(d) < fpmin)
21214 d = fpmin;
21215 c = 1 + aa / c;
21216 if (Math.abs(c) < fpmin)
21217 c = fpmin;
21218 d = 1 / d;
21219 h *= d * c;
21220 aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2));
21221 // Next step of the recurrence (the odd one)
21222 d = 1 + aa * d;
21223 if (Math.abs(d) < fpmin)
21224 d = fpmin;
21225 c = 1 + aa / c;
21226 if (Math.abs(c) < fpmin)
21227 c = fpmin;
21228 d = 1 / d;
21229 del = d * c;
21230 h *= del;
21231 if (Math.abs(del - 1.0) < 3e-7)
21232 break;
21233 }
21234
21235 return h;
21236};
21237
21238
21239// Returns the inverse of the lower regularized inomplete gamma function
21240jStat.gammapinv = function gammapinv(p, a) {
21241 var j = 0;
21242 var a1 = a - 1;
21243 var EPS = 1e-8;
21244 var gln = jStat.gammaln(a);
21245 var x, err, t, u, pp, lna1, afac;
21246
21247 if (p >= 1)
21248 return Math.max(100, a + 100 * Math.sqrt(a));
21249 if (p <= 0)
21250 return 0;
21251 if (a > 1) {
21252 lna1 = Math.log(a1);
21253 afac = Math.exp(a1 * (lna1 - 1) - gln);
21254 pp = (p < 0.5) ? p : 1 - p;
21255 t = Math.sqrt(-2 * Math.log(pp));
21256 x = (2.30753 + t * 0.27061) / (1 + t * (0.99229 + t * 0.04481)) - t;
21257 if (p < 0.5)
21258 x = -x;
21259 x = Math.max(1e-3,
21260 a * Math.pow(1 - 1 / (9 * a) - x / (3 * Math.sqrt(a)), 3));
21261 } else {
21262 t = 1 - a * (0.253 + a * 0.12);
21263 if (p < t)
21264 x = Math.pow(p / t, 1 / a);
21265 else
21266 x = 1 - Math.log(1 - (p - t) / (1 - t));
21267 }
21268
21269 for(; j < 12; j++) {
21270 if (x <= 0)
21271 return 0;
21272 err = jStat.lowRegGamma(a, x) - p;
21273 if (a > 1)
21274 t = afac * Math.exp(-(x - a1) + a1 * (Math.log(x) - lna1));
21275 else
21276 t = Math.exp(-x + a1 * Math.log(x) - gln);
21277 u = err / t;
21278 x -= (t = u / (1 - 0.5 * Math.min(1, u * ((a - 1) / x - 1))));
21279 if (x <= 0)
21280 x = 0.5 * (x + t);
21281 if (Math.abs(t) < EPS * x)
21282 break;
21283 }
21284
21285 return x;
21286};
21287
21288
21289// Returns the error function erf(x)
21290jStat.erf = function erf(x) {
21291 var cof = [-1.3026537197817094, 6.4196979235649026e-1, 1.9476473204185836e-2,
21292 -9.561514786808631e-3, -9.46595344482036e-4, 3.66839497852761e-4,
21293 4.2523324806907e-5, -2.0278578112534e-5, -1.624290004647e-6,
21294 1.303655835580e-6, 1.5626441722e-8, -8.5238095915e-8,
21295 6.529054439e-9, 5.059343495e-9, -9.91364156e-10,
21296 -2.27365122e-10, 9.6467911e-11, 2.394038e-12,
21297 -6.886027e-12, 8.94487e-13, 3.13092e-13,
21298 -1.12708e-13, 3.81e-16, 7.106e-15,
21299 -1.523e-15, -9.4e-17, 1.21e-16,
21300 -2.8e-17];
21301 var j = cof.length - 1;
21302 var isneg = false;
21303 var d = 0;
21304 var dd = 0;
21305 var t, ty, tmp, res;
21306
21307 if (x < 0) {
21308 x = -x;
21309 isneg = true;
21310 }
21311
21312 t = 2 / (2 + x);
21313 ty = 4 * t - 2;
21314
21315 for(; j > 0; j--) {
21316 tmp = d;
21317 d = ty * d - dd + cof[j];
21318 dd = tmp;
21319 }
21320
21321 res = t * Math.exp(-x * x + 0.5 * (cof[0] + ty * d) - dd);
21322 return isneg ? res - 1 : 1 - res;
21323};
21324
21325
21326// Returns the complmentary error function erfc(x)
21327jStat.erfc = function erfc(x) {
21328 return 1 - jStat.erf(x);
21329};
21330
21331
21332// Returns the inverse of the complementary error function
21333jStat.erfcinv = function erfcinv(p) {
21334 var j = 0;
21335 var x, err, t, pp;
21336 if (p >= 2)
21337 return -100;
21338 if (p <= 0)
21339 return 100;
21340 pp = (p < 1) ? p : 2 - p;
21341 t = Math.sqrt(-2 * Math.log(pp / 2));
21342 x = -0.70711 * ((2.30753 + t * 0.27061) /
21343 (1 + t * (0.99229 + t * 0.04481)) - t);
21344 for (; j < 2; j++) {
21345 err = jStat.erfc(x) - pp;
21346 x += err / (1.12837916709551257 * Math.exp(-x * x) - x * err);
21347 }
21348 return (p < 1) ? x : -x;
21349};
21350
21351
21352// Returns the inverse of the incomplete beta function
21353jStat.ibetainv = function ibetainv(p, a, b) {
21354 var EPS = 1e-8;
21355 var a1 = a - 1;
21356 var b1 = b - 1;
21357 var j = 0;
21358 var lna, lnb, pp, t, u, err, x, al, h, w, afac;
21359 if (p <= 0)
21360 return 0;
21361 if (p >= 1)
21362 return 1;
21363 if (a >= 1 && b >= 1) {
21364 pp = (p < 0.5) ? p : 1 - p;
21365 t = Math.sqrt(-2 * Math.log(pp));
21366 x = (2.30753 + t * 0.27061) / (1 + t* (0.99229 + t * 0.04481)) - t;
21367 if (p < 0.5)
21368 x = -x;
21369 al = (x * x - 3) / 6;
21370 h = 2 / (1 / (2 * a - 1) + 1 / (2 * b - 1));
21371 w = (x * Math.sqrt(al + h) / h) - (1 / (2 * b - 1) - 1 / (2 * a - 1)) *
21372 (al + 5 / 6 - 2 / (3 * h));
21373 x = a / (a + b * Math.exp(2 * w));
21374 } else {
21375 lna = Math.log(a / (a + b));
21376 lnb = Math.log(b / (a + b));
21377 t = Math.exp(a * lna) / a;
21378 u = Math.exp(b * lnb) / b;
21379 w = t + u;
21380 if (p < t / w)
21381 x = Math.pow(a * w * p, 1 / a);
21382 else
21383 x = 1 - Math.pow(b * w * (1 - p), 1 / b);
21384 }
21385 afac = -jStat.gammaln(a) - jStat.gammaln(b) + jStat.gammaln(a + b);
21386 for(; j < 10; j++) {
21387 if (x === 0 || x === 1)
21388 return x;
21389 err = jStat.ibeta(x, a, b) - p;
21390 t = Math.exp(a1 * Math.log(x) + b1 * Math.log(1 - x) + afac);
21391 u = err / t;
21392 x -= (t = u / (1 - 0.5 * Math.min(1, u * (a1 / x - b1 / (1 - x)))));
21393 if (x <= 0)
21394 x = 0.5 * (x + t);
21395 if (x >= 1)
21396 x = 0.5 * (x + t + 1);
21397 if (Math.abs(t) < EPS * x && j > 0)
21398 break;
21399 }
21400 return x;
21401};
21402
21403
21404// Returns the incomplete beta function I_x(a,b)
21405jStat.ibeta = function ibeta(x, a, b) {
21406 // Factors in front of the continued fraction.
21407 var bt = (x === 0 || x === 1) ? 0 :
21408 Math.exp(jStat.gammaln(a + b) - jStat.gammaln(a) -
21409 jStat.gammaln(b) + a * Math.log(x) + b *
21410 Math.log(1 - x));
21411 if (x < 0 || x > 1)
21412 return false;
21413 if (x < (a + 1) / (a + b + 2))
21414 // Use continued fraction directly.
21415 return bt * jStat.betacf(x, a, b) / a;
21416 // else use continued fraction after making the symmetry transformation.
21417 return 1 - bt * jStat.betacf(1 - x, b, a) / b;
21418};
21419
21420
21421// Returns a normal deviate (mu=0, sigma=1).
21422// If n and m are specified it returns a object of normal deviates.
21423jStat.randn = function randn(n, m) {
21424 var u, v, x, y, q, mat;
21425 if (!m)
21426 m = n;
21427 if (n)
21428 return jStat.create(n, m, function() { return jStat.randn(); });
21429 do {
21430 u = Math.random();
21431 v = 1.7156 * (Math.random() - 0.5);
21432 x = u - 0.449871;
21433 y = Math.abs(v) + 0.386595;
21434 q = x * x + y * (0.19600 * y - 0.25472 * x);
21435 } while (q > 0.27597 && (q > 0.27846 || v * v > -4 * Math.log(u) * u * u));
21436 return v / u;
21437};
21438
21439
21440// Returns a gamma deviate by the method of Marsaglia and Tsang.
21441jStat.randg = function randg(shape, n, m) {
21442 var oalph = shape;
21443 var a1, a2, u, v, x, mat;
21444 if (!m)
21445 m = n;
21446 if (!shape)
21447 shape = 1;
21448 if (n) {
21449 mat = jStat.zeros(n,m);
21450 mat.alter(function() { return jStat.randg(shape); });
21451 return mat;
21452 }
21453 if (shape < 1)
21454 shape += 1;
21455 a1 = shape - 1 / 3;
21456 a2 = 1 / Math.sqrt(9 * a1);
21457 do {
21458 do {
21459 x = jStat.randn();
21460 v = 1 + a2 * x;
21461 } while(v <= 0);
21462 v = v * v * v;
21463 u = Math.random();
21464 } while(u > 1 - 0.331 * Math.pow(x, 4) &&
21465 Math.log(u) > 0.5 * x*x + a1 * (1 - v + Math.log(v)));
21466 // alpha > 1
21467 if (shape == oalph)
21468 return a1 * v;
21469 // alpha < 1
21470 do {
21471 u = Math.random();
21472 } while(u === 0);
21473 return Math.pow(u, 1 / oalph) * a1 * v;
21474};
21475
21476
21477// making use of static methods on the instance
21478(function(funcs) {
21479 for (var i = 0; i < funcs.length; i++) (function(passfunc) {
21480 jStat.fn[passfunc] = function() {
21481 return jStat(
21482 jStat.map(this, function(value) { return jStat[passfunc](value); }));
21483 }
21484 })(funcs[i]);
21485})('gammaln gammafn factorial factorialln'.split(' '));
21486
21487
21488(function(funcs) {
21489 for (var i = 0; i < funcs.length; i++) (function(passfunc) {
21490 jStat.fn[passfunc] = function() {
21491 return jStat(jStat[passfunc].apply(null, arguments));
21492 };
21493 })(funcs[i]);
21494})('randn'.split(' '));
21495
21496}(this.jStat, Math));
21497(function(jStat, Math) {
21498
21499// generate all distribution instance methods
21500(function(list) {
21501 for (var i = 0; i < list.length; i++) (function(func) {
21502 // distribution instance method
21503 jStat[func] = function(a, b, c) {
21504 if (!(this instanceof arguments.callee))
21505 return new arguments.callee(a, b, c);
21506 this._a = a;
21507 this._b = b;
21508 this._c = c;
21509 return this;
21510 };
21511 // distribution method to be used on a jStat instance
21512 jStat.fn[func] = function(a, b, c) {
21513 var newthis = jStat[func](a, b, c);
21514 newthis.data = this;
21515 return newthis;
21516 };
21517 // sample instance method
21518 jStat[func].prototype.sample = function(arr) {
21519 var a = this._a;
21520 var b = this._b;
21521 var c = this._c;
21522 if (arr)
21523 return jStat.alter(arr, function() {
21524 return jStat[func].sample(a, b, c);
21525 });
21526 else
21527 return jStat[func].sample(a, b, c);
21528 };
21529 // generate the pdf, cdf and inv instance methods
21530 (function(vals) {
21531 for (var i = 0; i < vals.length; i++) (function(fnfunc) {
21532 jStat[func].prototype[fnfunc] = function(x) {
21533 var a = this._a;
21534 var b = this._b;
21535 var c = this._c;
21536 if (!x && x !== 0)
21537 x = this.data;
21538 if (typeof x !== 'number') {
21539 return jStat.fn.map.call(x, function(x) {
21540 return jStat[func][fnfunc](x, a, b, c);
21541 });
21542 }
21543 return jStat[func][fnfunc](x, a, b, c);
21544 };
21545 })(vals[i]);
21546 })('pdf cdf inv'.split(' '));
21547 // generate the mean, median, mode and variance instance methods
21548 (function(vals) {
21549 for (var i = 0; i < vals.length; i++) (function(fnfunc) {
21550 jStat[func].prototype[fnfunc] = function() {
21551 return jStat[func][fnfunc](this._a, this._b, this._c);
21552 };
21553 })(vals[i]);
21554 })('mean median mode variance'.split(' '));
21555 })(list[i]);
21556})((
21557 'beta centralF cauchy chisquare exponential gamma invgamma kumaraswamy ' +
21558 'laplace lognormal noncentralt normal pareto studentt weibull uniform ' +
21559 'binomial negbin hypgeom poisson triangular'
21560).split(' '));
21561
21562
21563
21564// extend beta function with static methods
21565jStat.extend(jStat.beta, {
21566 pdf: function pdf(x, alpha, beta) {
21567 // PDF is zero outside the support
21568 if (x > 1 || x < 0)
21569 return 0;
21570 // PDF is one for the uniform case
21571 if (alpha == 1 && beta == 1)
21572 return 1;
21573
21574 if (alpha < 512 && beta < 512) {
21575 return (Math.pow(x, alpha - 1) * Math.pow(1 - x, beta - 1)) /
21576 jStat.betafn(alpha, beta);
21577 } else {
21578 return Math.exp((alpha - 1) * Math.log(x) +
21579 (beta - 1) * Math.log(1 - x) -
21580 jStat.betaln(alpha, beta));
21581 }
21582 },
21583
21584 cdf: function cdf(x, alpha, beta) {
21585 return (x > 1 || x < 0) ? (x > 1) * 1 : jStat.ibeta(x, alpha, beta);
21586 },
21587
21588 inv: function inv(x, alpha, beta) {
21589 return jStat.ibetainv(x, alpha, beta);
21590 },
21591
21592 mean: function mean(alpha, beta) {
21593 return alpha / (alpha + beta);
21594 },
21595
21596 median: function median(alpha, beta) {
21597 return jStat.ibetainv(0.5, alpha, beta);
21598 },
21599
21600 mode: function mode(alpha, beta) {
21601 return (alpha - 1 ) / ( alpha + beta - 2);
21602 },
21603
21604 // return a random sample
21605 sample: function sample(alpha, beta) {
21606 var u = jStat.randg(alpha);
21607 return u / (u + jStat.randg(beta));
21608 },
21609
21610 variance: function variance(alpha, beta) {
21611 return (alpha * beta) / (Math.pow(alpha + beta, 2) * (alpha + beta + 1));
21612 }
21613});
21614
21615// extend F function with static methods
21616jStat.extend(jStat.centralF, {
21617 // This implementation of the pdf function avoids float overflow
21618 // See the way that R calculates this value:
21619 // https://svn.r-project.org/R/trunk/src/nmath/df.c
21620 pdf: function pdf(x, df1, df2) {
21621 var p, q, f;
21622
21623 if (x < 0)
21624 return 0;
21625
21626 if (df1 <= 2) {
21627 if (x === 0 && df1 < 2) {
21628 return Infinity;
21629 }
21630 if (x === 0 && df1 === 2) {
21631 return 1;
21632 }
21633 return Math.sqrt((Math.pow(df1 * x, df1) * Math.pow(df2, df2)) /
21634 (Math.pow(df1 * x + df2, df1 + df2))) /
21635 (x * jStat.betafn(df1/2, df2/2));
21636 }
21637
21638 p = (df1 * x) / (df2 + x * df1);
21639 q = df2 / (df2 + x * df1);
21640 f = df1 * q / 2.0;
21641 return f * jStat.binomial.pdf((df1 - 2) / 2, (df1 + df2 - 2) / 2, p);
21642 },
21643
21644 cdf: function cdf(x, df1, df2) {
21645 if (x < 0)
21646 return 0;
21647 return jStat.ibeta((df1 * x) / (df1 * x + df2), df1 / 2, df2 / 2);
21648 },
21649
21650 inv: function inv(x, df1, df2) {
21651 return df2 / (df1 * (1 / jStat.ibetainv(x, df1 / 2, df2 / 2) - 1));
21652 },
21653
21654 mean: function mean(df1, df2) {
21655 return (df2 > 2) ? df2 / (df2 - 2) : undefined;
21656 },
21657
21658 mode: function mode(df1, df2) {
21659 return (df1 > 2) ? (df2 * (df1 - 2)) / (df1 * (df2 + 2)) : undefined;
21660 },
21661
21662 // return a random sample
21663 sample: function sample(df1, df2) {
21664 var x1 = jStat.randg(df1 / 2) * 2;
21665 var x2 = jStat.randg(df2 / 2) * 2;
21666 return (x1 / df1) / (x2 / df2);
21667 },
21668
21669 variance: function variance(df1, df2) {
21670 if (df2 <= 4)
21671 return undefined;
21672 return 2 * df2 * df2 * (df1 + df2 - 2) /
21673 (df1 * (df2 - 2) * (df2 - 2) * (df2 - 4));
21674 }
21675});
21676
21677
21678// extend cauchy function with static methods
21679jStat.extend(jStat.cauchy, {
21680 pdf: function pdf(x, local, scale) {
21681 if (scale < 0) { return 0; }
21682
21683 return (scale / (Math.pow(x - local, 2) + Math.pow(scale, 2))) / Math.PI;
21684 },
21685
21686 cdf: function cdf(x, local, scale) {
21687 return Math.atan((x - local) / scale) / Math.PI + 0.5;
21688 },
21689
21690 inv: function(p, local, scale) {
21691 return local + scale * Math.tan(Math.PI * (p - 0.5));
21692 },
21693
21694 median: function median(local, scale) {
21695 return local;
21696 },
21697
21698 mode: function mode(local, scale) {
21699 return local;
21700 },
21701
21702 sample: function sample(local, scale) {
21703 return jStat.randn() *
21704 Math.sqrt(1 / (2 * jStat.randg(0.5))) * scale + local;
21705 }
21706});
21707
21708
21709
21710// extend chisquare function with static methods
21711jStat.extend(jStat.chisquare, {
21712 pdf: function pdf(x, dof) {
21713 if (x < 0)
21714 return 0;
21715 return (x === 0 && dof === 2) ? 0.5 :
21716 Math.exp((dof / 2 - 1) * Math.log(x) - x / 2 - (dof / 2) *
21717 Math.log(2) - jStat.gammaln(dof / 2));
21718 },
21719
21720 cdf: function cdf(x, dof) {
21721 if (x < 0)
21722 return 0;
21723 return jStat.lowRegGamma(dof / 2, x / 2);
21724 },
21725
21726 inv: function(p, dof) {
21727 return 2 * jStat.gammapinv(p, 0.5 * dof);
21728 },
21729
21730 mean : function(dof) {
21731 return dof;
21732 },
21733
21734 // TODO: this is an approximation (is there a better way?)
21735 median: function median(dof) {
21736 return dof * Math.pow(1 - (2 / (9 * dof)), 3);
21737 },
21738
21739 mode: function mode(dof) {
21740 return (dof - 2 > 0) ? dof - 2 : 0;
21741 },
21742
21743 sample: function sample(dof) {
21744 return jStat.randg(dof / 2) * 2;
21745 },
21746
21747 variance: function variance(dof) {
21748 return 2 * dof;
21749 }
21750});
21751
21752
21753
21754// extend exponential function with static methods
21755jStat.extend(jStat.exponential, {
21756 pdf: function pdf(x, rate) {
21757 return x < 0 ? 0 : rate * Math.exp(-rate * x);
21758 },
21759
21760 cdf: function cdf(x, rate) {
21761 return x < 0 ? 0 : 1 - Math.exp(-rate * x);
21762 },
21763
21764 inv: function(p, rate) {
21765 return -Math.log(1 - p) / rate;
21766 },
21767
21768 mean : function(rate) {
21769 return 1 / rate;
21770 },
21771
21772 median: function (rate) {
21773 return (1 / rate) * Math.log(2);
21774 },
21775
21776 mode: function mode(rate) {
21777 return 0;
21778 },
21779
21780 sample: function sample(rate) {
21781 return -1 / rate * Math.log(Math.random());
21782 },
21783
21784 variance : function(rate) {
21785 return Math.pow(rate, -2);
21786 }
21787});
21788
21789
21790
21791// extend gamma function with static methods
21792jStat.extend(jStat.gamma, {
21793 pdf: function pdf(x, shape, scale) {
21794 if (x < 0)
21795 return 0;
21796 return (x === 0 && shape === 1) ? 1 / scale :
21797 Math.exp((shape - 1) * Math.log(x) - x / scale -
21798 jStat.gammaln(shape) - shape * Math.log(scale));
21799 },
21800
21801 cdf: function cdf(x, shape, scale) {
21802 if (x < 0)
21803 return 0;
21804 return jStat.lowRegGamma(shape, x / scale);
21805 },
21806
21807 inv: function(p, shape, scale) {
21808 return jStat.gammapinv(p, shape) * scale;
21809 },
21810
21811 mean : function(shape, scale) {
21812 return shape * scale;
21813 },
21814
21815 mode: function mode(shape, scale) {
21816 if(shape > 1) return (shape - 1) * scale;
21817 return undefined;
21818 },
21819
21820 sample: function sample(shape, scale) {
21821 return jStat.randg(shape) * scale;
21822 },
21823
21824 variance: function variance(shape, scale) {
21825 return shape * scale * scale;
21826 }
21827});
21828
21829// extend inverse gamma function with static methods
21830jStat.extend(jStat.invgamma, {
21831 pdf: function pdf(x, shape, scale) {
21832 if (x <= 0)
21833 return 0;
21834 return Math.exp(-(shape + 1) * Math.log(x) - scale / x -
21835 jStat.gammaln(shape) + shape * Math.log(scale));
21836 },
21837
21838 cdf: function cdf(x, shape, scale) {
21839 if (x <= 0)
21840 return 0;
21841 return 1 - jStat.lowRegGamma(shape, scale / x);
21842 },
21843
21844 inv: function(p, shape, scale) {
21845 return scale / jStat.gammapinv(1 - p, shape);
21846 },
21847
21848 mean : function(shape, scale) {
21849 return (shape > 1) ? scale / (shape - 1) : undefined;
21850 },
21851
21852 mode: function mode(shape, scale) {
21853 return scale / (shape + 1);
21854 },
21855
21856 sample: function sample(shape, scale) {
21857 return scale / jStat.randg(shape);
21858 },
21859
21860 variance: function variance(shape, scale) {
21861 if (shape <= 2)
21862 return undefined;
21863 return scale * scale / ((shape - 1) * (shape - 1) * (shape - 2));
21864 }
21865});
21866
21867
21868// extend kumaraswamy function with static methods
21869jStat.extend(jStat.kumaraswamy, {
21870 pdf: function pdf(x, alpha, beta) {
21871 if (x === 0 && alpha === 1)
21872 return beta;
21873 else if (x === 1 && beta === 1)
21874 return alpha;
21875 return Math.exp(Math.log(alpha) + Math.log(beta) + (alpha - 1) *
21876 Math.log(x) + (beta - 1) *
21877 Math.log(1 - Math.pow(x, alpha)));
21878 },
21879
21880 cdf: function cdf(x, alpha, beta) {
21881 if (x < 0)
21882 return 0;
21883 else if (x > 1)
21884 return 1;
21885 return (1 - Math.pow(1 - Math.pow(x, alpha), beta));
21886 },
21887
21888 inv: function inv(p, alpha, beta) {
21889 return Math.pow(1 - Math.pow(1 - p, 1 / beta), 1 / alpha);
21890 },
21891
21892 mean : function(alpha, beta) {
21893 return (beta * jStat.gammafn(1 + 1 / alpha) *
21894 jStat.gammafn(beta)) / (jStat.gammafn(1 + 1 / alpha + beta));
21895 },
21896
21897 median: function median(alpha, beta) {
21898 return Math.pow(1 - Math.pow(2, -1 / beta), 1 / alpha);
21899 },
21900
21901 mode: function mode(alpha, beta) {
21902 if (!(alpha >= 1 && beta >= 1 && (alpha !== 1 && beta !== 1)))
21903 return undefined;
21904 return Math.pow((alpha - 1) / (alpha * beta - 1), 1 / alpha);
21905 },
21906
21907 variance: function variance(alpha, beta) {
21908 throw new Error('variance not yet implemented');
21909 // TODO: complete this
21910 }
21911});
21912
21913
21914
21915// extend lognormal function with static methods
21916jStat.extend(jStat.lognormal, {
21917 pdf: function pdf(x, mu, sigma) {
21918 if (x <= 0)
21919 return 0;
21920 return Math.exp(-Math.log(x) - 0.5 * Math.log(2 * Math.PI) -
21921 Math.log(sigma) - Math.pow(Math.log(x) - mu, 2) /
21922 (2 * sigma * sigma));
21923 },
21924
21925 cdf: function cdf(x, mu, sigma) {
21926 if (x < 0)
21927 return 0;
21928 return 0.5 +
21929 (0.5 * jStat.erf((Math.log(x) - mu) / Math.sqrt(2 * sigma * sigma)));
21930 },
21931
21932 inv: function(p, mu, sigma) {
21933 return Math.exp(-1.41421356237309505 * sigma * jStat.erfcinv(2 * p) + mu);
21934 },
21935
21936 mean: function mean(mu, sigma) {
21937 return Math.exp(mu + sigma * sigma / 2);
21938 },
21939
21940 median: function median(mu, sigma) {
21941 return Math.exp(mu);
21942 },
21943
21944 mode: function mode(mu, sigma) {
21945 return Math.exp(mu - sigma * sigma);
21946 },
21947
21948 sample: function sample(mu, sigma) {
21949 return Math.exp(jStat.randn() * sigma + mu);
21950 },
21951
21952 variance: function variance(mu, sigma) {
21953 return (Math.exp(sigma * sigma) - 1) * Math.exp(2 * mu + sigma * sigma);
21954 }
21955});
21956
21957
21958
21959// extend noncentralt function with static methods
21960jStat.extend(jStat.noncentralt, {
21961 pdf: function pdf(x, dof, ncp) {
21962 var tol = 1e-14;
21963 if (Math.abs(ncp) < tol) // ncp approx 0; use student-t
21964 return jStat.studentt.pdf(x, dof)
21965
21966 if (Math.abs(x) < tol) { // different formula for x == 0
21967 return Math.exp(jStat.gammaln((dof + 1) / 2) - ncp * ncp / 2 -
21968 0.5 * Math.log(Math.PI * dof) - jStat.gammaln(dof / 2));
21969 }
21970
21971 // formula for x != 0
21972 return dof / x *
21973 (jStat.noncentralt.cdf(x * Math.sqrt(1 + 2 / dof), dof+2, ncp) -
21974 jStat.noncentralt.cdf(x, dof, ncp));
21975 },
21976
21977 cdf: function cdf(x, dof, ncp) {
21978 var tol = 1e-14;
21979 var min_iterations = 200;
21980
21981 if (Math.abs(ncp) < tol) // ncp approx 0; use student-t
21982 return jStat.studentt.cdf(x, dof);
21983
21984 // turn negative x into positive and flip result afterwards
21985 var flip = false;
21986 if (x < 0) {
21987 flip = true;
21988 ncp = -ncp;
21989 }
21990
21991 var prob = jStat.normal.cdf(-ncp, 0, 1);
21992 var value = tol + 1;
21993 // use value at last two steps to determine convergence
21994 var lastvalue = value;
21995 var y = x * x / (x * x + dof);
21996 var j = 0;
21997 var p = Math.exp(-ncp * ncp / 2);
21998 var q = Math.exp(-ncp * ncp / 2 - 0.5 * Math.log(2) -
21999 jStat.gammaln(3 / 2)) * ncp;
22000 while (j < min_iterations || lastvalue > tol || value > tol) {
22001 lastvalue = value;
22002 if (j > 0) {
22003 p *= (ncp * ncp) / (2 * j);
22004 q *= (ncp * ncp) / (2 * (j + 1 / 2));
22005 }
22006 value = p * jStat.beta.cdf(y, j + 0.5, dof / 2) +
22007 q * jStat.beta.cdf(y, j+1, dof/2);
22008 prob += 0.5 * value;
22009 j++;
22010 }
22011
22012 return flip ? (1 - prob) : prob;
22013 }
22014});
22015
22016
22017// extend normal function with static methods
22018jStat.extend(jStat.normal, {
22019 pdf: function pdf(x, mean, std) {
22020 return Math.exp(-0.5 * Math.log(2 * Math.PI) -
22021 Math.log(std) - Math.pow(x - mean, 2) / (2 * std * std));
22022 },
22023
22024 cdf: function cdf(x, mean, std) {
22025 return 0.5 * (1 + jStat.erf((x - mean) / Math.sqrt(2 * std * std)));
22026 },
22027
22028 inv: function(p, mean, std) {
22029 return -1.41421356237309505 * std * jStat.erfcinv(2 * p) + mean;
22030 },
22031
22032 mean : function(mean, std) {
22033 return mean;
22034 },
22035
22036 median: function median(mean, std) {
22037 return mean;
22038 },
22039
22040 mode: function (mean, std) {
22041 return mean;
22042 },
22043
22044 sample: function sample(mean, std) {
22045 return jStat.randn() * std + mean;
22046 },
22047
22048 variance : function(mean, std) {
22049 return std * std;
22050 }
22051});
22052
22053
22054
22055// extend pareto function with static methods
22056jStat.extend(jStat.pareto, {
22057 pdf: function pdf(x, scale, shape) {
22058 if (x < scale)
22059 return 0;
22060 return (shape * Math.pow(scale, shape)) / Math.pow(x, shape + 1);
22061 },
22062
22063 cdf: function cdf(x, scale, shape) {
22064 if (x < scale)
22065 return 0;
22066 return 1 - Math.pow(scale / x, shape);
22067 },
22068
22069 inv: function inv(p, scale, shape) {
22070 return scale / Math.pow(1 - p, 1 / shape);
22071 },
22072
22073 mean: function mean(scale, shape) {
22074 if (shape <= 1)
22075 return undefined;
22076 return (shape * Math.pow(scale, shape)) / (shape - 1);
22077 },
22078
22079 median: function median(scale, shape) {
22080 return scale * (shape * Math.SQRT2);
22081 },
22082
22083 mode: function mode(scale, shape) {
22084 return scale;
22085 },
22086
22087 variance : function(scale, shape) {
22088 if (shape <= 2)
22089 return undefined;
22090 return (scale*scale * shape) / (Math.pow(shape - 1, 2) * (shape - 2));
22091 }
22092});
22093
22094
22095
22096// extend studentt function with static methods
22097jStat.extend(jStat.studentt, {
22098 pdf: function pdf(x, dof) {
22099 dof = dof > 1e100 ? 1e100 : dof;
22100 return (1/(Math.sqrt(dof) * jStat.betafn(0.5, dof/2))) *
22101 Math.pow(1 + ((x * x) / dof), -((dof + 1) / 2));
22102 },
22103
22104 cdf: function cdf(x, dof) {
22105 var dof2 = dof / 2;
22106 return jStat.ibeta((x + Math.sqrt(x * x + dof)) /
22107 (2 * Math.sqrt(x * x + dof)), dof2, dof2);
22108 },
22109
22110 inv: function(p, dof) {
22111 var x = jStat.ibetainv(2 * Math.min(p, 1 - p), 0.5 * dof, 0.5);
22112 x = Math.sqrt(dof * (1 - x) / x);
22113 return (p > 0.5) ? x : -x;
22114 },
22115
22116 mean: function mean(dof) {
22117 return (dof > 1) ? 0 : undefined;
22118 },
22119
22120 median: function median(dof) {
22121 return 0;
22122 },
22123
22124 mode: function mode(dof) {
22125 return 0;
22126 },
22127
22128 sample: function sample(dof) {
22129 return jStat.randn() * Math.sqrt(dof / (2 * jStat.randg(dof / 2)));
22130 },
22131
22132 variance: function variance(dof) {
22133 return (dof > 2) ? dof / (dof - 2) : (dof > 1) ? Infinity : undefined;
22134 }
22135});
22136
22137
22138
22139// extend weibull function with static methods
22140jStat.extend(jStat.weibull, {
22141 pdf: function pdf(x, scale, shape) {
22142 if (x < 0 || scale < 0 || shape < 0)
22143 return 0;
22144 return (shape / scale) * Math.pow((x / scale), (shape - 1)) *
22145 Math.exp(-(Math.pow((x / scale), shape)));
22146 },
22147
22148 cdf: function cdf(x, scale, shape) {
22149 return x < 0 ? 0 : 1 - Math.exp(-Math.pow((x / scale), shape));
22150 },
22151
22152 inv: function(p, scale, shape) {
22153 return scale * Math.pow(-Math.log(1 - p), 1 / shape);
22154 },
22155
22156 mean : function(scale, shape) {
22157 return scale * jStat.gammafn(1 + 1 / shape);
22158 },
22159
22160 median: function median(scale, shape) {
22161 return scale * Math.pow(Math.log(2), 1 / shape);
22162 },
22163
22164 mode: function mode(scale, shape) {
22165 if (shape <= 1)
22166 return 0;
22167 return scale * Math.pow((shape - 1) / shape, 1 / shape);
22168 },
22169
22170 sample: function sample(scale, shape) {
22171 return scale * Math.pow(-Math.log(Math.random()), 1 / shape);
22172 },
22173
22174 variance: function variance(scale, shape) {
22175 return scale * scale * jStat.gammafn(1 + 2 / shape) -
22176 Math.pow(jStat.weibull.mean(scale, shape), 2);
22177 }
22178});
22179
22180
22181
22182// extend uniform function with static methods
22183jStat.extend(jStat.uniform, {
22184 pdf: function pdf(x, a, b) {
22185 return (x < a || x > b) ? 0 : 1 / (b - a);
22186 },
22187
22188 cdf: function cdf(x, a, b) {
22189 if (x < a)
22190 return 0;
22191 else if (x < b)
22192 return (x - a) / (b - a);
22193 return 1;
22194 },
22195
22196 inv: function(p, a, b) {
22197 return a + (p * (b - a));
22198 },
22199
22200 mean: function mean(a, b) {
22201 return 0.5 * (a + b);
22202 },
22203
22204 median: function median(a, b) {
22205 return jStat.mean(a, b);
22206 },
22207
22208 mode: function mode(a, b) {
22209 throw new Error('mode is not yet implemented');
22210 },
22211
22212 sample: function sample(a, b) {
22213 return (a / 2 + b / 2) + (b / 2 - a / 2) * (2 * Math.random() - 1);
22214 },
22215
22216 variance: function variance(a, b) {
22217 return Math.pow(b - a, 2) / 12;
22218 }
22219});
22220
22221
22222
22223// extend uniform function with static methods
22224jStat.extend(jStat.binomial, {
22225 pdf: function pdf(k, n, p) {
22226 return (p === 0 || p === 1) ?
22227 ((n * p) === k ? 1 : 0) :
22228 jStat.combination(n, k) * Math.pow(p, k) * Math.pow(1 - p, n - k);
22229 },
22230
22231 cdf: function cdf(x, n, p) {
22232 var binomarr = [],
22233 k = 0;
22234 if (x < 0) {
22235 return 0;
22236 }
22237 if (x < n) {
22238 for (; k <= x; k++) {
22239 binomarr[ k ] = jStat.binomial.pdf(k, n, p);
22240 }
22241 return jStat.sum(binomarr);
22242 }
22243 return 1;
22244 }
22245});
22246
22247
22248
22249// extend uniform function with static methods
22250jStat.extend(jStat.negbin, {
22251 pdf: function pdf(k, r, p) {
22252 if (k !== k >>> 0)
22253 return false;
22254 if (k < 0)
22255 return 0;
22256 return jStat.combination(k + r - 1, r - 1) *
22257 Math.pow(1 - p, k) * Math.pow(p, r);
22258 },
22259
22260 cdf: function cdf(x, r, p) {
22261 var sum = 0,
22262 k = 0;
22263 if (x < 0) return 0;
22264 for (; k <= x; k++) {
22265 sum += jStat.negbin.pdf(k, r, p);
22266 }
22267 return sum;
22268 }
22269});
22270
22271
22272
22273// extend uniform function with static methods
22274jStat.extend(jStat.hypgeom, {
22275 pdf: function pdf(k, N, m, n) {
22276 // Hypergeometric PDF.
22277
22278 // A simplification of the CDF algorithm below.
22279
22280 // k = number of successes drawn
22281 // N = population size
22282 // m = number of successes in population
22283 // n = number of items drawn from population
22284
22285 if(k !== k | 0) {
22286 return false;
22287 } else if(k < 0 || k < m - (N - n)) {
22288 // It's impossible to have this few successes drawn.
22289 return 0;
22290 } else if(k > n || k > m) {
22291 // It's impossible to have this many successes drawn.
22292 return 0;
22293 } else if (m * 2 > N) {
22294 // More than half the population is successes.
22295
22296 if(n * 2 > N) {
22297 // More than half the population is sampled.
22298
22299 return jStat.hypgeom.pdf(N - m - n + k, N, N - m, N - n)
22300 } else {
22301 // Half or less of the population is sampled.
22302
22303 return jStat.hypgeom.pdf(n - k, N, N - m, n);
22304 }
22305
22306 } else if(n * 2 > N) {
22307 // Half or less is successes.
22308
22309 return jStat.hypgeom.pdf(m - k, N, m, N - n);
22310
22311 } else if(m < n) {
22312 // We want to have the number of things sampled to be less than the
22313 // successes available. So swap the definitions of successful and sampled.
22314 return jStat.hypgeom.pdf(k, N, n, m);
22315 } else {
22316 // If we get here, half or less of the population was sampled, half or
22317 // less of it was successes, and we had fewer sampled things than
22318 // successes. Now we can do this complicated iterative algorithm in an
22319 // efficient way.
22320
22321 // The basic premise of the algorithm is that we partially normalize our
22322 // intermediate product to keep it in a numerically good region, and then
22323 // finish the normalization at the end.
22324
22325 // This variable holds the scaled probability of the current number of
22326 // successes.
22327 var scaledPDF = 1;
22328
22329 // This keeps track of how much we have normalized.
22330 var samplesDone = 0;
22331
22332 for(var i = 0; i < k; i++) {
22333 // For every possible number of successes up to that observed...
22334
22335 while(scaledPDF > 1 && samplesDone < n) {
22336 // Intermediate result is growing too big. Apply some of the
22337 // normalization to shrink everything.
22338
22339 scaledPDF *= 1 - (m / (N - samplesDone));
22340
22341 // Say we've normalized by this sample already.
22342 samplesDone++;
22343 }
22344
22345 // Work out the partially-normalized hypergeometric PDF for the next
22346 // number of successes
22347 scaledPDF *= (n - i) * (m - i) / ((i + 1) * (N - m - n + i + 1));
22348 }
22349
22350 for(; samplesDone < n; samplesDone++) {
22351 // Apply all the rest of the normalization
22352 scaledPDF *= 1 - (m / (N - samplesDone));
22353 }
22354
22355 // Bound answer sanely before returning.
22356 return Math.min(1, Math.max(0, scaledPDF));
22357 }
22358 },
22359
22360 cdf: function cdf(x, N, m, n) {
22361 // Hypergeometric CDF.
22362
22363 // This algorithm is due to Prof. Thomas S. Ferguson, <tom@math.ucla.edu>,
22364 // and comes from his hypergeometric test calculator at
22365 // <http://www.math.ucla.edu/~tom/distributions/Hypergeometric.html>.
22366
22367 // x = number of successes drawn
22368 // N = population size
22369 // m = number of successes in population
22370 // n = number of items drawn from population
22371
22372 if(x < 0 || x < m - (N - n)) {
22373 // It's impossible to have this few successes drawn or fewer.
22374 return 0;
22375 } else if(x >= n || x >= m) {
22376 // We will always have this many successes or fewer.
22377 return 1;
22378 } else if (m * 2 > N) {
22379 // More than half the population is successes.
22380
22381 if(n * 2 > N) {
22382 // More than half the population is sampled.
22383
22384 return jStat.hypgeom.cdf(N - m - n + x, N, N - m, N - n)
22385 } else {
22386 // Half or less of the population is sampled.
22387
22388 return 1 - jStat.hypgeom.cdf(n - x - 1, N, N - m, n);
22389 }
22390
22391 } else if(n * 2 > N) {
22392 // Half or less is successes.
22393
22394 return 1 - jStat.hypgeom.cdf(m - x - 1, N, m, N - n);
22395
22396 } else if(m < n) {
22397 // We want to have the number of things sampled to be less than the
22398 // successes available. So swap the definitions of successful and sampled.
22399 return jStat.hypgeom.cdf(x, N, n, m);
22400 } else {
22401 // If we get here, half or less of the population was sampled, half or
22402 // less of it was successes, and we had fewer sampled things than
22403 // successes. Now we can do this complicated iterative algorithm in an
22404 // efficient way.
22405
22406 // The basic premise of the algorithm is that we partially normalize our
22407 // intermediate sum to keep it in a numerically good region, and then
22408 // finish the normalization at the end.
22409
22410 // Holds the intermediate, scaled total CDF.
22411 var scaledCDF = 1;
22412
22413 // This variable holds the scaled probability of the current number of
22414 // successes.
22415 var scaledPDF = 1;
22416
22417 // This keeps track of how much we have normalized.
22418 var samplesDone = 0;
22419
22420 for(var i = 0; i < x; i++) {
22421 // For every possible number of successes up to that observed...
22422
22423 while(scaledCDF > 1 && samplesDone < n) {
22424 // Intermediate result is growing too big. Apply some of the
22425 // normalization to shrink everything.
22426
22427 var factor = 1 - (m / (N - samplesDone));
22428
22429 scaledPDF *= factor;
22430 scaledCDF *= factor;
22431
22432 // Say we've normalized by this sample already.
22433 samplesDone++;
22434 }
22435
22436 // Work out the partially-normalized hypergeometric PDF for the next
22437 // number of successes
22438 scaledPDF *= (n - i) * (m - i) / ((i + 1) * (N - m - n + i + 1));
22439
22440 // Add to the CDF answer.
22441 scaledCDF += scaledPDF;
22442 }
22443
22444 for(; samplesDone < n; samplesDone++) {
22445 // Apply all the rest of the normalization
22446 scaledCDF *= 1 - (m / (N - samplesDone));
22447 }
22448
22449 // Bound answer sanely before returning.
22450 return Math.min(1, Math.max(0, scaledCDF));
22451 }
22452 }
22453});
22454
22455
22456
22457// extend uniform function with static methods
22458jStat.extend(jStat.poisson, {
22459 pdf: function pdf(k, l) {
22460 if (l < 0 || (k % 1) !== 0 || k < 0) {
22461 return 0;
22462 }
22463
22464 return Math.pow(l, k) * Math.exp(-l) / jStat.factorial(k);
22465 },
22466
22467 cdf: function cdf(x, l) {
22468 var sumarr = [],
22469 k = 0;
22470 if (x < 0) return 0;
22471 for (; k <= x; k++) {
22472 sumarr.push(jStat.poisson.pdf(k, l));
22473 }
22474 return jStat.sum(sumarr);
22475 },
22476
22477 mean : function(l) {
22478 return l;
22479 },
22480
22481 variance : function(l) {
22482 return l;
22483 },
22484
22485 sample: function sample(l) {
22486 var p = 1, k = 0, L = Math.exp(-l);
22487 do {
22488 k++;
22489 p *= Math.random();
22490 } while (p > L);
22491 return k - 1;
22492 }
22493});
22494
22495// extend triangular function with static methods
22496jStat.extend(jStat.triangular, {
22497 pdf: function pdf(x, a, b, c) {
22498 if (b <= a || c < a || c > b) {
22499 return NaN;
22500 } else {
22501 if (x < a || x > b) {
22502 return 0;
22503 } else if (x < c) {
22504 return (2 * (x - a)) / ((b - a) * (c - a));
22505 } else if (x === c) {
22506 return (2 / (b - a));
22507 } else { // x > c
22508 return (2 * (b - x)) / ((b - a) * (b - c));
22509 }
22510 }
22511 },
22512
22513 cdf: function cdf(x, a, b, c) {
22514 if (b <= a || c < a || c > b)
22515 return NaN;
22516 if (x <= a)
22517 return 0;
22518 else if (x >= b)
22519 return 1;
22520 if (x <= c)
22521 return Math.pow(x - a, 2) / ((b - a) * (c - a));
22522 else // x > c
22523 return 1 - Math.pow(b - x, 2) / ((b - a) * (b - c));
22524 },
22525
22526 inv: function inv(p, a, b, c) {
22527 if (b <= a || c < a || c > b) {
22528 return NaN;
22529 } else {
22530 if (p <= ((c - a) / (b - a))) {
22531 return a + (b - a) * Math.sqrt(p * ((c - a) / (b - a)));
22532 } else { // p > ((c - a) / (b - a))
22533 return a + (b - a) * (1 - Math.sqrt((1 - p) * (1 - ((c - a) / (b - a)))));
22534 }
22535 }
22536 },
22537
22538 mean: function mean(a, b, c) {
22539 return (a + b + c) / 3;
22540 },
22541
22542 median: function median(a, b, c) {
22543 if (c <= (a + b) / 2) {
22544 return b - Math.sqrt((b - a) * (b - c)) / Math.sqrt(2);
22545 } else if (c > (a + b) / 2) {
22546 return a + Math.sqrt((b - a) * (c - a)) / Math.sqrt(2);
22547 }
22548 },
22549
22550 mode: function mode(a, b, c) {
22551 return c;
22552 },
22553
22554 sample: function sample(a, b, c) {
22555 var u = Math.random();
22556 if (u < ((c - a) / (b - a)))
22557 return a + Math.sqrt(u * (b - a) * (c - a))
22558 return b - Math.sqrt((1 - u) * (b - a) * (b - c));
22559 },
22560
22561 variance: function variance(a, b, c) {
22562 return (a * a + b * b + c * c - a * b - a * c - b * c) / 18;
22563 }
22564});
22565
22566function laplaceSign(x) { return x / Math.abs(x); }
22567
22568jStat.extend(jStat.laplace, {
22569 pdf: function pdf(x, mu, b) {
22570 return (b <= 0) ? 0 : (Math.exp(-Math.abs(x - mu) / b)) / (2 * b);
22571 },
22572
22573 cdf: function cdf(x, mu, b) {
22574 if (b <= 0) { return 0; }
22575
22576 if(x < mu) {
22577 return 0.5 * Math.exp((x - mu) / b);
22578 } else {
22579 return 1 - 0.5 * Math.exp(- (x - mu) / b);
22580 }
22581 },
22582
22583 mean: function(mu, b) {
22584 return mu;
22585 },
22586
22587 median: function(mu, b) {
22588 return mu;
22589 },
22590
22591 mode: function(mu, b) {
22592 return mu;
22593 },
22594
22595 variance: function(mu, b) {
22596 return 2 * b * b;
22597 },
22598
22599 sample: function sample(mu, b) {
22600 var u = Math.random() - 0.5;
22601
22602 return mu - (b * laplaceSign(u) * Math.log(1 - (2 * Math.abs(u))));
22603 }
22604});
22605
22606}(this.jStat, Math));
22607/* Provides functions for the solution of linear system of equations, integration, extrapolation,
22608 * interpolation, eigenvalue problems, differential equations and PCA analysis. */
22609
22610(function(jStat, Math) {
22611
22612var push = Array.prototype.push;
22613var isArray = jStat.utils.isArray;
22614
22615function isUsable(arg) {
22616 return isArray(arg) || arg instanceof jStat;
22617}
22618
22619jStat.extend({
22620
22621 // add a vector/matrix to a vector/matrix or scalar
22622 add: function add(arr, arg) {
22623 // check if arg is a vector or scalar
22624 if (isUsable(arg)) {
22625 if (!isUsable(arg[0])) arg = [ arg ];
22626 return jStat.map(arr, function(value, row, col) {
22627 return value + arg[row][col];
22628 });
22629 }
22630 return jStat.map(arr, function(value) { return value + arg; });
22631 },
22632
22633 // subtract a vector or scalar from the vector
22634 subtract: function subtract(arr, arg) {
22635 // check if arg is a vector or scalar
22636 if (isUsable(arg)) {
22637 if (!isUsable(arg[0])) arg = [ arg ];
22638 return jStat.map(arr, function(value, row, col) {
22639 return value - arg[row][col] || 0;
22640 });
22641 }
22642 return jStat.map(arr, function(value) { return value - arg; });
22643 },
22644
22645 // matrix division
22646 divide: function divide(arr, arg) {
22647 if (isUsable(arg)) {
22648 if (!isUsable(arg[0])) arg = [ arg ];
22649 return jStat.multiply(arr, jStat.inv(arg));
22650 }
22651 return jStat.map(arr, function(value) { return value / arg; });
22652 },
22653
22654 // matrix multiplication
22655 multiply: function multiply(arr, arg) {
22656 var row, col, nrescols, sum,
22657 nrow = arr.length,
22658 ncol = arr[0].length,
22659 res = jStat.zeros(nrow, nrescols = (isUsable(arg)) ? arg[0].length : ncol),
22660 rescols = 0;
22661 if (isUsable(arg)) {
22662 for (; rescols < nrescols; rescols++) {
22663 for (row = 0; row < nrow; row++) {
22664 sum = 0;
22665 for (col = 0; col < ncol; col++)
22666 sum += arr[row][col] * arg[col][rescols];
22667 res[row][rescols] = sum;
22668 }
22669 }
22670 return (nrow === 1 && rescols === 1) ? res[0][0] : res;
22671 }
22672 return jStat.map(arr, function(value) { return value * arg; });
22673 },
22674
22675 // Returns the dot product of two matricies
22676 dot: function dot(arr, arg) {
22677 if (!isUsable(arr[0])) arr = [ arr ];
22678 if (!isUsable(arg[0])) arg = [ arg ];
22679 // convert column to row vector
22680 var left = (arr[0].length === 1 && arr.length !== 1) ? jStat.transpose(arr) : arr,
22681 right = (arg[0].length === 1 && arg.length !== 1) ? jStat.transpose(arg) : arg,
22682 res = [],
22683 row = 0,
22684 nrow = left.length,
22685 ncol = left[0].length,
22686 sum, col;
22687 for (; row < nrow; row++) {
22688 res[row] = [];
22689 sum = 0;
22690 for (col = 0; col < ncol; col++)
22691 sum += left[row][col] * right[row][col];
22692 res[row] = sum;
22693 }
22694 return (res.length === 1) ? res[0] : res;
22695 },
22696
22697 // raise every element by a scalar
22698 pow: function pow(arr, arg) {
22699 return jStat.map(arr, function(value) { return Math.pow(value, arg); });
22700 },
22701
22702 // exponentiate every element
22703 exp: function exp(arr) {
22704 return jStat.map(arr, function(value) { return Math.exp(value); });
22705 },
22706
22707 // generate the natural log of every element
22708 log: function exp(arr) {
22709 return jStat.map(arr, function(value) { return Math.log(value); });
22710 },
22711
22712 // generate the absolute values of the vector
22713 abs: function abs(arr) {
22714 return jStat.map(arr, function(value) { return Math.abs(value); });
22715 },
22716
22717 // computes the p-norm of the vector
22718 // In the case that a matrix is passed, uses the first row as the vector
22719 norm: function norm(arr, p) {
22720 var nnorm = 0,
22721 i = 0;
22722 // check the p-value of the norm, and set for most common case
22723 if (isNaN(p)) p = 2;
22724 // check if multi-dimensional array, and make vector correction
22725 if (isUsable(arr[0])) arr = arr[0];
22726 // vector norm
22727 for (; i < arr.length; i++) {
22728 nnorm += Math.pow(Math.abs(arr[i]), p);
22729 }
22730 return Math.pow(nnorm, 1 / p);
22731 },
22732
22733 // computes the angle between two vectors in rads
22734 // In case a matrix is passed, this uses the first row as the vector
22735 angle: function angle(arr, arg) {
22736 return Math.acos(jStat.dot(arr, arg) / (jStat.norm(arr) * jStat.norm(arg)));
22737 },
22738
22739 // augment one matrix by another
22740 // Note: this function returns a matrix, not a jStat object
22741 aug: function aug(a, b) {
22742 var newarr = [];
22743 for (var i = 0; i < a.length; i++) {
22744 newarr.push(a[i].slice());
22745 }
22746 for (var i = 0; i < newarr.length; i++) {
22747 push.apply(newarr[i], b[i]);
22748 }
22749 return newarr;
22750 },
22751
22752 // The inv() function calculates the inverse of a matrix
22753 // Create the inverse by augmenting the matrix by the identity matrix of the
22754 // appropriate size, and then use G-J elimination on the augmented matrix.
22755 inv: function inv(a) {
22756 var rows = a.length;
22757 var cols = a[0].length;
22758 var b = jStat.identity(rows, cols);
22759 var c = jStat.gauss_jordan(a, b);
22760 var result = [];
22761 var i = 0;
22762 var j;
22763
22764 //We need to copy the inverse portion to a new matrix to rid G-J artifacts
22765 for (; i < rows; i++) {
22766 result[i] = [];
22767 for (j = cols; j < c[0].length; j++)
22768 result[i][j - cols] = c[i][j];
22769 }
22770 return result;
22771 },
22772
22773 // calculate the determinant of a matrix
22774 det: function det(a) {
22775 var alen = a.length,
22776 alend = alen * 2,
22777 vals = new Array(alend),
22778 rowshift = alen - 1,
22779 colshift = alend - 1,
22780 mrow = rowshift - alen + 1,
22781 mcol = colshift,
22782 i = 0,
22783 result = 0,
22784 j;
22785 // check for special 2x2 case
22786 if (alen === 2) {
22787 return a[0][0] * a[1][1] - a[0][1] * a[1][0];
22788 }
22789 for (; i < alend; i++) {
22790 vals[i] = 1;
22791 }
22792 for (i = 0; i < alen; i++) {
22793 for (j = 0; j < alen; j++) {
22794 vals[(mrow < 0) ? mrow + alen : mrow ] *= a[i][j];
22795 vals[(mcol < alen) ? mcol + alen : mcol ] *= a[i][j];
22796 mrow++;
22797 mcol--;
22798 }
22799 mrow = --rowshift - alen + 1;
22800 mcol = --colshift;
22801 }
22802 for (i = 0; i < alen; i++) {
22803 result += vals[i];
22804 }
22805 for (; i < alend; i++) {
22806 result -= vals[i];
22807 }
22808 return result;
22809 },
22810
22811 gauss_elimination: function gauss_elimination(a, b) {
22812 var i = 0,
22813 j = 0,
22814 n = a.length,
22815 m = a[0].length,
22816 factor = 1,
22817 sum = 0,
22818 x = [],
22819 maug, pivot, temp, k;
22820 a = jStat.aug(a, b);
22821 maug = a[0].length;
22822 for(i = 0; i < n; i++) {
22823 pivot = a[i][i];
22824 j = i;
22825 for (k = i + 1; k < m; k++) {
22826 if (pivot < Math.abs(a[k][i])) {
22827 pivot = a[k][i];
22828 j = k;
22829 }
22830 }
22831 if (j != i) {
22832 for(k = 0; k < maug; k++) {
22833 temp = a[i][k];
22834 a[i][k] = a[j][k];
22835 a[j][k] = temp;
22836 }
22837 }
22838 for (j = i + 1; j < n; j++) {
22839 factor = a[j][i] / a[i][i];
22840 for(k = i; k < maug; k++) {
22841 a[j][k] = a[j][k] - factor * a[i][k];
22842 }
22843 }
22844 }
22845 for (i = n - 1; i >= 0; i--) {
22846 sum = 0;
22847 for (j = i + 1; j<= n - 1; j++) {
22848 sum = sum + x[j] * a[i][j];
22849 }
22850 x[i] =(a[i][maug - 1] - sum) / a[i][i];
22851 }
22852 return x;
22853 },
22854
22855 gauss_jordan: function gauss_jordan(a, b) {
22856 var m = jStat.aug(a, b),
22857 h = m.length,
22858 w = m[0].length;
22859 // find max pivot
22860 for (var y = 0; y < h; y++) {
22861 var maxrow = y;
22862 for (var y2 = y+1; y2 < h; y2++) {
22863 if (Math.abs(m[y2][y]) > Math.abs(m[maxrow][y]))
22864 maxrow = y2;
22865 }
22866 var tmp = m[y];
22867 m[y] = m[maxrow];
22868 m[maxrow] = tmp
22869 for (var y2 = y+1; y2 < h; y2++) {
22870 c = m[y2][y] / m[y][y];
22871 for (var x = y; x < w; x++) {
22872 m[y2][x] -= m[y][x] * c;
22873 }
22874 }
22875 }
22876 // backsubstitute
22877 for (var y = h-1; y >= 0; y--) {
22878 c = m[y][y];
22879 for (var y2 = 0; y2 < y; y2++) {
22880 for (var x = w-1; x > y-1; x--) {
22881 m[y2][x] -= m[y][x] * m[y2][y] / c;
22882 }
22883 }
22884 m[y][y] /= c;
22885 for (var x = h; x < w; x++) {
22886 m[y][x] /= c;
22887 }
22888 }
22889 return m;
22890 },
22891
22892 lu: function lu(a, b) {
22893 throw new Error('lu not yet implemented');
22894 },
22895
22896 cholesky: function cholesky(a, b) {
22897 throw new Error('cholesky not yet implemented');
22898 },
22899
22900 gauss_jacobi: function gauss_jacobi(a, b, x, r) {
22901 var i = 0;
22902 var j = 0;
22903 var n = a.length;
22904 var l = [];
22905 var u = [];
22906 var d = [];
22907 var xv, c, h, xk;
22908 for (; i < n; i++) {
22909 l[i] = [];
22910 u[i] = [];
22911 d[i] = [];
22912 for (j = 0; j < n; j++) {
22913 if (i > j) {
22914 l[i][j] = a[i][j];
22915 u[i][j] = d[i][j] = 0;
22916 } else if (i < j) {
22917 u[i][j] = a[i][j];
22918 l[i][j] = d[i][j] = 0;
22919 } else {
22920 d[i][j] = a[i][j];
22921 l[i][j] = u[i][j] = 0;
22922 }
22923 }
22924 }
22925 h = jStat.multiply(jStat.multiply(jStat.inv(d), jStat.add(l, u)), -1);
22926 c = jStat.multiply(jStat.inv(d), b);
22927 xv = x;
22928 xk = jStat.add(jStat.multiply(h, x), c);
22929 i = 2;
22930 while (Math.abs(jStat.norm(jStat.subtract(xk,xv))) > r) {
22931 xv = xk;
22932 xk = jStat.add(jStat.multiply(h, xv), c);
22933 i++;
22934 }
22935 return xk;
22936 },
22937
22938 gauss_seidel: function gauss_seidel(a, b, x, r) {
22939 var i = 0;
22940 var n = a.length;
22941 var l = [];
22942 var u = [];
22943 var d = [];
22944 var j, xv, c, h, xk;
22945 for (; i < n; i++) {
22946 l[i] = [];
22947 u[i] = [];
22948 d[i] = [];
22949 for (j = 0; j < n; j++) {
22950 if (i > j) {
22951 l[i][j] = a[i][j];
22952 u[i][j] = d[i][j] = 0;
22953 } else if (i < j) {
22954 u[i][j] = a[i][j];
22955 l[i][j] = d[i][j] = 0;
22956 } else {
22957 d[i][j] = a[i][j];
22958 l[i][j] = u[i][j] = 0;
22959 }
22960 }
22961 }
22962 h = jStat.multiply(jStat.multiply(jStat.inv(jStat.add(d, l)), u), -1);
22963 c = jStat.multiply(jStat.inv(jStat.add(d, l)), b);
22964 xv = x;
22965 xk = jStat.add(jStat.multiply(h, x), c);
22966 i = 2;
22967 while (Math.abs(jStat.norm(jStat.subtract(xk, xv))) > r) {
22968 xv = xk;
22969 xk = jStat.add(jStat.multiply(h, xv), c);
22970 i = i + 1;
22971 }
22972 return xk;
22973 },
22974
22975 SOR: function SOR(a, b, x, r, w) {
22976 var i = 0;
22977 var n = a.length;
22978 var l = [];
22979 var u = [];
22980 var d = [];
22981 var j, xv, c, h, xk;
22982 for (; i < n; i++) {
22983 l[i] = [];
22984 u[i] = [];
22985 d[i] = [];
22986 for (j = 0; j < n; j++) {
22987 if (i > j) {
22988 l[i][j] = a[i][j];
22989 u[i][j] = d[i][j] = 0;
22990 } else if (i < j) {
22991 u[i][j] = a[i][j];
22992 l[i][j] = d[i][j] = 0;
22993 } else {
22994 d[i][j] = a[i][j];
22995 l[i][j] = u[i][j] = 0;
22996 }
22997 }
22998 }
22999 h = jStat.multiply(jStat.inv(jStat.add(d, jStat.multiply(l, w))),
23000 jStat.subtract(jStat.multiply(d, 1 - w),
23001 jStat.multiply(u, w)));
23002 c = jStat.multiply(jStat.multiply(jStat.inv(jStat.add(d,
23003 jStat.multiply(l, w))), b), w);
23004 xv = x;
23005 xk = jStat.add(jStat.multiply(h, x), c);
23006 i = 2;
23007 while (Math.abs(jStat.norm(jStat.subtract(xk, xv))) > r) {
23008 xv = xk;
23009 xk = jStat.add(jStat.multiply(h, xv), c);
23010 i++;
23011 }
23012 return xk;
23013 },
23014
23015 householder: function householder(a) {
23016 var m = a.length;
23017 var n = a[0].length;
23018 var i = 0;
23019 var w = [];
23020 var p = [];
23021 var alpha, r, k, j, factor;
23022 for (; i < m - 1; i++) {
23023 alpha = 0;
23024 for (j = i + 1; j < n; j++)
23025 alpha += (a[j][i] * a[j][i]);
23026 factor = (a[i + 1][i] > 0) ? -1 : 1;
23027 alpha = factor * Math.sqrt(alpha);
23028 r = Math.sqrt((((alpha * alpha) - a[i + 1][i] * alpha) / 2));
23029 w = jStat.zeros(m, 1);
23030 w[i + 1][0] = (a[i + 1][i] - alpha) / (2 * r);
23031 for (k = i + 2; k < m; k++) w[k][0] = a[k][i] / (2 * r);
23032 p = jStat.subtract(jStat.identity(m, n),
23033 jStat.multiply(jStat.multiply(w, jStat.transpose(w)), 2));
23034 a = jStat.multiply(p, jStat.multiply(a, p));
23035 }
23036 return a;
23037 },
23038
23039 // TODO: not working properly.
23040 QR: function QR(a, b) {
23041 var m = a.length;
23042 var n = a[0].length;
23043 var i = 0;
23044 var w = [];
23045 var p = [];
23046 var x = [];
23047 var j, alpha, r, k, factor, sum;
23048 for (; i < m - 1; i++) {
23049 alpha = 0;
23050 for (j = i + 1; j < n; j++)
23051 alpha += (a[j][i] * a[j][i]);
23052 factor = (a[i + 1][i] > 0) ? -1 : 1;
23053 alpha = factor * Math.sqrt(alpha);
23054 r = Math.sqrt((((alpha * alpha) - a[i + 1][i] * alpha) / 2));
23055 w = jStat.zeros(m, 1);
23056 w[i + 1][0] = (a[i + 1][i] - alpha) / (2 * r);
23057 for (k = i + 2; k < m; k++)
23058 w[k][0] = a[k][i] / (2 * r);
23059 p = jStat.subtract(jStat.identity(m, n),
23060 jStat.multiply(jStat.multiply(w, jStat.transpose(w)), 2));
23061 a = jStat.multiply(p, a);
23062 b = jStat.multiply(p, b);
23063 }
23064 for (i = m - 1; i >= 0; i--) {
23065 sum = 0;
23066 for (j = i + 1; j <= n - 1; j++)
23067 sum = x[j] * a[i][j];
23068 x[i] = b[i][0] / a[i][i];
23069 }
23070 return x;
23071 },
23072
23073 jacobi: function jacobi(a) {
23074 var condition = 1;
23075 var count = 0;
23076 var n = a.length;
23077 var e = jStat.identity(n, n);
23078 var ev = [];
23079 var b, i, j, p, q, maxim, theta, s;
23080 // condition === 1 only if tolerance is not reached
23081 while (condition === 1) {
23082 count++;
23083 maxim = a[0][1];
23084 p = 0;
23085 q = 1;
23086 for (i = 0; i < n; i++) {
23087 for (j = 0; j < n; j++) {
23088 if (i != j) {
23089 if (maxim < Math.abs(a[i][j])) {
23090 maxim = Math.abs(a[i][j]);
23091 p = i;
23092 q = j;
23093 }
23094 }
23095 }
23096 }
23097 if (a[p][p] === a[q][q])
23098 theta = (a[p][q] > 0) ? Math.PI / 4 : -Math.PI / 4;
23099 else
23100 theta = Math.atan(2 * a[p][q] / (a[p][p] - a[q][q])) / 2;
23101 s = jStat.identity(n, n);
23102 s[p][p] = Math.cos(theta);
23103 s[p][q] = -Math.sin(theta);
23104 s[q][p] = Math.sin(theta);
23105 s[q][q] = Math.cos(theta);
23106 // eigen vector matrix
23107 e = jStat.multiply(e, s);
23108 b = jStat.multiply(jStat.multiply(jStat.inv(s), a), s);
23109 a = b;
23110 condition = 0;
23111 for (i = 1; i < n; i++) {
23112 for (j = 1; j < n; j++) {
23113 if (i != j && Math.abs(a[i][j]) > 0.001) {
23114 condition = 1;
23115 }
23116 }
23117 }
23118 }
23119 for (i = 0; i < n; i++) ev.push(a[i][i]);
23120 //returns both the eigenvalue and eigenmatrix
23121 return [e, ev];
23122 },
23123
23124 rungekutta: function rungekutta(f, h, p, t_j, u_j, order) {
23125 var k1, k2, u_j1, k3, k4;
23126 if (order === 2) {
23127 while (t_j <= p) {
23128 k1 = h * f(t_j, u_j);
23129 k2 = h * f(t_j + h, u_j + k1);
23130 u_j1 = u_j + (k1 + k2) / 2;
23131 u_j = u_j1;
23132 t_j = t_j + h;
23133 }
23134 }
23135 if (order === 4) {
23136 while (t_j <= p) {
23137 k1 = h * f(t_j, u_j);
23138 k2 = h * f(t_j + h / 2, u_j + k1 / 2);
23139 k3 = h * f(t_j + h / 2, u_j + k2 / 2);
23140 k4 = h * f(t_j +h, u_j + k3);
23141 u_j1 = u_j + (k1 + 2 * k2 + 2 * k3 + k4) / 6;
23142 u_j = u_j1;
23143 t_j = t_j + h;
23144 }
23145 }
23146 return u_j;
23147 },
23148
23149 romberg: function romberg(f, a, b, order) {
23150 var i = 0;
23151 var h = (b - a) / 2;
23152 var x = [];
23153 var h1 = [];
23154 var g = [];
23155 var m, a1, j, k, I, d;
23156 while (i < order / 2) {
23157 I = f(a);
23158 for (j = a, k = 0; j <= b; j = j + h, k++) x[k] = j;
23159 m = x.length;
23160 for (j = 1; j < m - 1; j++) {
23161 I += (((j % 2) !== 0) ? 4 : 2) * f(x[j]);
23162 }
23163 I = (h / 3) * (I + f(b));
23164 g[i] = I;
23165 h /= 2;
23166 i++;
23167 }
23168 a1 = g.length;
23169 m = 1;
23170 while (a1 !== 1) {
23171 for (j = 0; j < a1 - 1; j++)
23172 h1[j] = ((Math.pow(4, m)) * g[j + 1] - g[j]) / (Math.pow(4, m) - 1);
23173 a1 = h1.length;
23174 g = h1;
23175 h1 = [];
23176 m++;
23177 }
23178 return g;
23179 },
23180
23181 richardson: function richardson(X, f, x, h) {
23182 function pos(X, x) {
23183 var i = 0;
23184 var n = X.length;
23185 var p;
23186 for (; i < n; i++)
23187 if (X[i] === x) p = i;
23188 return p;
23189 }
23190 var n = X.length,
23191 h_min = Math.abs(x - X[pos(X, x) + 1]),
23192 i = 0,
23193 g = [],
23194 h1 = [],
23195 y1, y2, m, a, j;
23196 while (h >= h_min) {
23197 y1 = pos(X, x + h);
23198 y2 = pos(X, x);
23199 g[i] = (f[y1] - 2 * f[y2] + f[2 * y2 - y1]) / (h * h);
23200 h /= 2;
23201 i++;
23202 }
23203 a = g.length;
23204 m = 1;
23205 while (a != 1) {
23206 for (j = 0; j < a - 1; j++)
23207 h1[j] = ((Math.pow(4, m)) * g[j + 1] - g[j]) / (Math.pow(4, m) - 1);
23208 a = h1.length;
23209 g = h1;
23210 h1 = [];
23211 m++;
23212 }
23213 return g;
23214 },
23215
23216 simpson: function simpson(f, a, b, n) {
23217 var h = (b - a) / n;
23218 var I = f(a);
23219 var x = [];
23220 var j = a;
23221 var k = 0;
23222 var i = 1;
23223 var m;
23224 for (; j <= b; j = j + h, k++)
23225 x[k] = j;
23226 m = x.length;
23227 for (; i < m - 1; i++) {
23228 I += ((i % 2 !== 0) ? 4 : 2) * f(x[i]);
23229 }
23230 return (h / 3) * (I + f(b));
23231 },
23232
23233 hermite: function hermite(X, F, dF, value) {
23234 var n = X.length;
23235 var p = 0;
23236 var i = 0;
23237 var l = [];
23238 var dl = [];
23239 var A = [];
23240 var B = [];
23241 var j;
23242 for (; i < n; i++) {
23243 l[i] = 1;
23244 for (j = 0; j < n; j++) {
23245 if (i != j) l[i] *= (value - X[j]) / (X[i] - X[j]);
23246 }
23247 dl[i] = 0;
23248 for (j = 0; j < n; j++) {
23249 if (i != j) dl[i] += 1 / (X [i] - X[j]);
23250 }
23251 A[i] = (1 - 2 * (value - X[i]) * dl[i]) * (l[i] * l[i]);
23252 B[i] = (value - X[i]) * (l[i] * l[i]);
23253 p += (A[i] * F[i] + B[i] * dF[i]);
23254 }
23255 return p;
23256 },
23257
23258 lagrange: function lagrange(X, F, value) {
23259 var p = 0;
23260 var i = 0;
23261 var j, l;
23262 var n = X.length;
23263 for (; i < n; i++) {
23264 l = F[i];
23265 for (j = 0; j < n; j++) {
23266 // calculating the lagrange polynomial L_i
23267 if (i != j) l *= (value - X[j]) / (X[i] - X[j]);
23268 }
23269 // adding the lagrange polynomials found above
23270 p += l;
23271 }
23272 return p;
23273 },
23274
23275 cubic_spline: function cubic_spline(X, F, value) {
23276 var n = X.length;
23277 var i = 0, j;
23278 var A = [];
23279 var B = [];
23280 var alpha = [];
23281 var c = [];
23282 var h = [];
23283 var b = [];
23284 var d = [];
23285 for (; i < n - 1; i++)
23286 h[i] = X[i + 1] - X[i];
23287 alpha[0] = 0;
23288 for (i = 1; i < n - 1; i++) {
23289 alpha[i] = (3 / h[i]) * (F[i + 1] - F[i]) -
23290 (3 / h[i-1]) * (F[i] - F[i-1]);
23291 }
23292 for (i = 1; i < n - 1; i++) {
23293 A[i] = [];
23294 B[i] = [];
23295 A[i][i-1] = h[i-1];
23296 A[i][i] = 2 * (h[i - 1] + h[i]);
23297 A[i][i+1] = h[i];
23298 B[i][0] = alpha[i];
23299 }
23300 c = jStat.multiply(jStat.inv(A), B);
23301 for (j = 0; j < n - 1; j++) {
23302 b[j] = (F[j + 1] - F[j]) / h[j] - h[j] * (c[j + 1][0] + 2 * c[j][0]) / 3;
23303 d[j] = (c[j + 1][0] - c[j][0]) / (3 * h[j]);
23304 }
23305 for (j = 0; j < n; j++) {
23306 if (X[j] > value) break;
23307 }
23308 j -= 1;
23309 return F[j] + (value - X[j]) * b[j] + jStat.sq(value-X[j]) *
23310 c[j] + (value - X[j]) * jStat.sq(value - X[j]) * d[j];
23311 },
23312
23313 gauss_quadrature: function gauss_quadrature() {
23314 throw new Error('gauss_quadrature not yet implemented');
23315 },
23316
23317 PCA: function PCA(X) {
23318 var m = X.length;
23319 var n = X[0].length;
23320 var flag = false;
23321 var i = 0;
23322 var j, temp1;
23323 var u = [];
23324 var D = [];
23325 var result = [];
23326 var temp2 = [];
23327 var Y = [];
23328 var Bt = [];
23329 var B = [];
23330 var C = [];
23331 var V = [];
23332 var Vt = [];
23333 for (i = 0; i < m; i++) {
23334 u[i] = jStat.sum(X[i]) / n;
23335 }
23336 for (i = 0; i < n; i++) {
23337 B[i] = [];
23338 for(j = 0; j < m; j++) {
23339 B[i][j] = X[j][i] - u[j];
23340 }
23341 }
23342 B = jStat.transpose(B);
23343 for (i = 0; i < m; i++) {
23344 C[i] = [];
23345 for (j = 0; j < m; j++) {
23346 C[i][j] = (jStat.dot([B[i]], [B[j]])) / (n - 1);
23347 }
23348 }
23349 result = jStat.jacobi(C);
23350 V = result[0];
23351 D = result[1];
23352 Vt = jStat.transpose(V);
23353 for (i = 0; i < D.length; i++) {
23354 for (j = i; j < D.length; j++) {
23355 if(D[i] < D[j]) {
23356 temp1 = D[i];
23357 D[i] = D[j];
23358 D[j] = temp1;
23359 temp2 = Vt[i];
23360 Vt[i] = Vt[j];
23361 Vt[j] = temp2;
23362 }
23363 }
23364 }
23365 Bt = jStat.transpose(B);
23366 for (i = 0; i < m; i++) {
23367 Y[i] = [];
23368 for (j = 0; j < Bt.length; j++) {
23369 Y[i][j] = jStat.dot([Vt[i]], [Bt[j]]);
23370 }
23371 }
23372 return [X, D, Vt, Y];
23373 }
23374});
23375
23376// extend jStat.fn with methods that require one argument
23377(function(funcs) {
23378 for (var i = 0; i < funcs.length; i++) (function(passfunc) {
23379 jStat.fn[passfunc] = function(arg, func) {
23380 var tmpthis = this;
23381 // check for callback
23382 if (func) {
23383 setTimeout(function() {
23384 func.call(tmpthis, jStat.fn[passfunc].call(tmpthis, arg));
23385 }, 15);
23386 return this;
23387 }
23388 if (typeof jStat[passfunc](this, arg) === 'number')
23389 return jStat[passfunc](this, arg);
23390 else
23391 return jStat(jStat[passfunc](this, arg));
23392 };
23393 }(funcs[i]));
23394}('add divide multiply subtract dot pow exp log abs norm angle'.split(' ')));
23395
23396}(this.jStat, Math));
23397(function(jStat, Math) {
23398
23399var slice = [].slice;
23400var isNumber = jStat.utils.isNumber;
23401var isArray = jStat.utils.isArray;
23402
23403// flag==true denotes use of sample standard deviation
23404// Z Statistics
23405jStat.extend({
23406 // 2 different parameter lists:
23407 // (value, mean, sd)
23408 // (value, array, flag)
23409 zscore: function zscore() {
23410 var args = slice.call(arguments);
23411 if (isNumber(args[1])) {
23412 return (args[0] - args[1]) / args[2];
23413 }
23414 return (args[0] - jStat.mean(args[1])) / jStat.stdev(args[1], args[2]);
23415 },
23416
23417 // 3 different paramter lists:
23418 // (value, mean, sd, sides)
23419 // (zscore, sides)
23420 // (value, array, sides, flag)
23421 ztest: function ztest() {
23422 var args = slice.call(arguments);
23423 var z;
23424 if (isArray(args[1])) {
23425 // (value, array, sides, flag)
23426 z = jStat.zscore(args[0],args[1],args[3]);
23427 return (args[2] === 1) ?
23428 (jStat.normal.cdf(-Math.abs(z), 0, 1)) :
23429 (jStat.normal.cdf(-Math.abs(z), 0, 1)*2);
23430 } else {
23431 if (args.length > 2) {
23432 // (value, mean, sd, sides)
23433 z = jStat.zscore(args[0],args[1],args[2]);
23434 return (args[3] === 1) ?
23435 (jStat.normal.cdf(-Math.abs(z),0,1)) :
23436 (jStat.normal.cdf(-Math.abs(z),0,1)* 2);
23437 } else {
23438 // (zscore, sides)
23439 z = args[0];
23440 return (args[1] === 1) ?
23441 (jStat.normal.cdf(-Math.abs(z),0,1)) :
23442 (jStat.normal.cdf(-Math.abs(z),0,1)*2);
23443 }
23444 }
23445 }
23446});
23447
23448jStat.extend(jStat.fn, {
23449 zscore: function zscore(value, flag) {
23450 return (value - this.mean()) / this.stdev(flag);
23451 },
23452
23453 ztest: function ztest(value, sides, flag) {
23454 var zscore = Math.abs(this.zscore(value, flag));
23455 return (sides === 1) ?
23456 (jStat.normal.cdf(-zscore, 0, 1)) :
23457 (jStat.normal.cdf(-zscore, 0, 1) * 2);
23458 }
23459});
23460
23461// T Statistics
23462jStat.extend({
23463 // 2 parameter lists
23464 // (value, mean, sd, n)
23465 // (value, array)
23466 tscore: function tscore() {
23467 var args = slice.call(arguments);
23468 return (args.length === 4) ?
23469 ((args[0] - args[1]) / (args[2] / Math.sqrt(args[3]))) :
23470 ((args[0] - jStat.mean(args[1])) /
23471 (jStat.stdev(args[1], true) / Math.sqrt(args[1].length)));
23472 },
23473
23474 // 3 different paramter lists:
23475 // (value, mean, sd, n, sides)
23476 // (tscore, n, sides)
23477 // (value, array, sides)
23478 ttest: function ttest() {
23479 var args = slice.call(arguments);
23480 var tscore;
23481 if (args.length === 5) {
23482 tscore = Math.abs(jStat.tscore(args[0], args[1], args[2], args[3]));
23483 return (args[4] === 1) ?
23484 (jStat.studentt.cdf(-tscore, args[3]-1)) :
23485 (jStat.studentt.cdf(-tscore, args[3]-1)*2);
23486 }
23487 if (isNumber(args[1])) {
23488 tscore = Math.abs(args[0])
23489 return (args[2] == 1) ?
23490 (jStat.studentt.cdf(-tscore, args[1]-1)) :
23491 (jStat.studentt.cdf(-tscore, args[1]-1) * 2);
23492 }
23493 tscore = Math.abs(jStat.tscore(args[0], args[1]))
23494 return (args[2] == 1) ?
23495 (jStat.studentt.cdf(-tscore, args[1].length-1)) :
23496 (jStat.studentt.cdf(-tscore, args[1].length-1) * 2);
23497 }
23498});
23499
23500jStat.extend(jStat.fn, {
23501 tscore: function tscore(value) {
23502 return (value - this.mean()) / (this.stdev(true) / Math.sqrt(this.cols()));
23503 },
23504
23505 ttest: function ttest(value, sides) {
23506 return (sides === 1) ?
23507 (1 - jStat.studentt.cdf(Math.abs(this.tscore(value)), this.cols()-1)) :
23508 (jStat.studentt.cdf(-Math.abs(this.tscore(value)), this.cols()-1)*2);
23509 }
23510});
23511
23512// F Statistics
23513jStat.extend({
23514 // Paramter list is as follows:
23515 // (array1, array2, array3, ...)
23516 // or it is an array of arrays
23517 // array of arrays conversion
23518 anovafscore: function anovafscore() {
23519 var args = slice.call(arguments),
23520 expVar, sample, sampMean, sampSampMean, tmpargs, unexpVar, i, j;
23521 if (args.length === 1) {
23522 tmpargs = new Array(args[0].length);
23523 for (i = 0; i < args[0].length; i++) {
23524 tmpargs[i] = args[0][i];
23525 }
23526 args = tmpargs;
23527 }
23528 // 2 sample case
23529 if (args.length === 2) {
23530 return jStat.variance(args[0]) / jStat.variance(args[1]);
23531 }
23532 // Builds sample array
23533 sample = new Array();
23534 for (i = 0; i < args.length; i++) {
23535 sample = sample.concat(args[i]);
23536 }
23537 sampMean = jStat.mean(sample);
23538 // Computes the explained variance
23539 expVar = 0;
23540 for (i = 0; i < args.length; i++) {
23541 expVar = expVar + args[i].length * Math.pow(jStat.mean(args[i]) - sampMean, 2);
23542 }
23543 expVar /= (args.length - 1);
23544 // Computes unexplained variance
23545 unexpVar = 0;
23546 for (i = 0; i < args.length; i++) {
23547 sampSampMean = jStat.mean(args[i]);
23548 for (j = 0; j < args[i].length; j++) {
23549 unexpVar += Math.pow(args[i][j] - sampSampMean, 2);
23550 }
23551 }
23552 unexpVar /= (sample.length - args.length);
23553 return expVar / unexpVar;
23554 },
23555
23556 // 2 different paramter setups
23557 // (array1, array2, array3, ...)
23558 // (anovafscore, df1, df2)
23559 anovaftest: function anovaftest() {
23560 var args = slice.call(arguments),
23561 df1, df2, n, i;
23562 if (isNumber(args[0])) {
23563 return 1 - jStat.centralF.cdf(args[0], args[1], args[2]);
23564 }
23565 anovafscore = jStat.anovafscore(args);
23566 df1 = args.length - 1;
23567 n = 0;
23568 for (i = 0; i < args.length; i++) {
23569 n = n + args[i].length;
23570 }
23571 df2 = n - df1 - 1;
23572 return 1 - jStat.centralF.cdf(anovafscore, df1, df2);
23573 },
23574
23575 ftest: function ftest(fscore, df1, df2) {
23576 return 1 - jStat.centralF.cdf(fscore, df1, df2);
23577 }
23578});
23579
23580jStat.extend(jStat.fn, {
23581 anovafscore: function anovafscore() {
23582 return jStat.anovafscore(this.toArray());
23583 },
23584
23585 anovaftes: function anovaftes() {
23586 var n = 0;
23587 var i;
23588 for (i = 0; i < this.length; i++) {
23589 n = n + this[i].length;
23590 }
23591 return jStat.ftest(this.anovafscore(), this.length - 1, n - this.length);
23592 }
23593});
23594
23595// Error Bounds
23596jStat.extend({
23597 // 2 different parameter setups
23598 // (value, alpha, sd, n)
23599 // (value, alpha, array)
23600 normalci: function normalci() {
23601 var args = slice.call(arguments),
23602 ans = new Array(2),
23603 change;
23604 if (args.length === 4) {
23605 change = Math.abs(jStat.normal.inv(args[1] / 2, 0, 1) *
23606 args[2] / Math.sqrt(args[3]));
23607 } else {
23608 change = Math.abs(jStat.normal.inv(args[1] / 2, 0, 1) *
23609 jStat.stdev(args[2]) / Math.sqrt(args[2].length));
23610 }
23611 ans[0] = args[0] - change;
23612 ans[1] = args[0] + change;
23613 return ans;
23614 },
23615
23616 // 2 different parameter setups
23617 // (value, alpha, sd, n)
23618 // (value, alpha, array)
23619 tci: function tci() {
23620 var args = slice.call(arguments),
23621 ans = new Array(2),
23622 change;
23623 if (args.length === 4) {
23624 change = Math.abs(jStat.studentt.inv(args[1] / 2, args[3] - 1) *
23625 args[2] / Math.sqrt(args[3]));
23626 } else {
23627 change = Math.abs(jStat.studentt.inv(args[1] / 2, args[2].length - 1) *
23628 jStat.stdev(args[2], true) / Math.sqrt(args[2].length));
23629 }
23630 ans[0] = args[0] - change;
23631 ans[1] = args[0] + change;
23632 return ans;
23633 },
23634
23635 significant: function significant(pvalue, alpha) {
23636 return pvalue < alpha;
23637 }
23638});
23639
23640jStat.extend(jStat.fn, {
23641 normalci: function normalci(value, alpha) {
23642 return jStat.normalci(value, alpha, this.toArray());
23643 },
23644
23645 tci: function tci(value, alpha) {
23646 return jStat.tci(value, alpha, this.toArray());
23647 }
23648});
23649
23650// internal method for calculating the z-score for a difference of proportions test
23651function differenceOfProportions(p1, n1, p2, n2) {
23652 if (p1 > 1 || p2 > 1 || p1 <= 0 || p2 <= 0) {
23653 throw new Error("Proportions should be greater than 0 and less than 1")
23654 }
23655 var pooled = (p1 * n1 + p2 * n2) / (n1 + n2);
23656 var se = Math.sqrt(pooled * (1 - pooled) * ((1/n1) + (1/n2)));
23657 return (p1 - p2) / se;
23658}
23659
23660// Difference of Proportions
23661jStat.extend(jStat.fn, {
23662 oneSidedDifferenceOfProportions: function oneSidedDifferenceOfProportions(p1, n1, p2, n2) {
23663 var z = differenceOfProportions(p1, n1, p2, n2);
23664 return jStat.ztest(z, 1);
23665 },
23666
23667 twoSidedDifferenceOfProportions: function twoSidedDifferenceOfProportions(p1, n1, p2, n2) {
23668 var z = differenceOfProportions(p1, n1, p2, n2);
23669 return jStat.ztest(z, 2);
23670 }
23671});
23672
23673}(this.jStat, Math));
23674
23675},{}],15:[function(require,module,exports){
23676(function (global){
23677/**
23678 * @license
23679 * lodash <https://lodash.com/>
23680 * Copyright jQuery Foundation and other contributors <https://jquery.org/>
23681 * Released under MIT license <https://lodash.com/license>
23682 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
23683 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
23684 */
23685;(function() {
23686
23687 /** Used as a safe reference for `undefined` in pre-ES5 environments. */
23688 var undefined;
23689
23690 /** Used as the semantic version number. */
23691 var VERSION = '4.16.4';
23692
23693 /** Used as the size to enable large array optimizations. */
23694 var LARGE_ARRAY_SIZE = 200;
23695
23696 /** Error message constants. */
23697 var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://github.com/es-shims.',
23698 FUNC_ERROR_TEXT = 'Expected a function';
23699
23700 /** Used to stand-in for `undefined` hash values. */
23701 var HASH_UNDEFINED = '__lodash_hash_undefined__';
23702
23703 /** Used as the maximum memoize cache size. */
23704 var MAX_MEMOIZE_SIZE = 500;
23705
23706 /** Used as the internal argument placeholder. */
23707 var PLACEHOLDER = '__lodash_placeholder__';
23708
23709 /** Used to compose bitmasks for function metadata. */
23710 var BIND_FLAG = 1,
23711 BIND_KEY_FLAG = 2,
23712 CURRY_BOUND_FLAG = 4,
23713 CURRY_FLAG = 8,
23714 CURRY_RIGHT_FLAG = 16,
23715 PARTIAL_FLAG = 32,
23716 PARTIAL_RIGHT_FLAG = 64,
23717 ARY_FLAG = 128,
23718 REARG_FLAG = 256,
23719 FLIP_FLAG = 512;
23720
23721 /** Used to compose bitmasks for comparison styles. */
23722 var UNORDERED_COMPARE_FLAG = 1,
23723 PARTIAL_COMPARE_FLAG = 2;
23724
23725 /** Used as default options for `_.truncate`. */
23726 var DEFAULT_TRUNC_LENGTH = 30,
23727 DEFAULT_TRUNC_OMISSION = '...';
23728
23729 /** Used to detect hot functions by number of calls within a span of milliseconds. */
23730 var HOT_COUNT = 500,
23731 HOT_SPAN = 16;
23732
23733 /** Used to indicate the type of lazy iteratees. */
23734 var LAZY_FILTER_FLAG = 1,
23735 LAZY_MAP_FLAG = 2,
23736 LAZY_WHILE_FLAG = 3;
23737
23738 /** Used as references for various `Number` constants. */
23739 var INFINITY = 1 / 0,
23740 MAX_SAFE_INTEGER = 9007199254740991,
23741 MAX_INTEGER = 1.7976931348623157e+308,
23742 NAN = 0 / 0;
23743
23744 /** Used as references for the maximum length and index of an array. */
23745 var MAX_ARRAY_LENGTH = 4294967295,
23746 MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,
23747 HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;
23748
23749 /** Used to associate wrap methods with their bit flags. */
23750 var wrapFlags = [
23751 ['ary', ARY_FLAG],
23752 ['bind', BIND_FLAG],
23753 ['bindKey', BIND_KEY_FLAG],
23754 ['curry', CURRY_FLAG],
23755 ['curryRight', CURRY_RIGHT_FLAG],
23756 ['flip', FLIP_FLAG],
23757 ['partial', PARTIAL_FLAG],
23758 ['partialRight', PARTIAL_RIGHT_FLAG],
23759 ['rearg', REARG_FLAG]
23760 ];
23761
23762 /** `Object#toString` result references. */
23763 var argsTag = '[object Arguments]',
23764 arrayTag = '[object Array]',
23765 boolTag = '[object Boolean]',
23766 dateTag = '[object Date]',
23767 errorTag = '[object Error]',
23768 funcTag = '[object Function]',
23769 genTag = '[object GeneratorFunction]',
23770 mapTag = '[object Map]',
23771 numberTag = '[object Number]',
23772 objectTag = '[object Object]',
23773 promiseTag = '[object Promise]',
23774 proxyTag = '[object Proxy]',
23775 regexpTag = '[object RegExp]',
23776 setTag = '[object Set]',
23777 stringTag = '[object String]',
23778 symbolTag = '[object Symbol]',
23779 weakMapTag = '[object WeakMap]',
23780 weakSetTag = '[object WeakSet]';
23781
23782 var arrayBufferTag = '[object ArrayBuffer]',
23783 dataViewTag = '[object DataView]',
23784 float32Tag = '[object Float32Array]',
23785 float64Tag = '[object Float64Array]',
23786 int8Tag = '[object Int8Array]',
23787 int16Tag = '[object Int16Array]',
23788 int32Tag = '[object Int32Array]',
23789 uint8Tag = '[object Uint8Array]',
23790 uint8ClampedTag = '[object Uint8ClampedArray]',
23791 uint16Tag = '[object Uint16Array]',
23792 uint32Tag = '[object Uint32Array]';
23793
23794 /** Used to match empty string literals in compiled template source. */
23795 var reEmptyStringLeading = /\b__p \+= '';/g,
23796 reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
23797 reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
23798
23799 /** Used to match HTML entities and HTML characters. */
23800 var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g,
23801 reUnescapedHtml = /[&<>"']/g,
23802 reHasEscapedHtml = RegExp(reEscapedHtml.source),
23803 reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
23804
23805 /** Used to match template delimiters. */
23806 var reEscape = /<%-([\s\S]+?)%>/g,
23807 reEvaluate = /<%([\s\S]+?)%>/g,
23808 reInterpolate = /<%=([\s\S]+?)%>/g;
23809
23810 /** Used to match property names within property paths. */
23811 var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
23812 reIsPlainProp = /^\w*$/,
23813 reLeadingDot = /^\./,
23814 rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
23815
23816 /**
23817 * Used to match `RegExp`
23818 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
23819 */
23820 var reRegExpChar = /[\\^$.*+?()[\]{}|]/g,
23821 reHasRegExpChar = RegExp(reRegExpChar.source);
23822
23823 /** Used to match leading and trailing whitespace. */
23824 var reTrim = /^\s+|\s+$/g,
23825 reTrimStart = /^\s+/,
23826 reTrimEnd = /\s+$/;
23827
23828 /** Used to match wrap detail comments. */
23829 var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,
23830 reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/,
23831 reSplitDetails = /,? & /;
23832
23833 /** Used to match words composed of alphanumeric characters. */
23834 var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
23835
23836 /** Used to match backslashes in property paths. */
23837 var reEscapeChar = /\\(\\)?/g;
23838
23839 /**
23840 * Used to match
23841 * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components).
23842 */
23843 var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
23844
23845 /** Used to match `RegExp` flags from their coerced string values. */
23846 var reFlags = /\w*$/;
23847
23848 /** Used to detect bad signed hexadecimal string values. */
23849 var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
23850
23851 /** Used to detect binary string values. */
23852 var reIsBinary = /^0b[01]+$/i;
23853
23854 /** Used to detect host constructors (Safari). */
23855 var reIsHostCtor = /^\[object .+?Constructor\]$/;
23856
23857 /** Used to detect octal string values. */
23858 var reIsOctal = /^0o[0-7]+$/i;
23859
23860 /** Used to detect unsigned integer values. */
23861 var reIsUint = /^(?:0|[1-9]\d*)$/;
23862
23863 /** Used to match Latin Unicode letters (excluding mathematical operators). */
23864 var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
23865
23866 /** Used to ensure capturing order of template delimiters. */
23867 var reNoMatch = /($^)/;
23868
23869 /** Used to match unescaped characters in compiled string literals. */
23870 var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
23871
23872 /** Used to compose unicode character classes. */
23873 var rsAstralRange = '\\ud800-\\udfff',
23874 rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23',
23875 rsComboSymbolsRange = '\\u20d0-\\u20f0',
23876 rsDingbatRange = '\\u2700-\\u27bf',
23877 rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
23878 rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
23879 rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
23880 rsPunctuationRange = '\\u2000-\\u206f',
23881 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',
23882 rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
23883 rsVarRange = '\\ufe0e\\ufe0f',
23884 rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
23885
23886 /** Used to compose unicode capture groups. */
23887 var rsApos = "['\u2019]",
23888 rsAstral = '[' + rsAstralRange + ']',
23889 rsBreak = '[' + rsBreakRange + ']',
23890 rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']',
23891 rsDigits = '\\d+',
23892 rsDingbat = '[' + rsDingbatRange + ']',
23893 rsLower = '[' + rsLowerRange + ']',
23894 rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
23895 rsFitz = '\\ud83c[\\udffb-\\udfff]',
23896 rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
23897 rsNonAstral = '[^' + rsAstralRange + ']',
23898 rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
23899 rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
23900 rsUpper = '[' + rsUpperRange + ']',
23901 rsZWJ = '\\u200d';
23902
23903 /** Used to compose unicode regexes. */
23904 var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')',
23905 rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')',
23906 rsOptLowerContr = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',
23907 rsOptUpperContr = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',
23908 reOptMod = rsModifier + '?',
23909 rsOptVar = '[' + rsVarRange + ']?',
23910 rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
23911 rsSeq = rsOptVar + reOptMod + rsOptJoin,
23912 rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,
23913 rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
23914
23915 /** Used to match apostrophes. */
23916 var reApos = RegExp(rsApos, 'g');
23917
23918 /**
23919 * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
23920 * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
23921 */
23922 var reComboMark = RegExp(rsCombo, 'g');
23923
23924 /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
23925 var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
23926
23927 /** Used to match complex or compound words. */
23928 var reUnicodeWord = RegExp([
23929 rsUpper + '?' + rsLower + '+' + rsOptLowerContr + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
23930 rsUpperMisc + '+' + rsOptUpperContr + '(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')',
23931 rsUpper + '?' + rsLowerMisc + '+' + rsOptLowerContr,
23932 rsUpper + '+' + rsOptUpperContr,
23933 rsDigits,
23934 rsEmoji
23935 ].join('|'), 'g');
23936
23937 /** 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/). */
23938 var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']');
23939
23940 /** Used to detect strings that need a more robust regexp to match words. */
23941 var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;
23942
23943 /** Used to assign default `context` object properties. */
23944 var contextProps = [
23945 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array',
23946 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object',
23947 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array',
23948 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap',
23949 '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout'
23950 ];
23951
23952 /** Used to make template sourceURLs easier to identify. */
23953 var templateCounter = -1;
23954
23955 /** Used to identify `toStringTag` values of typed arrays. */
23956 var typedArrayTags = {};
23957 typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
23958 typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
23959 typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
23960 typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
23961 typedArrayTags[uint32Tag] = true;
23962 typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
23963 typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
23964 typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
23965 typedArrayTags[errorTag] = typedArrayTags[funcTag] =
23966 typedArrayTags[mapTag] = typedArrayTags[numberTag] =
23967 typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
23968 typedArrayTags[setTag] = typedArrayTags[stringTag] =
23969 typedArrayTags[weakMapTag] = false;
23970
23971 /** Used to identify `toStringTag` values supported by `_.clone`. */
23972 var cloneableTags = {};
23973 cloneableTags[argsTag] = cloneableTags[arrayTag] =
23974 cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
23975 cloneableTags[boolTag] = cloneableTags[dateTag] =
23976 cloneableTags[float32Tag] = cloneableTags[float64Tag] =
23977 cloneableTags[int8Tag] = cloneableTags[int16Tag] =
23978 cloneableTags[int32Tag] = cloneableTags[mapTag] =
23979 cloneableTags[numberTag] = cloneableTags[objectTag] =
23980 cloneableTags[regexpTag] = cloneableTags[setTag] =
23981 cloneableTags[stringTag] = cloneableTags[symbolTag] =
23982 cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
23983 cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
23984 cloneableTags[errorTag] = cloneableTags[funcTag] =
23985 cloneableTags[weakMapTag] = false;
23986
23987 /** Used to map Latin Unicode letters to basic Latin letters. */
23988 var deburredLetters = {
23989 // Latin-1 Supplement block.
23990 '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
23991 '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
23992 '\xc7': 'C', '\xe7': 'c',
23993 '\xd0': 'D', '\xf0': 'd',
23994 '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
23995 '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
23996 '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
23997 '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
23998 '\xd1': 'N', '\xf1': 'n',
23999 '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
24000 '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
24001 '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
24002 '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
24003 '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
24004 '\xc6': 'Ae', '\xe6': 'ae',
24005 '\xde': 'Th', '\xfe': 'th',
24006 '\xdf': 'ss',
24007 // Latin Extended-A block.
24008 '\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
24009 '\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
24010 '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
24011 '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
24012 '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
24013 '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
24014 '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
24015 '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
24016 '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
24017 '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
24018 '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
24019 '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
24020 '\u0134': 'J', '\u0135': 'j',
24021 '\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
24022 '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
24023 '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
24024 '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
24025 '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
24026 '\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
24027 '\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
24028 '\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
24029 '\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
24030 '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
24031 '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
24032 '\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
24033 '\u0163': 't', '\u0165': 't', '\u0167': 't',
24034 '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
24035 '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
24036 '\u0174': 'W', '\u0175': 'w',
24037 '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
24038 '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
24039 '\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
24040 '\u0132': 'IJ', '\u0133': 'ij',
24041 '\u0152': 'Oe', '\u0153': 'oe',
24042 '\u0149': "'n", '\u017f': 's'
24043 };
24044
24045 /** Used to map characters to HTML entities. */
24046 var htmlEscapes = {
24047 '&': '&amp;',
24048 '<': '&lt;',
24049 '>': '&gt;',
24050 '"': '&quot;',
24051 "'": '&#39;'
24052 };
24053
24054 /** Used to map HTML entities to characters. */
24055 var htmlUnescapes = {
24056 '&amp;': '&',
24057 '&lt;': '<',
24058 '&gt;': '>',
24059 '&quot;': '"',
24060 '&#39;': "'"
24061 };
24062
24063 /** Used to escape characters for inclusion in compiled string literals. */
24064 var stringEscapes = {
24065 '\\': '\\',
24066 "'": "'",
24067 '\n': 'n',
24068 '\r': 'r',
24069 '\u2028': 'u2028',
24070 '\u2029': 'u2029'
24071 };
24072
24073 /** Built-in method references without a dependency on `root`. */
24074 var freeParseFloat = parseFloat,
24075 freeParseInt = parseInt;
24076
24077 /** Detect free variable `global` from Node.js. */
24078 var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
24079
24080 /** Detect free variable `self`. */
24081 var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
24082
24083 /** Used as a reference to the global object. */
24084 var root = freeGlobal || freeSelf || Function('return this')();
24085
24086 /** Detect free variable `exports`. */
24087 var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
24088
24089 /** Detect free variable `module`. */
24090 var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
24091
24092 /** Detect the popular CommonJS extension `module.exports`. */
24093 var moduleExports = freeModule && freeModule.exports === freeExports;
24094
24095 /** Detect free variable `process` from Node.js. */
24096 var freeProcess = moduleExports && freeGlobal.process;
24097
24098 /** Used to access faster Node.js helpers. */
24099 var nodeUtil = (function() {
24100 try {
24101 return freeProcess && freeProcess.binding('util');
24102 } catch (e) {}
24103 }());
24104
24105 /* Node.js helper references. */
24106 var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer,
24107 nodeIsDate = nodeUtil && nodeUtil.isDate,
24108 nodeIsMap = nodeUtil && nodeUtil.isMap,
24109 nodeIsRegExp = nodeUtil && nodeUtil.isRegExp,
24110 nodeIsSet = nodeUtil && nodeUtil.isSet,
24111 nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
24112
24113 /*--------------------------------------------------------------------------*/
24114
24115 /**
24116 * Adds the key-value `pair` to `map`.
24117 *
24118 * @private
24119 * @param {Object} map The map to modify.
24120 * @param {Array} pair The key-value pair to add.
24121 * @returns {Object} Returns `map`.
24122 */
24123 function addMapEntry(map, pair) {
24124 // Don't return `map.set` because it's not chainable in IE 11.
24125 map.set(pair[0], pair[1]);
24126 return map;
24127 }
24128
24129 /**
24130 * Adds `value` to `set`.
24131 *
24132 * @private
24133 * @param {Object} set The set to modify.
24134 * @param {*} value The value to add.
24135 * @returns {Object} Returns `set`.
24136 */
24137 function addSetEntry(set, value) {
24138 // Don't return `set.add` because it's not chainable in IE 11.
24139 set.add(value);
24140 return set;
24141 }
24142
24143 /**
24144 * A faster alternative to `Function#apply`, this function invokes `func`
24145 * with the `this` binding of `thisArg` and the arguments of `args`.
24146 *
24147 * @private
24148 * @param {Function} func The function to invoke.
24149 * @param {*} thisArg The `this` binding of `func`.
24150 * @param {Array} args The arguments to invoke `func` with.
24151 * @returns {*} Returns the result of `func`.
24152 */
24153 function apply(func, thisArg, args) {
24154 switch (args.length) {
24155 case 0: return func.call(thisArg);
24156 case 1: return func.call(thisArg, args[0]);
24157 case 2: return func.call(thisArg, args[0], args[1]);
24158 case 3: return func.call(thisArg, args[0], args[1], args[2]);
24159 }
24160 return func.apply(thisArg, args);
24161 }
24162
24163 /**
24164 * A specialized version of `baseAggregator` for arrays.
24165 *
24166 * @private
24167 * @param {Array} [array] The array to iterate over.
24168 * @param {Function} setter The function to set `accumulator` values.
24169 * @param {Function} iteratee The iteratee to transform keys.
24170 * @param {Object} accumulator The initial aggregated object.
24171 * @returns {Function} Returns `accumulator`.
24172 */
24173 function arrayAggregator(array, setter, iteratee, accumulator) {
24174 var index = -1,
24175 length = array ? array.length : 0;
24176
24177 while (++index < length) {
24178 var value = array[index];
24179 setter(accumulator, value, iteratee(value), array);
24180 }
24181 return accumulator;
24182 }
24183
24184 /**
24185 * A specialized version of `_.forEach` for arrays without support for
24186 * iteratee shorthands.
24187 *
24188 * @private
24189 * @param {Array} [array] The array to iterate over.
24190 * @param {Function} iteratee The function invoked per iteration.
24191 * @returns {Array} Returns `array`.
24192 */
24193 function arrayEach(array, iteratee) {
24194 var index = -1,
24195 length = array ? array.length : 0;
24196
24197 while (++index < length) {
24198 if (iteratee(array[index], index, array) === false) {
24199 break;
24200 }
24201 }
24202 return array;
24203 }
24204
24205 /**
24206 * A specialized version of `_.forEachRight` for arrays without support for
24207 * iteratee shorthands.
24208 *
24209 * @private
24210 * @param {Array} [array] The array to iterate over.
24211 * @param {Function} iteratee The function invoked per iteration.
24212 * @returns {Array} Returns `array`.
24213 */
24214 function arrayEachRight(array, iteratee) {
24215 var length = array ? array.length : 0;
24216
24217 while (length--) {
24218 if (iteratee(array[length], length, array) === false) {
24219 break;
24220 }
24221 }
24222 return array;
24223 }
24224
24225 /**
24226 * A specialized version of `_.every` for arrays without support for
24227 * iteratee shorthands.
24228 *
24229 * @private
24230 * @param {Array} [array] The array to iterate over.
24231 * @param {Function} predicate The function invoked per iteration.
24232 * @returns {boolean} Returns `true` if all elements pass the predicate check,
24233 * else `false`.
24234 */
24235 function arrayEvery(array, predicate) {
24236 var index = -1,
24237 length = array ? array.length : 0;
24238
24239 while (++index < length) {
24240 if (!predicate(array[index], index, array)) {
24241 return false;
24242 }
24243 }
24244 return true;
24245 }
24246
24247 /**
24248 * A specialized version of `_.filter` for arrays without support for
24249 * iteratee shorthands.
24250 *
24251 * @private
24252 * @param {Array} [array] The array to iterate over.
24253 * @param {Function} predicate The function invoked per iteration.
24254 * @returns {Array} Returns the new filtered array.
24255 */
24256 function arrayFilter(array, predicate) {
24257 var index = -1,
24258 length = array ? array.length : 0,
24259 resIndex = 0,
24260 result = [];
24261
24262 while (++index < length) {
24263 var value = array[index];
24264 if (predicate(value, index, array)) {
24265 result[resIndex++] = value;
24266 }
24267 }
24268 return result;
24269 }
24270
24271 /**
24272 * A specialized version of `_.includes` for arrays without support for
24273 * specifying an index to search from.
24274 *
24275 * @private
24276 * @param {Array} [array] The array to inspect.
24277 * @param {*} target The value to search for.
24278 * @returns {boolean} Returns `true` if `target` is found, else `false`.
24279 */
24280 function arrayIncludes(array, value) {
24281 var length = array ? array.length : 0;
24282 return !!length && baseIndexOf(array, value, 0) > -1;
24283 }
24284
24285 /**
24286 * This function is like `arrayIncludes` except that it accepts a comparator.
24287 *
24288 * @private
24289 * @param {Array} [array] The array to inspect.
24290 * @param {*} target The value to search for.
24291 * @param {Function} comparator The comparator invoked per element.
24292 * @returns {boolean} Returns `true` if `target` is found, else `false`.
24293 */
24294 function arrayIncludesWith(array, value, comparator) {
24295 var index = -1,
24296 length = array ? array.length : 0;
24297
24298 while (++index < length) {
24299 if (comparator(value, array[index])) {
24300 return true;
24301 }
24302 }
24303 return false;
24304 }
24305
24306 /**
24307 * A specialized version of `_.map` for arrays without support for iteratee
24308 * shorthands.
24309 *
24310 * @private
24311 * @param {Array} [array] The array to iterate over.
24312 * @param {Function} iteratee The function invoked per iteration.
24313 * @returns {Array} Returns the new mapped array.
24314 */
24315 function arrayMap(array, iteratee) {
24316 var index = -1,
24317 length = array ? array.length : 0,
24318 result = Array(length);
24319
24320 while (++index < length) {
24321 result[index] = iteratee(array[index], index, array);
24322 }
24323 return result;
24324 }
24325
24326 /**
24327 * Appends the elements of `values` to `array`.
24328 *
24329 * @private
24330 * @param {Array} array The array to modify.
24331 * @param {Array} values The values to append.
24332 * @returns {Array} Returns `array`.
24333 */
24334 function arrayPush(array, values) {
24335 var index = -1,
24336 length = values.length,
24337 offset = array.length;
24338
24339 while (++index < length) {
24340 array[offset + index] = values[index];
24341 }
24342 return array;
24343 }
24344
24345 /**
24346 * A specialized version of `_.reduce` for arrays without support for
24347 * iteratee shorthands.
24348 *
24349 * @private
24350 * @param {Array} [array] The array to iterate over.
24351 * @param {Function} iteratee The function invoked per iteration.
24352 * @param {*} [accumulator] The initial value.
24353 * @param {boolean} [initAccum] Specify using the first element of `array` as
24354 * the initial value.
24355 * @returns {*} Returns the accumulated value.
24356 */
24357 function arrayReduce(array, iteratee, accumulator, initAccum) {
24358 var index = -1,
24359 length = array ? array.length : 0;
24360
24361 if (initAccum && length) {
24362 accumulator = array[++index];
24363 }
24364 while (++index < length) {
24365 accumulator = iteratee(accumulator, array[index], index, array);
24366 }
24367 return accumulator;
24368 }
24369
24370 /**
24371 * A specialized version of `_.reduceRight` for arrays without support for
24372 * iteratee shorthands.
24373 *
24374 * @private
24375 * @param {Array} [array] The array to iterate over.
24376 * @param {Function} iteratee The function invoked per iteration.
24377 * @param {*} [accumulator] The initial value.
24378 * @param {boolean} [initAccum] Specify using the last element of `array` as
24379 * the initial value.
24380 * @returns {*} Returns the accumulated value.
24381 */
24382 function arrayReduceRight(array, iteratee, accumulator, initAccum) {
24383 var length = array ? array.length : 0;
24384 if (initAccum && length) {
24385 accumulator = array[--length];
24386 }
24387 while (length--) {
24388 accumulator = iteratee(accumulator, array[length], length, array);
24389 }
24390 return accumulator;
24391 }
24392
24393 /**
24394 * A specialized version of `_.some` for arrays without support for iteratee
24395 * shorthands.
24396 *
24397 * @private
24398 * @param {Array} [array] The array to iterate over.
24399 * @param {Function} predicate The function invoked per iteration.
24400 * @returns {boolean} Returns `true` if any element passes the predicate check,
24401 * else `false`.
24402 */
24403 function arraySome(array, predicate) {
24404 var index = -1,
24405 length = array ? array.length : 0;
24406
24407 while (++index < length) {
24408 if (predicate(array[index], index, array)) {
24409 return true;
24410 }
24411 }
24412 return false;
24413 }
24414
24415 /**
24416 * Gets the size of an ASCII `string`.
24417 *
24418 * @private
24419 * @param {string} string The string inspect.
24420 * @returns {number} Returns the string size.
24421 */
24422 var asciiSize = baseProperty('length');
24423
24424 /**
24425 * Converts an ASCII `string` to an array.
24426 *
24427 * @private
24428 * @param {string} string The string to convert.
24429 * @returns {Array} Returns the converted array.
24430 */
24431 function asciiToArray(string) {
24432 return string.split('');
24433 }
24434
24435 /**
24436 * Splits an ASCII `string` into an array of its words.
24437 *
24438 * @private
24439 * @param {string} The string to inspect.
24440 * @returns {Array} Returns the words of `string`.
24441 */
24442 function asciiWords(string) {
24443 return string.match(reAsciiWord) || [];
24444 }
24445
24446 /**
24447 * The base implementation of methods like `_.findKey` and `_.findLastKey`,
24448 * without support for iteratee shorthands, which iterates over `collection`
24449 * using `eachFunc`.
24450 *
24451 * @private
24452 * @param {Array|Object} collection The collection to inspect.
24453 * @param {Function} predicate The function invoked per iteration.
24454 * @param {Function} eachFunc The function to iterate over `collection`.
24455 * @returns {*} Returns the found element or its key, else `undefined`.
24456 */
24457 function baseFindKey(collection, predicate, eachFunc) {
24458 var result;
24459 eachFunc(collection, function(value, key, collection) {
24460 if (predicate(value, key, collection)) {
24461 result = key;
24462 return false;
24463 }
24464 });
24465 return result;
24466 }
24467
24468 /**
24469 * The base implementation of `_.findIndex` and `_.findLastIndex` without
24470 * support for iteratee shorthands.
24471 *
24472 * @private
24473 * @param {Array} array The array to inspect.
24474 * @param {Function} predicate The function invoked per iteration.
24475 * @param {number} fromIndex The index to search from.
24476 * @param {boolean} [fromRight] Specify iterating from right to left.
24477 * @returns {number} Returns the index of the matched value, else `-1`.
24478 */
24479 function baseFindIndex(array, predicate, fromIndex, fromRight) {
24480 var length = array.length,
24481 index = fromIndex + (fromRight ? 1 : -1);
24482
24483 while ((fromRight ? index-- : ++index < length)) {
24484 if (predicate(array[index], index, array)) {
24485 return index;
24486 }
24487 }
24488 return -1;
24489 }
24490
24491 /**
24492 * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
24493 *
24494 * @private
24495 * @param {Array} array The array to inspect.
24496 * @param {*} value The value to search for.
24497 * @param {number} fromIndex The index to search from.
24498 * @returns {number} Returns the index of the matched value, else `-1`.
24499 */
24500 function baseIndexOf(array, value, fromIndex) {
24501 return value === value
24502 ? strictIndexOf(array, value, fromIndex)
24503 : baseFindIndex(array, baseIsNaN, fromIndex);
24504 }
24505
24506 /**
24507 * This function is like `baseIndexOf` except that it accepts a comparator.
24508 *
24509 * @private
24510 * @param {Array} array The array to inspect.
24511 * @param {*} value The value to search for.
24512 * @param {number} fromIndex The index to search from.
24513 * @param {Function} comparator The comparator invoked per element.
24514 * @returns {number} Returns the index of the matched value, else `-1`.
24515 */
24516 function baseIndexOfWith(array, value, fromIndex, comparator) {
24517 var index = fromIndex - 1,
24518 length = array.length;
24519
24520 while (++index < length) {
24521 if (comparator(array[index], value)) {
24522 return index;
24523 }
24524 }
24525 return -1;
24526 }
24527
24528 /**
24529 * The base implementation of `_.isNaN` without support for number objects.
24530 *
24531 * @private
24532 * @param {*} value The value to check.
24533 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
24534 */
24535 function baseIsNaN(value) {
24536 return value !== value;
24537 }
24538
24539 /**
24540 * The base implementation of `_.mean` and `_.meanBy` without support for
24541 * iteratee shorthands.
24542 *
24543 * @private
24544 * @param {Array} array The array to iterate over.
24545 * @param {Function} iteratee The function invoked per iteration.
24546 * @returns {number} Returns the mean.
24547 */
24548 function baseMean(array, iteratee) {
24549 var length = array ? array.length : 0;
24550 return length ? (baseSum(array, iteratee) / length) : NAN;
24551 }
24552
24553 /**
24554 * The base implementation of `_.property` without support for deep paths.
24555 *
24556 * @private
24557 * @param {string} key The key of the property to get.
24558 * @returns {Function} Returns the new accessor function.
24559 */
24560 function baseProperty(key) {
24561 return function(object) {
24562 return object == null ? undefined : object[key];
24563 };
24564 }
24565
24566 /**
24567 * The base implementation of `_.propertyOf` without support for deep paths.
24568 *
24569 * @private
24570 * @param {Object} object The object to query.
24571 * @returns {Function} Returns the new accessor function.
24572 */
24573 function basePropertyOf(object) {
24574 return function(key) {
24575 return object == null ? undefined : object[key];
24576 };
24577 }
24578
24579 /**
24580 * The base implementation of `_.reduce` and `_.reduceRight`, without support
24581 * for iteratee shorthands, which iterates over `collection` using `eachFunc`.
24582 *
24583 * @private
24584 * @param {Array|Object} collection The collection to iterate over.
24585 * @param {Function} iteratee The function invoked per iteration.
24586 * @param {*} accumulator The initial value.
24587 * @param {boolean} initAccum Specify using the first or last element of
24588 * `collection` as the initial value.
24589 * @param {Function} eachFunc The function to iterate over `collection`.
24590 * @returns {*} Returns the accumulated value.
24591 */
24592 function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
24593 eachFunc(collection, function(value, index, collection) {
24594 accumulator = initAccum
24595 ? (initAccum = false, value)
24596 : iteratee(accumulator, value, index, collection);
24597 });
24598 return accumulator;
24599 }
24600
24601 /**
24602 * The base implementation of `_.sortBy` which uses `comparer` to define the
24603 * sort order of `array` and replaces criteria objects with their corresponding
24604 * values.
24605 *
24606 * @private
24607 * @param {Array} array The array to sort.
24608 * @param {Function} comparer The function to define sort order.
24609 * @returns {Array} Returns `array`.
24610 */
24611 function baseSortBy(array, comparer) {
24612 var length = array.length;
24613
24614 array.sort(comparer);
24615 while (length--) {
24616 array[length] = array[length].value;
24617 }
24618 return array;
24619 }
24620
24621 /**
24622 * The base implementation of `_.sum` and `_.sumBy` without support for
24623 * iteratee shorthands.
24624 *
24625 * @private
24626 * @param {Array} array The array to iterate over.
24627 * @param {Function} iteratee The function invoked per iteration.
24628 * @returns {number} Returns the sum.
24629 */
24630 function baseSum(array, iteratee) {
24631 var result,
24632 index = -1,
24633 length = array.length;
24634
24635 while (++index < length) {
24636 var current = iteratee(array[index]);
24637 if (current !== undefined) {
24638 result = result === undefined ? current : (result + current);
24639 }
24640 }
24641 return result;
24642 }
24643
24644 /**
24645 * The base implementation of `_.times` without support for iteratee shorthands
24646 * or max array length checks.
24647 *
24648 * @private
24649 * @param {number} n The number of times to invoke `iteratee`.
24650 * @param {Function} iteratee The function invoked per iteration.
24651 * @returns {Array} Returns the array of results.
24652 */
24653 function baseTimes(n, iteratee) {
24654 var index = -1,
24655 result = Array(n);
24656
24657 while (++index < n) {
24658 result[index] = iteratee(index);
24659 }
24660 return result;
24661 }
24662
24663 /**
24664 * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array
24665 * of key-value pairs for `object` corresponding to the property names of `props`.
24666 *
24667 * @private
24668 * @param {Object} object The object to query.
24669 * @param {Array} props The property names to get values for.
24670 * @returns {Object} Returns the key-value pairs.
24671 */
24672 function baseToPairs(object, props) {
24673 return arrayMap(props, function(key) {
24674 return [key, object[key]];
24675 });
24676 }
24677
24678 /**
24679 * The base implementation of `_.unary` without support for storing metadata.
24680 *
24681 * @private
24682 * @param {Function} func The function to cap arguments for.
24683 * @returns {Function} Returns the new capped function.
24684 */
24685 function baseUnary(func) {
24686 return function(value) {
24687 return func(value);
24688 };
24689 }
24690
24691 /**
24692 * The base implementation of `_.values` and `_.valuesIn` which creates an
24693 * array of `object` property values corresponding to the property names
24694 * of `props`.
24695 *
24696 * @private
24697 * @param {Object} object The object to query.
24698 * @param {Array} props The property names to get values for.
24699 * @returns {Object} Returns the array of property values.
24700 */
24701 function baseValues(object, props) {
24702 return arrayMap(props, function(key) {
24703 return object[key];
24704 });
24705 }
24706
24707 /**
24708 * Checks if a `cache` value for `key` exists.
24709 *
24710 * @private
24711 * @param {Object} cache The cache to query.
24712 * @param {string} key The key of the entry to check.
24713 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
24714 */
24715 function cacheHas(cache, key) {
24716 return cache.has(key);
24717 }
24718
24719 /**
24720 * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
24721 * that is not found in the character symbols.
24722 *
24723 * @private
24724 * @param {Array} strSymbols The string symbols to inspect.
24725 * @param {Array} chrSymbols The character symbols to find.
24726 * @returns {number} Returns the index of the first unmatched string symbol.
24727 */
24728 function charsStartIndex(strSymbols, chrSymbols) {
24729 var index = -1,
24730 length = strSymbols.length;
24731
24732 while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
24733 return index;
24734 }
24735
24736 /**
24737 * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
24738 * that is not found in the character symbols.
24739 *
24740 * @private
24741 * @param {Array} strSymbols The string symbols to inspect.
24742 * @param {Array} chrSymbols The character symbols to find.
24743 * @returns {number} Returns the index of the last unmatched string symbol.
24744 */
24745 function charsEndIndex(strSymbols, chrSymbols) {
24746 var index = strSymbols.length;
24747
24748 while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
24749 return index;
24750 }
24751
24752 /**
24753 * Gets the number of `placeholder` occurrences in `array`.
24754 *
24755 * @private
24756 * @param {Array} array The array to inspect.
24757 * @param {*} placeholder The placeholder to search for.
24758 * @returns {number} Returns the placeholder count.
24759 */
24760 function countHolders(array, placeholder) {
24761 var length = array.length,
24762 result = 0;
24763
24764 while (length--) {
24765 if (array[length] === placeholder) {
24766 ++result;
24767 }
24768 }
24769 return result;
24770 }
24771
24772 /**
24773 * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
24774 * letters to basic Latin letters.
24775 *
24776 * @private
24777 * @param {string} letter The matched letter to deburr.
24778 * @returns {string} Returns the deburred letter.
24779 */
24780 var deburrLetter = basePropertyOf(deburredLetters);
24781
24782 /**
24783 * Used by `_.escape` to convert characters to HTML entities.
24784 *
24785 * @private
24786 * @param {string} chr The matched character to escape.
24787 * @returns {string} Returns the escaped character.
24788 */
24789 var escapeHtmlChar = basePropertyOf(htmlEscapes);
24790
24791 /**
24792 * Used by `_.template` to escape characters for inclusion in compiled string literals.
24793 *
24794 * @private
24795 * @param {string} chr The matched character to escape.
24796 * @returns {string} Returns the escaped character.
24797 */
24798 function escapeStringChar(chr) {
24799 return '\\' + stringEscapes[chr];
24800 }
24801
24802 /**
24803 * Gets the value at `key` of `object`.
24804 *
24805 * @private
24806 * @param {Object} [object] The object to query.
24807 * @param {string} key The key of the property to get.
24808 * @returns {*} Returns the property value.
24809 */
24810 function getValue(object, key) {
24811 return object == null ? undefined : object[key];
24812 }
24813
24814 /**
24815 * Checks if `string` contains Unicode symbols.
24816 *
24817 * @private
24818 * @param {string} string The string to inspect.
24819 * @returns {boolean} Returns `true` if a symbol is found, else `false`.
24820 */
24821 function hasUnicode(string) {
24822 return reHasUnicode.test(string);
24823 }
24824
24825 /**
24826 * Checks if `string` contains a word composed of Unicode symbols.
24827 *
24828 * @private
24829 * @param {string} string The string to inspect.
24830 * @returns {boolean} Returns `true` if a word is found, else `false`.
24831 */
24832 function hasUnicodeWord(string) {
24833 return reHasUnicodeWord.test(string);
24834 }
24835
24836 /**
24837 * Converts `iterator` to an array.
24838 *
24839 * @private
24840 * @param {Object} iterator The iterator to convert.
24841 * @returns {Array} Returns the converted array.
24842 */
24843 function iteratorToArray(iterator) {
24844 var data,
24845 result = [];
24846
24847 while (!(data = iterator.next()).done) {
24848 result.push(data.value);
24849 }
24850 return result;
24851 }
24852
24853 /**
24854 * Converts `map` to its key-value pairs.
24855 *
24856 * @private
24857 * @param {Object} map The map to convert.
24858 * @returns {Array} Returns the key-value pairs.
24859 */
24860 function mapToArray(map) {
24861 var index = -1,
24862 result = Array(map.size);
24863
24864 map.forEach(function(value, key) {
24865 result[++index] = [key, value];
24866 });
24867 return result;
24868 }
24869
24870 /**
24871 * Creates a unary function that invokes `func` with its argument transformed.
24872 *
24873 * @private
24874 * @param {Function} func The function to wrap.
24875 * @param {Function} transform The argument transform.
24876 * @returns {Function} Returns the new function.
24877 */
24878 function overArg(func, transform) {
24879 return function(arg) {
24880 return func(transform(arg));
24881 };
24882 }
24883
24884 /**
24885 * Replaces all `placeholder` elements in `array` with an internal placeholder
24886 * and returns an array of their indexes.
24887 *
24888 * @private
24889 * @param {Array} array The array to modify.
24890 * @param {*} placeholder The placeholder to replace.
24891 * @returns {Array} Returns the new array of placeholder indexes.
24892 */
24893 function replaceHolders(array, placeholder) {
24894 var index = -1,
24895 length = array.length,
24896 resIndex = 0,
24897 result = [];
24898
24899 while (++index < length) {
24900 var value = array[index];
24901 if (value === placeholder || value === PLACEHOLDER) {
24902 array[index] = PLACEHOLDER;
24903 result[resIndex++] = index;
24904 }
24905 }
24906 return result;
24907 }
24908
24909 /**
24910 * Converts `set` to an array of its values.
24911 *
24912 * @private
24913 * @param {Object} set The set to convert.
24914 * @returns {Array} Returns the values.
24915 */
24916 function setToArray(set) {
24917 var index = -1,
24918 result = Array(set.size);
24919
24920 set.forEach(function(value) {
24921 result[++index] = value;
24922 });
24923 return result;
24924 }
24925
24926 /**
24927 * Converts `set` to its value-value pairs.
24928 *
24929 * @private
24930 * @param {Object} set The set to convert.
24931 * @returns {Array} Returns the value-value pairs.
24932 */
24933 function setToPairs(set) {
24934 var index = -1,
24935 result = Array(set.size);
24936
24937 set.forEach(function(value) {
24938 result[++index] = [value, value];
24939 });
24940 return result;
24941 }
24942
24943 /**
24944 * A specialized version of `_.indexOf` which performs strict equality
24945 * comparisons of values, i.e. `===`.
24946 *
24947 * @private
24948 * @param {Array} array The array to inspect.
24949 * @param {*} value The value to search for.
24950 * @param {number} fromIndex The index to search from.
24951 * @returns {number} Returns the index of the matched value, else `-1`.
24952 */
24953 function strictIndexOf(array, value, fromIndex) {
24954 var index = fromIndex - 1,
24955 length = array.length;
24956
24957 while (++index < length) {
24958 if (array[index] === value) {
24959 return index;
24960 }
24961 }
24962 return -1;
24963 }
24964
24965 /**
24966 * A specialized version of `_.lastIndexOf` which performs strict equality
24967 * comparisons of values, i.e. `===`.
24968 *
24969 * @private
24970 * @param {Array} array The array to inspect.
24971 * @param {*} value The value to search for.
24972 * @param {number} fromIndex The index to search from.
24973 * @returns {number} Returns the index of the matched value, else `-1`.
24974 */
24975 function strictLastIndexOf(array, value, fromIndex) {
24976 var index = fromIndex + 1;
24977 while (index--) {
24978 if (array[index] === value) {
24979 return index;
24980 }
24981 }
24982 return index;
24983 }
24984
24985 /**
24986 * Gets the number of symbols in `string`.
24987 *
24988 * @private
24989 * @param {string} string The string to inspect.
24990 * @returns {number} Returns the string size.
24991 */
24992 function stringSize(string) {
24993 return hasUnicode(string)
24994 ? unicodeSize(string)
24995 : asciiSize(string);
24996 }
24997
24998 /**
24999 * Converts `string` to an array.
25000 *
25001 * @private
25002 * @param {string} string The string to convert.
25003 * @returns {Array} Returns the converted array.
25004 */
25005 function stringToArray(string) {
25006 return hasUnicode(string)
25007 ? unicodeToArray(string)
25008 : asciiToArray(string);
25009 }
25010
25011 /**
25012 * Used by `_.unescape` to convert HTML entities to characters.
25013 *
25014 * @private
25015 * @param {string} chr The matched character to unescape.
25016 * @returns {string} Returns the unescaped character.
25017 */
25018 var unescapeHtmlChar = basePropertyOf(htmlUnescapes);
25019
25020 /**
25021 * Gets the size of a Unicode `string`.
25022 *
25023 * @private
25024 * @param {string} string The string inspect.
25025 * @returns {number} Returns the string size.
25026 */
25027 function unicodeSize(string) {
25028 var result = reUnicode.lastIndex = 0;
25029 while (reUnicode.test(string)) {
25030 ++result;
25031 }
25032 return result;
25033 }
25034
25035 /**
25036 * Converts a Unicode `string` to an array.
25037 *
25038 * @private
25039 * @param {string} string The string to convert.
25040 * @returns {Array} Returns the converted array.
25041 */
25042 function unicodeToArray(string) {
25043 return string.match(reUnicode) || [];
25044 }
25045
25046 /**
25047 * Splits a Unicode `string` into an array of its words.
25048 *
25049 * @private
25050 * @param {string} The string to inspect.
25051 * @returns {Array} Returns the words of `string`.
25052 */
25053 function unicodeWords(string) {
25054 return string.match(reUnicodeWord) || [];
25055 }
25056
25057 /*--------------------------------------------------------------------------*/
25058
25059 /**
25060 * Create a new pristine `lodash` function using the `context` object.
25061 *
25062 * @static
25063 * @memberOf _
25064 * @since 1.1.0
25065 * @category Util
25066 * @param {Object} [context=root] The context object.
25067 * @returns {Function} Returns a new `lodash` function.
25068 * @example
25069 *
25070 * _.mixin({ 'foo': _.constant('foo') });
25071 *
25072 * var lodash = _.runInContext();
25073 * lodash.mixin({ 'bar': lodash.constant('bar') });
25074 *
25075 * _.isFunction(_.foo);
25076 * // => true
25077 * _.isFunction(_.bar);
25078 * // => false
25079 *
25080 * lodash.isFunction(lodash.foo);
25081 * // => false
25082 * lodash.isFunction(lodash.bar);
25083 * // => true
25084 *
25085 * // Create a suped-up `defer` in Node.js.
25086 * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
25087 */
25088 var runInContext = (function runInContext(context) {
25089 context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root;
25090
25091 /** Built-in constructor references. */
25092 var Array = context.Array,
25093 Date = context.Date,
25094 Error = context.Error,
25095 Function = context.Function,
25096 Math = context.Math,
25097 Object = context.Object,
25098 RegExp = context.RegExp,
25099 String = context.String,
25100 TypeError = context.TypeError;
25101
25102 /** Used for built-in method references. */
25103 var arrayProto = Array.prototype,
25104 funcProto = Function.prototype,
25105 objectProto = Object.prototype;
25106
25107 /** Used to detect overreaching core-js shims. */
25108 var coreJsData = context['__core-js_shared__'];
25109
25110 /** Used to detect methods masquerading as native. */
25111 var maskSrcKey = (function() {
25112 var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
25113 return uid ? ('Symbol(src)_1.' + uid) : '';
25114 }());
25115
25116 /** Used to resolve the decompiled source of functions. */
25117 var funcToString = funcProto.toString;
25118
25119 /** Used to check objects for own properties. */
25120 var hasOwnProperty = objectProto.hasOwnProperty;
25121
25122 /** Used to generate unique IDs. */
25123 var idCounter = 0;
25124
25125 /** Used to infer the `Object` constructor. */
25126 var objectCtorString = funcToString.call(Object);
25127
25128 /**
25129 * Used to resolve the
25130 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
25131 * of values.
25132 */
25133 var objectToString = objectProto.toString;
25134
25135 /** Used to restore the original `_` reference in `_.noConflict`. */
25136 var oldDash = root._;
25137
25138 /** Used to detect if a method is native. */
25139 var reIsNative = RegExp('^' +
25140 funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
25141 .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
25142 );
25143
25144 /** Built-in value references. */
25145 var Buffer = moduleExports ? context.Buffer : undefined,
25146 Symbol = context.Symbol,
25147 Uint8Array = context.Uint8Array,
25148 allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined,
25149 getPrototype = overArg(Object.getPrototypeOf, Object),
25150 iteratorSymbol = Symbol ? Symbol.iterator : undefined,
25151 objectCreate = Object.create,
25152 propertyIsEnumerable = objectProto.propertyIsEnumerable,
25153 splice = arrayProto.splice,
25154 spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;
25155
25156 var defineProperty = (function() {
25157 try {
25158 var func = getNative(Object, 'defineProperty');
25159 func({}, '', {});
25160 return func;
25161 } catch (e) {}
25162 }());
25163
25164 /** Mocked built-ins. */
25165 var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout,
25166 ctxNow = Date && Date.now !== root.Date.now && Date.now,
25167 ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout;
25168
25169 /* Built-in method references for those with the same name as other `lodash` methods. */
25170 var nativeCeil = Math.ceil,
25171 nativeFloor = Math.floor,
25172 nativeGetSymbols = Object.getOwnPropertySymbols,
25173 nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
25174 nativeIsFinite = context.isFinite,
25175 nativeJoin = arrayProto.join,
25176 nativeKeys = overArg(Object.keys, Object),
25177 nativeMax = Math.max,
25178 nativeMin = Math.min,
25179 nativeNow = Date.now,
25180 nativeParseInt = context.parseInt,
25181 nativeRandom = Math.random,
25182 nativeReverse = arrayProto.reverse;
25183
25184 /* Built-in method references that are verified to be native. */
25185 var DataView = getNative(context, 'DataView'),
25186 Map = getNative(context, 'Map'),
25187 Promise = getNative(context, 'Promise'),
25188 Set = getNative(context, 'Set'),
25189 WeakMap = getNative(context, 'WeakMap'),
25190 nativeCreate = getNative(Object, 'create');
25191
25192 /** Used to store function metadata. */
25193 var metaMap = WeakMap && new WeakMap;
25194
25195 /** Used to lookup unminified function names. */
25196 var realNames = {};
25197
25198 /** Used to detect maps, sets, and weakmaps. */
25199 var dataViewCtorString = toSource(DataView),
25200 mapCtorString = toSource(Map),
25201 promiseCtorString = toSource(Promise),
25202 setCtorString = toSource(Set),
25203 weakMapCtorString = toSource(WeakMap);
25204
25205 /** Used to convert symbols to primitives and strings. */
25206 var symbolProto = Symbol ? Symbol.prototype : undefined,
25207 symbolValueOf = symbolProto ? symbolProto.valueOf : undefined,
25208 symbolToString = symbolProto ? symbolProto.toString : undefined;
25209
25210 /*------------------------------------------------------------------------*/
25211
25212 /**
25213 * Creates a `lodash` object which wraps `value` to enable implicit method
25214 * chain sequences. Methods that operate on and return arrays, collections,
25215 * and functions can be chained together. Methods that retrieve a single value
25216 * or may return a primitive value will automatically end the chain sequence
25217 * and return the unwrapped value. Otherwise, the value must be unwrapped
25218 * with `_#value`.
25219 *
25220 * Explicit chain sequences, which must be unwrapped with `_#value`, may be
25221 * enabled using `_.chain`.
25222 *
25223 * The execution of chained methods is lazy, that is, it's deferred until
25224 * `_#value` is implicitly or explicitly called.
25225 *
25226 * Lazy evaluation allows several methods to support shortcut fusion.
25227 * Shortcut fusion is an optimization to merge iteratee calls; this avoids
25228 * the creation of intermediate arrays and can greatly reduce the number of
25229 * iteratee executions. Sections of a chain sequence qualify for shortcut
25230 * fusion if the section is applied to an array of at least `200` elements
25231 * and any iteratees accept only one argument. The heuristic for whether a
25232 * section qualifies for shortcut fusion is subject to change.
25233 *
25234 * Chaining is supported in custom builds as long as the `_#value` method is
25235 * directly or indirectly included in the build.
25236 *
25237 * In addition to lodash methods, wrappers have `Array` and `String` methods.
25238 *
25239 * The wrapper `Array` methods are:
25240 * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
25241 *
25242 * The wrapper `String` methods are:
25243 * `replace` and `split`
25244 *
25245 * The wrapper methods that support shortcut fusion are:
25246 * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
25247 * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
25248 * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
25249 *
25250 * The chainable wrapper methods are:
25251 * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
25252 * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
25253 * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
25254 * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
25255 * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
25256 * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
25257 * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
25258 * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
25259 * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
25260 * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
25261 * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
25262 * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
25263 * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
25264 * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
25265 * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
25266 * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
25267 * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
25268 * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
25269 * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
25270 * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
25271 * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
25272 * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
25273 * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
25274 * `zipObject`, `zipObjectDeep`, and `zipWith`
25275 *
25276 * The wrapper methods that are **not** chainable by default are:
25277 * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
25278 * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
25279 * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
25280 * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
25281 * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
25282 * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
25283 * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
25284 * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
25285 * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
25286 * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
25287 * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
25288 * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
25289 * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
25290 * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
25291 * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
25292 * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
25293 * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
25294 * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
25295 * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
25296 * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
25297 * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
25298 * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
25299 * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
25300 * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
25301 * `upperFirst`, `value`, and `words`
25302 *
25303 * @name _
25304 * @constructor
25305 * @category Seq
25306 * @param {*} value The value to wrap in a `lodash` instance.
25307 * @returns {Object} Returns the new `lodash` wrapper instance.
25308 * @example
25309 *
25310 * function square(n) {
25311 * return n * n;
25312 * }
25313 *
25314 * var wrapped = _([1, 2, 3]);
25315 *
25316 * // Returns an unwrapped value.
25317 * wrapped.reduce(_.add);
25318 * // => 6
25319 *
25320 * // Returns a wrapped value.
25321 * var squares = wrapped.map(square);
25322 *
25323 * _.isArray(squares);
25324 * // => false
25325 *
25326 * _.isArray(squares.value());
25327 * // => true
25328 */
25329 function lodash(value) {
25330 if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
25331 if (value instanceof LodashWrapper) {
25332 return value;
25333 }
25334 if (hasOwnProperty.call(value, '__wrapped__')) {
25335 return wrapperClone(value);
25336 }
25337 }
25338 return new LodashWrapper(value);
25339 }
25340
25341 /**
25342 * The base implementation of `_.create` without support for assigning
25343 * properties to the created object.
25344 *
25345 * @private
25346 * @param {Object} proto The object to inherit from.
25347 * @returns {Object} Returns the new object.
25348 */
25349 var baseCreate = (function() {
25350 function object() {}
25351 return function(proto) {
25352 if (!isObject(proto)) {
25353 return {};
25354 }
25355 if (objectCreate) {
25356 return objectCreate(proto);
25357 }
25358 object.prototype = proto;
25359 var result = new object;
25360 object.prototype = undefined;
25361 return result;
25362 };
25363 }());
25364
25365 /**
25366 * The function whose prototype chain sequence wrappers inherit from.
25367 *
25368 * @private
25369 */
25370 function baseLodash() {
25371 // No operation performed.
25372 }
25373
25374 /**
25375 * The base constructor for creating `lodash` wrapper objects.
25376 *
25377 * @private
25378 * @param {*} value The value to wrap.
25379 * @param {boolean} [chainAll] Enable explicit method chain sequences.
25380 */
25381 function LodashWrapper(value, chainAll) {
25382 this.__wrapped__ = value;
25383 this.__actions__ = [];
25384 this.__chain__ = !!chainAll;
25385 this.__index__ = 0;
25386 this.__values__ = undefined;
25387 }
25388
25389 /**
25390 * By default, the template delimiters used by lodash are like those in
25391 * embedded Ruby (ERB). Change the following template settings to use
25392 * alternative delimiters.
25393 *
25394 * @static
25395 * @memberOf _
25396 * @type {Object}
25397 */
25398 lodash.templateSettings = {
25399
25400 /**
25401 * Used to detect `data` property values to be HTML-escaped.
25402 *
25403 * @memberOf _.templateSettings
25404 * @type {RegExp}
25405 */
25406 'escape': reEscape,
25407
25408 /**
25409 * Used to detect code to be evaluated.
25410 *
25411 * @memberOf _.templateSettings
25412 * @type {RegExp}
25413 */
25414 'evaluate': reEvaluate,
25415
25416 /**
25417 * Used to detect `data` property values to inject.
25418 *
25419 * @memberOf _.templateSettings
25420 * @type {RegExp}
25421 */
25422 'interpolate': reInterpolate,
25423
25424 /**
25425 * Used to reference the data object in the template text.
25426 *
25427 * @memberOf _.templateSettings
25428 * @type {string}
25429 */
25430 'variable': '',
25431
25432 /**
25433 * Used to import variables into the compiled template.
25434 *
25435 * @memberOf _.templateSettings
25436 * @type {Object}
25437 */
25438 'imports': {
25439
25440 /**
25441 * A reference to the `lodash` function.
25442 *
25443 * @memberOf _.templateSettings.imports
25444 * @type {Function}
25445 */
25446 '_': lodash
25447 }
25448 };
25449
25450 // Ensure wrappers are instances of `baseLodash`.
25451 lodash.prototype = baseLodash.prototype;
25452 lodash.prototype.constructor = lodash;
25453
25454 LodashWrapper.prototype = baseCreate(baseLodash.prototype);
25455 LodashWrapper.prototype.constructor = LodashWrapper;
25456
25457 /*------------------------------------------------------------------------*/
25458
25459 /**
25460 * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
25461 *
25462 * @private
25463 * @constructor
25464 * @param {*} value The value to wrap.
25465 */
25466 function LazyWrapper(value) {
25467 this.__wrapped__ = value;
25468 this.__actions__ = [];
25469 this.__dir__ = 1;
25470 this.__filtered__ = false;
25471 this.__iteratees__ = [];
25472 this.__takeCount__ = MAX_ARRAY_LENGTH;
25473 this.__views__ = [];
25474 }
25475
25476 /**
25477 * Creates a clone of the lazy wrapper object.
25478 *
25479 * @private
25480 * @name clone
25481 * @memberOf LazyWrapper
25482 * @returns {Object} Returns the cloned `LazyWrapper` object.
25483 */
25484 function lazyClone() {
25485 var result = new LazyWrapper(this.__wrapped__);
25486 result.__actions__ = copyArray(this.__actions__);
25487 result.__dir__ = this.__dir__;
25488 result.__filtered__ = this.__filtered__;
25489 result.__iteratees__ = copyArray(this.__iteratees__);
25490 result.__takeCount__ = this.__takeCount__;
25491 result.__views__ = copyArray(this.__views__);
25492 return result;
25493 }
25494
25495 /**
25496 * Reverses the direction of lazy iteration.
25497 *
25498 * @private
25499 * @name reverse
25500 * @memberOf LazyWrapper
25501 * @returns {Object} Returns the new reversed `LazyWrapper` object.
25502 */
25503 function lazyReverse() {
25504 if (this.__filtered__) {
25505 var result = new LazyWrapper(this);
25506 result.__dir__ = -1;
25507 result.__filtered__ = true;
25508 } else {
25509 result = this.clone();
25510 result.__dir__ *= -1;
25511 }
25512 return result;
25513 }
25514
25515 /**
25516 * Extracts the unwrapped value from its lazy wrapper.
25517 *
25518 * @private
25519 * @name value
25520 * @memberOf LazyWrapper
25521 * @returns {*} Returns the unwrapped value.
25522 */
25523 function lazyValue() {
25524 var array = this.__wrapped__.value(),
25525 dir = this.__dir__,
25526 isArr = isArray(array),
25527 isRight = dir < 0,
25528 arrLength = isArr ? array.length : 0,
25529 view = getView(0, arrLength, this.__views__),
25530 start = view.start,
25531 end = view.end,
25532 length = end - start,
25533 index = isRight ? end : (start - 1),
25534 iteratees = this.__iteratees__,
25535 iterLength = iteratees.length,
25536 resIndex = 0,
25537 takeCount = nativeMin(length, this.__takeCount__);
25538
25539 if (!isArr || arrLength < LARGE_ARRAY_SIZE ||
25540 (arrLength == length && takeCount == length)) {
25541 return baseWrapperValue(array, this.__actions__);
25542 }
25543 var result = [];
25544
25545 outer:
25546 while (length-- && resIndex < takeCount) {
25547 index += dir;
25548
25549 var iterIndex = -1,
25550 value = array[index];
25551
25552 while (++iterIndex < iterLength) {
25553 var data = iteratees[iterIndex],
25554 iteratee = data.iteratee,
25555 type = data.type,
25556 computed = iteratee(value);
25557
25558 if (type == LAZY_MAP_FLAG) {
25559 value = computed;
25560 } else if (!computed) {
25561 if (type == LAZY_FILTER_FLAG) {
25562 continue outer;
25563 } else {
25564 break outer;
25565 }
25566 }
25567 }
25568 result[resIndex++] = value;
25569 }
25570 return result;
25571 }
25572
25573 // Ensure `LazyWrapper` is an instance of `baseLodash`.
25574 LazyWrapper.prototype = baseCreate(baseLodash.prototype);
25575 LazyWrapper.prototype.constructor = LazyWrapper;
25576
25577 /*------------------------------------------------------------------------*/
25578
25579 /**
25580 * Creates a hash object.
25581 *
25582 * @private
25583 * @constructor
25584 * @param {Array} [entries] The key-value pairs to cache.
25585 */
25586 function Hash(entries) {
25587 var index = -1,
25588 length = entries ? entries.length : 0;
25589
25590 this.clear();
25591 while (++index < length) {
25592 var entry = entries[index];
25593 this.set(entry[0], entry[1]);
25594 }
25595 }
25596
25597 /**
25598 * Removes all key-value entries from the hash.
25599 *
25600 * @private
25601 * @name clear
25602 * @memberOf Hash
25603 */
25604 function hashClear() {
25605 this.__data__ = nativeCreate ? nativeCreate(null) : {};
25606 this.size = 0;
25607 }
25608
25609 /**
25610 * Removes `key` and its value from the hash.
25611 *
25612 * @private
25613 * @name delete
25614 * @memberOf Hash
25615 * @param {Object} hash The hash to modify.
25616 * @param {string} key The key of the value to remove.
25617 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
25618 */
25619 function hashDelete(key) {
25620 var result = this.has(key) && delete this.__data__[key];
25621 this.size -= result ? 1 : 0;
25622 return result;
25623 }
25624
25625 /**
25626 * Gets the hash value for `key`.
25627 *
25628 * @private
25629 * @name get
25630 * @memberOf Hash
25631 * @param {string} key The key of the value to get.
25632 * @returns {*} Returns the entry value.
25633 */
25634 function hashGet(key) {
25635 var data = this.__data__;
25636 if (nativeCreate) {
25637 var result = data[key];
25638 return result === HASH_UNDEFINED ? undefined : result;
25639 }
25640 return hasOwnProperty.call(data, key) ? data[key] : undefined;
25641 }
25642
25643 /**
25644 * Checks if a hash value for `key` exists.
25645 *
25646 * @private
25647 * @name has
25648 * @memberOf Hash
25649 * @param {string} key The key of the entry to check.
25650 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
25651 */
25652 function hashHas(key) {
25653 var data = this.__data__;
25654 return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);
25655 }
25656
25657 /**
25658 * Sets the hash `key` to `value`.
25659 *
25660 * @private
25661 * @name set
25662 * @memberOf Hash
25663 * @param {string} key The key of the value to set.
25664 * @param {*} value The value to set.
25665 * @returns {Object} Returns the hash instance.
25666 */
25667 function hashSet(key, value) {
25668 var data = this.__data__;
25669 this.size += this.has(key) ? 0 : 1;
25670 data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
25671 return this;
25672 }
25673
25674 // Add methods to `Hash`.
25675 Hash.prototype.clear = hashClear;
25676 Hash.prototype['delete'] = hashDelete;
25677 Hash.prototype.get = hashGet;
25678 Hash.prototype.has = hashHas;
25679 Hash.prototype.set = hashSet;
25680
25681 /*------------------------------------------------------------------------*/
25682
25683 /**
25684 * Creates an list cache object.
25685 *
25686 * @private
25687 * @constructor
25688 * @param {Array} [entries] The key-value pairs to cache.
25689 */
25690 function ListCache(entries) {
25691 var index = -1,
25692 length = entries ? entries.length : 0;
25693
25694 this.clear();
25695 while (++index < length) {
25696 var entry = entries[index];
25697 this.set(entry[0], entry[1]);
25698 }
25699 }
25700
25701 /**
25702 * Removes all key-value entries from the list cache.
25703 *
25704 * @private
25705 * @name clear
25706 * @memberOf ListCache
25707 */
25708 function listCacheClear() {
25709 this.__data__ = [];
25710 this.size = 0;
25711 }
25712
25713 /**
25714 * Removes `key` and its value from the list cache.
25715 *
25716 * @private
25717 * @name delete
25718 * @memberOf ListCache
25719 * @param {string} key The key of the value to remove.
25720 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
25721 */
25722 function listCacheDelete(key) {
25723 var data = this.__data__,
25724 index = assocIndexOf(data, key);
25725
25726 if (index < 0) {
25727 return false;
25728 }
25729 var lastIndex = data.length - 1;
25730 if (index == lastIndex) {
25731 data.pop();
25732 } else {
25733 splice.call(data, index, 1);
25734 }
25735 --this.size;
25736 return true;
25737 }
25738
25739 /**
25740 * Gets the list cache value for `key`.
25741 *
25742 * @private
25743 * @name get
25744 * @memberOf ListCache
25745 * @param {string} key The key of the value to get.
25746 * @returns {*} Returns the entry value.
25747 */
25748 function listCacheGet(key) {
25749 var data = this.__data__,
25750 index = assocIndexOf(data, key);
25751
25752 return index < 0 ? undefined : data[index][1];
25753 }
25754
25755 /**
25756 * Checks if a list cache value for `key` exists.
25757 *
25758 * @private
25759 * @name has
25760 * @memberOf ListCache
25761 * @param {string} key The key of the entry to check.
25762 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
25763 */
25764 function listCacheHas(key) {
25765 return assocIndexOf(this.__data__, key) > -1;
25766 }
25767
25768 /**
25769 * Sets the list cache `key` to `value`.
25770 *
25771 * @private
25772 * @name set
25773 * @memberOf ListCache
25774 * @param {string} key The key of the value to set.
25775 * @param {*} value The value to set.
25776 * @returns {Object} Returns the list cache instance.
25777 */
25778 function listCacheSet(key, value) {
25779 var data = this.__data__,
25780 index = assocIndexOf(data, key);
25781
25782 if (index < 0) {
25783 ++this.size;
25784 data.push([key, value]);
25785 } else {
25786 data[index][1] = value;
25787 }
25788 return this;
25789 }
25790
25791 // Add methods to `ListCache`.
25792 ListCache.prototype.clear = listCacheClear;
25793 ListCache.prototype['delete'] = listCacheDelete;
25794 ListCache.prototype.get = listCacheGet;
25795 ListCache.prototype.has = listCacheHas;
25796 ListCache.prototype.set = listCacheSet;
25797
25798 /*------------------------------------------------------------------------*/
25799
25800 /**
25801 * Creates a map cache object to store key-value pairs.
25802 *
25803 * @private
25804 * @constructor
25805 * @param {Array} [entries] The key-value pairs to cache.
25806 */
25807 function MapCache(entries) {
25808 var index = -1,
25809 length = entries ? entries.length : 0;
25810
25811 this.clear();
25812 while (++index < length) {
25813 var entry = entries[index];
25814 this.set(entry[0], entry[1]);
25815 }
25816 }
25817
25818 /**
25819 * Removes all key-value entries from the map.
25820 *
25821 * @private
25822 * @name clear
25823 * @memberOf MapCache
25824 */
25825 function mapCacheClear() {
25826 this.size = 0;
25827 this.__data__ = {
25828 'hash': new Hash,
25829 'map': new (Map || ListCache),
25830 'string': new Hash
25831 };
25832 }
25833
25834 /**
25835 * Removes `key` and its value from the map.
25836 *
25837 * @private
25838 * @name delete
25839 * @memberOf MapCache
25840 * @param {string} key The key of the value to remove.
25841 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
25842 */
25843 function mapCacheDelete(key) {
25844 var result = getMapData(this, key)['delete'](key);
25845 this.size -= result ? 1 : 0;
25846 return result;
25847 }
25848
25849 /**
25850 * Gets the map value for `key`.
25851 *
25852 * @private
25853 * @name get
25854 * @memberOf MapCache
25855 * @param {string} key The key of the value to get.
25856 * @returns {*} Returns the entry value.
25857 */
25858 function mapCacheGet(key) {
25859 return getMapData(this, key).get(key);
25860 }
25861
25862 /**
25863 * Checks if a map value for `key` exists.
25864 *
25865 * @private
25866 * @name has
25867 * @memberOf MapCache
25868 * @param {string} key The key of the entry to check.
25869 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
25870 */
25871 function mapCacheHas(key) {
25872 return getMapData(this, key).has(key);
25873 }
25874
25875 /**
25876 * Sets the map `key` to `value`.
25877 *
25878 * @private
25879 * @name set
25880 * @memberOf MapCache
25881 * @param {string} key The key of the value to set.
25882 * @param {*} value The value to set.
25883 * @returns {Object} Returns the map cache instance.
25884 */
25885 function mapCacheSet(key, value) {
25886 var data = getMapData(this, key),
25887 size = data.size;
25888
25889 data.set(key, value);
25890 this.size += data.size == size ? 0 : 1;
25891 return this;
25892 }
25893
25894 // Add methods to `MapCache`.
25895 MapCache.prototype.clear = mapCacheClear;
25896 MapCache.prototype['delete'] = mapCacheDelete;
25897 MapCache.prototype.get = mapCacheGet;
25898 MapCache.prototype.has = mapCacheHas;
25899 MapCache.prototype.set = mapCacheSet;
25900
25901 /*------------------------------------------------------------------------*/
25902
25903 /**
25904 *
25905 * Creates an array cache object to store unique values.
25906 *
25907 * @private
25908 * @constructor
25909 * @param {Array} [values] The values to cache.
25910 */
25911 function SetCache(values) {
25912 var index = -1,
25913 length = values ? values.length : 0;
25914
25915 this.__data__ = new MapCache;
25916 while (++index < length) {
25917 this.add(values[index]);
25918 }
25919 }
25920
25921 /**
25922 * Adds `value` to the array cache.
25923 *
25924 * @private
25925 * @name add
25926 * @memberOf SetCache
25927 * @alias push
25928 * @param {*} value The value to cache.
25929 * @returns {Object} Returns the cache instance.
25930 */
25931 function setCacheAdd(value) {
25932 this.__data__.set(value, HASH_UNDEFINED);
25933 return this;
25934 }
25935
25936 /**
25937 * Checks if `value` is in the array cache.
25938 *
25939 * @private
25940 * @name has
25941 * @memberOf SetCache
25942 * @param {*} value The value to search for.
25943 * @returns {number} Returns `true` if `value` is found, else `false`.
25944 */
25945 function setCacheHas(value) {
25946 return this.__data__.has(value);
25947 }
25948
25949 // Add methods to `SetCache`.
25950 SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
25951 SetCache.prototype.has = setCacheHas;
25952
25953 /*------------------------------------------------------------------------*/
25954
25955 /**
25956 * Creates a stack cache object to store key-value pairs.
25957 *
25958 * @private
25959 * @constructor
25960 * @param {Array} [entries] The key-value pairs to cache.
25961 */
25962 function Stack(entries) {
25963 var data = this.__data__ = new ListCache(entries);
25964 this.size = data.size;
25965 }
25966
25967 /**
25968 * Removes all key-value entries from the stack.
25969 *
25970 * @private
25971 * @name clear
25972 * @memberOf Stack
25973 */
25974 function stackClear() {
25975 this.__data__ = new ListCache;
25976 this.size = 0;
25977 }
25978
25979 /**
25980 * Removes `key` and its value from the stack.
25981 *
25982 * @private
25983 * @name delete
25984 * @memberOf Stack
25985 * @param {string} key The key of the value to remove.
25986 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
25987 */
25988 function stackDelete(key) {
25989 var data = this.__data__,
25990 result = data['delete'](key);
25991
25992 this.size = data.size;
25993 return result;
25994 }
25995
25996 /**
25997 * Gets the stack value for `key`.
25998 *
25999 * @private
26000 * @name get
26001 * @memberOf Stack
26002 * @param {string} key The key of the value to get.
26003 * @returns {*} Returns the entry value.
26004 */
26005 function stackGet(key) {
26006 return this.__data__.get(key);
26007 }
26008
26009 /**
26010 * Checks if a stack value for `key` exists.
26011 *
26012 * @private
26013 * @name has
26014 * @memberOf Stack
26015 * @param {string} key The key of the entry to check.
26016 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
26017 */
26018 function stackHas(key) {
26019 return this.__data__.has(key);
26020 }
26021
26022 /**
26023 * Sets the stack `key` to `value`.
26024 *
26025 * @private
26026 * @name set
26027 * @memberOf Stack
26028 * @param {string} key The key of the value to set.
26029 * @param {*} value The value to set.
26030 * @returns {Object} Returns the stack cache instance.
26031 */
26032 function stackSet(key, value) {
26033 var data = this.__data__;
26034 if (data instanceof ListCache) {
26035 var pairs = data.__data__;
26036 if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
26037 pairs.push([key, value]);
26038 this.size = ++data.size;
26039 return this;
26040 }
26041 data = this.__data__ = new MapCache(pairs);
26042 }
26043 data.set(key, value);
26044 this.size = data.size;
26045 return this;
26046 }
26047
26048 // Add methods to `Stack`.
26049 Stack.prototype.clear = stackClear;
26050 Stack.prototype['delete'] = stackDelete;
26051 Stack.prototype.get = stackGet;
26052 Stack.prototype.has = stackHas;
26053 Stack.prototype.set = stackSet;
26054
26055 /*------------------------------------------------------------------------*/
26056
26057 /**
26058 * Creates an array of the enumerable property names of the array-like `value`.
26059 *
26060 * @private
26061 * @param {*} value The value to query.
26062 * @param {boolean} inherited Specify returning inherited property names.
26063 * @returns {Array} Returns the array of property names.
26064 */
26065 function arrayLikeKeys(value, inherited) {
26066 var isArr = isArray(value),
26067 isArg = !isArr && isArguments(value),
26068 isBuff = !isArr && !isArg && isBuffer(value),
26069 isType = !isArr && !isArg && !isBuff && isTypedArray(value),
26070 skipIndexes = isArr || isArg || isBuff || isType,
26071 result = skipIndexes ? baseTimes(value.length, String) : [],
26072 length = result.length;
26073
26074 for (var key in value) {
26075 if ((inherited || hasOwnProperty.call(value, key)) &&
26076 !(skipIndexes && (
26077 // Safari 9 has enumerable `arguments.length` in strict mode.
26078 key == 'length' ||
26079 // Node.js 0.10 has enumerable non-index properties on buffers.
26080 (isBuff && (key == 'offset' || key == 'parent')) ||
26081 // PhantomJS 2 has enumerable non-index properties on typed arrays.
26082 (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
26083 // Skip index properties.
26084 isIndex(key, length)
26085 ))) {
26086 result.push(key);
26087 }
26088 }
26089 return result;
26090 }
26091
26092 /**
26093 * A specialized version of `_.sample` for arrays.
26094 *
26095 * @private
26096 * @param {Array} array The array to sample.
26097 * @returns {*} Returns the random element.
26098 */
26099 function arraySample(array) {
26100 var length = array.length;
26101 return length ? array[baseRandom(0, length - 1)] : undefined;
26102 }
26103
26104 /**
26105 * A specialized version of `_.sampleSize` for arrays.
26106 *
26107 * @private
26108 * @param {Array} array The array to sample.
26109 * @param {number} n The number of elements to sample.
26110 * @returns {Array} Returns the random elements.
26111 */
26112 function arraySampleSize(array, n) {
26113 return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length));
26114 }
26115
26116 /**
26117 * A specialized version of `_.shuffle` for arrays.
26118 *
26119 * @private
26120 * @param {Array} array The array to shuffle.
26121 * @returns {Array} Returns the new shuffled array.
26122 */
26123 function arrayShuffle(array) {
26124 return shuffleSelf(copyArray(array));
26125 }
26126
26127 /**
26128 * Used by `_.defaults` to customize its `_.assignIn` use.
26129 *
26130 * @private
26131 * @param {*} objValue The destination value.
26132 * @param {*} srcValue The source value.
26133 * @param {string} key The key of the property to assign.
26134 * @param {Object} object The parent object of `objValue`.
26135 * @returns {*} Returns the value to assign.
26136 */
26137 function assignInDefaults(objValue, srcValue, key, object) {
26138 if (objValue === undefined ||
26139 (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) {
26140 return srcValue;
26141 }
26142 return objValue;
26143 }
26144
26145 /**
26146 * This function is like `assignValue` except that it doesn't assign
26147 * `undefined` values.
26148 *
26149 * @private
26150 * @param {Object} object The object to modify.
26151 * @param {string} key The key of the property to assign.
26152 * @param {*} value The value to assign.
26153 */
26154 function assignMergeValue(object, key, value) {
26155 if ((value !== undefined && !eq(object[key], value)) ||
26156 (value === undefined && !(key in object))) {
26157 baseAssignValue(object, key, value);
26158 }
26159 }
26160
26161 /**
26162 * Assigns `value` to `key` of `object` if the existing value is not equivalent
26163 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
26164 * for equality comparisons.
26165 *
26166 * @private
26167 * @param {Object} object The object to modify.
26168 * @param {string} key The key of the property to assign.
26169 * @param {*} value The value to assign.
26170 */
26171 function assignValue(object, key, value) {
26172 var objValue = object[key];
26173 if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
26174 (value === undefined && !(key in object))) {
26175 baseAssignValue(object, key, value);
26176 }
26177 }
26178
26179 /**
26180 * Gets the index at which the `key` is found in `array` of key-value pairs.
26181 *
26182 * @private
26183 * @param {Array} array The array to inspect.
26184 * @param {*} key The key to search for.
26185 * @returns {number} Returns the index of the matched value, else `-1`.
26186 */
26187 function assocIndexOf(array, key) {
26188 var length = array.length;
26189 while (length--) {
26190 if (eq(array[length][0], key)) {
26191 return length;
26192 }
26193 }
26194 return -1;
26195 }
26196
26197 /**
26198 * Aggregates elements of `collection` on `accumulator` with keys transformed
26199 * by `iteratee` and values set by `setter`.
26200 *
26201 * @private
26202 * @param {Array|Object} collection The collection to iterate over.
26203 * @param {Function} setter The function to set `accumulator` values.
26204 * @param {Function} iteratee The iteratee to transform keys.
26205 * @param {Object} accumulator The initial aggregated object.
26206 * @returns {Function} Returns `accumulator`.
26207 */
26208 function baseAggregator(collection, setter, iteratee, accumulator) {
26209 baseEach(collection, function(value, key, collection) {
26210 setter(accumulator, value, iteratee(value), collection);
26211 });
26212 return accumulator;
26213 }
26214
26215 /**
26216 * The base implementation of `_.assign` without support for multiple sources
26217 * or `customizer` functions.
26218 *
26219 * @private
26220 * @param {Object} object The destination object.
26221 * @param {Object} source The source object.
26222 * @returns {Object} Returns `object`.
26223 */
26224 function baseAssign(object, source) {
26225 return object && copyObject(source, keys(source), object);
26226 }
26227
26228 /**
26229 * The base implementation of `assignValue` and `assignMergeValue` without
26230 * value checks.
26231 *
26232 * @private
26233 * @param {Object} object The object to modify.
26234 * @param {string} key The key of the property to assign.
26235 * @param {*} value The value to assign.
26236 */
26237 function baseAssignValue(object, key, value) {
26238 if (key == '__proto__' && defineProperty) {
26239 defineProperty(object, key, {
26240 'configurable': true,
26241 'enumerable': true,
26242 'value': value,
26243 'writable': true
26244 });
26245 } else {
26246 object[key] = value;
26247 }
26248 }
26249
26250 /**
26251 * The base implementation of `_.at` without support for individual paths.
26252 *
26253 * @private
26254 * @param {Object} object The object to iterate over.
26255 * @param {string[]} paths The property paths of elements to pick.
26256 * @returns {Array} Returns the picked elements.
26257 */
26258 function baseAt(object, paths) {
26259 var index = -1,
26260 isNil = object == null,
26261 length = paths.length,
26262 result = Array(length);
26263
26264 while (++index < length) {
26265 result[index] = isNil ? undefined : get(object, paths[index]);
26266 }
26267 return result;
26268 }
26269
26270 /**
26271 * The base implementation of `_.clamp` which doesn't coerce arguments.
26272 *
26273 * @private
26274 * @param {number} number The number to clamp.
26275 * @param {number} [lower] The lower bound.
26276 * @param {number} upper The upper bound.
26277 * @returns {number} Returns the clamped number.
26278 */
26279 function baseClamp(number, lower, upper) {
26280 if (number === number) {
26281 if (upper !== undefined) {
26282 number = number <= upper ? number : upper;
26283 }
26284 if (lower !== undefined) {
26285 number = number >= lower ? number : lower;
26286 }
26287 }
26288 return number;
26289 }
26290
26291 /**
26292 * The base implementation of `_.clone` and `_.cloneDeep` which tracks
26293 * traversed objects.
26294 *
26295 * @private
26296 * @param {*} value The value to clone.
26297 * @param {boolean} [isDeep] Specify a deep clone.
26298 * @param {boolean} [isFull] Specify a clone including symbols.
26299 * @param {Function} [customizer] The function to customize cloning.
26300 * @param {string} [key] The key of `value`.
26301 * @param {Object} [object] The parent object of `value`.
26302 * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
26303 * @returns {*} Returns the cloned value.
26304 */
26305 function baseClone(value, isDeep, isFull, customizer, key, object, stack) {
26306 var result;
26307 if (customizer) {
26308 result = object ? customizer(value, key, object, stack) : customizer(value);
26309 }
26310 if (result !== undefined) {
26311 return result;
26312 }
26313 if (!isObject(value)) {
26314 return value;
26315 }
26316 var isArr = isArray(value);
26317 if (isArr) {
26318 result = initCloneArray(value);
26319 if (!isDeep) {
26320 return copyArray(value, result);
26321 }
26322 } else {
26323 var tag = getTag(value),
26324 isFunc = tag == funcTag || tag == genTag;
26325
26326 if (isBuffer(value)) {
26327 return cloneBuffer(value, isDeep);
26328 }
26329 if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
26330 result = initCloneObject(isFunc ? {} : value);
26331 if (!isDeep) {
26332 return copySymbols(value, baseAssign(result, value));
26333 }
26334 } else {
26335 if (!cloneableTags[tag]) {
26336 return object ? value : {};
26337 }
26338 result = initCloneByTag(value, tag, baseClone, isDeep);
26339 }
26340 }
26341 // Check for circular references and return its corresponding clone.
26342 stack || (stack = new Stack);
26343 var stacked = stack.get(value);
26344 if (stacked) {
26345 return stacked;
26346 }
26347 stack.set(value, result);
26348
26349 var props = isArr ? undefined : (isFull ? getAllKeys : keys)(value);
26350 arrayEach(props || value, function(subValue, key) {
26351 if (props) {
26352 key = subValue;
26353 subValue = value[key];
26354 }
26355 // Recursively populate clone (susceptible to call stack limits).
26356 assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack));
26357 });
26358 return result;
26359 }
26360
26361 /**
26362 * The base implementation of `_.conforms` which doesn't clone `source`.
26363 *
26364 * @private
26365 * @param {Object} source The object of property predicates to conform to.
26366 * @returns {Function} Returns the new spec function.
26367 */
26368 function baseConforms(source) {
26369 var props = keys(source);
26370 return function(object) {
26371 return baseConformsTo(object, source, props);
26372 };
26373 }
26374
26375 /**
26376 * The base implementation of `_.conformsTo` which accepts `props` to check.
26377 *
26378 * @private
26379 * @param {Object} object The object to inspect.
26380 * @param {Object} source The object of property predicates to conform to.
26381 * @returns {boolean} Returns `true` if `object` conforms, else `false`.
26382 */
26383 function baseConformsTo(object, source, props) {
26384 var length = props.length;
26385 if (object == null) {
26386 return !length;
26387 }
26388 object = Object(object);
26389 while (length--) {
26390 var key = props[length],
26391 predicate = source[key],
26392 value = object[key];
26393
26394 if ((value === undefined && !(key in object)) || !predicate(value)) {
26395 return false;
26396 }
26397 }
26398 return true;
26399 }
26400
26401 /**
26402 * The base implementation of `_.delay` and `_.defer` which accepts `args`
26403 * to provide to `func`.
26404 *
26405 * @private
26406 * @param {Function} func The function to delay.
26407 * @param {number} wait The number of milliseconds to delay invocation.
26408 * @param {Array} args The arguments to provide to `func`.
26409 * @returns {number|Object} Returns the timer id or timeout object.
26410 */
26411 function baseDelay(func, wait, args) {
26412 if (typeof func != 'function') {
26413 throw new TypeError(FUNC_ERROR_TEXT);
26414 }
26415 return setTimeout(function() { func.apply(undefined, args); }, wait);
26416 }
26417
26418 /**
26419 * The base implementation of methods like `_.difference` without support
26420 * for excluding multiple arrays or iteratee shorthands.
26421 *
26422 * @private
26423 * @param {Array} array The array to inspect.
26424 * @param {Array} values The values to exclude.
26425 * @param {Function} [iteratee] The iteratee invoked per element.
26426 * @param {Function} [comparator] The comparator invoked per element.
26427 * @returns {Array} Returns the new array of filtered values.
26428 */
26429 function baseDifference(array, values, iteratee, comparator) {
26430 var index = -1,
26431 includes = arrayIncludes,
26432 isCommon = true,
26433 length = array.length,
26434 result = [],
26435 valuesLength = values.length;
26436
26437 if (!length) {
26438 return result;
26439 }
26440 if (iteratee) {
26441 values = arrayMap(values, baseUnary(iteratee));
26442 }
26443 if (comparator) {
26444 includes = arrayIncludesWith;
26445 isCommon = false;
26446 }
26447 else if (values.length >= LARGE_ARRAY_SIZE) {
26448 includes = cacheHas;
26449 isCommon = false;
26450 values = new SetCache(values);
26451 }
26452 outer:
26453 while (++index < length) {
26454 var value = array[index],
26455 computed = iteratee ? iteratee(value) : value;
26456
26457 value = (comparator || value !== 0) ? value : 0;
26458 if (isCommon && computed === computed) {
26459 var valuesIndex = valuesLength;
26460 while (valuesIndex--) {
26461 if (values[valuesIndex] === computed) {
26462 continue outer;
26463 }
26464 }
26465 result.push(value);
26466 }
26467 else if (!includes(values, computed, comparator)) {
26468 result.push(value);
26469 }
26470 }
26471 return result;
26472 }
26473
26474 /**
26475 * The base implementation of `_.forEach` without support for iteratee shorthands.
26476 *
26477 * @private
26478 * @param {Array|Object} collection The collection to iterate over.
26479 * @param {Function} iteratee The function invoked per iteration.
26480 * @returns {Array|Object} Returns `collection`.
26481 */
26482 var baseEach = createBaseEach(baseForOwn);
26483
26484 /**
26485 * The base implementation of `_.forEachRight` without support for iteratee shorthands.
26486 *
26487 * @private
26488 * @param {Array|Object} collection The collection to iterate over.
26489 * @param {Function} iteratee The function invoked per iteration.
26490 * @returns {Array|Object} Returns `collection`.
26491 */
26492 var baseEachRight = createBaseEach(baseForOwnRight, true);
26493
26494 /**
26495 * The base implementation of `_.every` without support for iteratee shorthands.
26496 *
26497 * @private
26498 * @param {Array|Object} collection The collection to iterate over.
26499 * @param {Function} predicate The function invoked per iteration.
26500 * @returns {boolean} Returns `true` if all elements pass the predicate check,
26501 * else `false`
26502 */
26503 function baseEvery(collection, predicate) {
26504 var result = true;
26505 baseEach(collection, function(value, index, collection) {
26506 result = !!predicate(value, index, collection);
26507 return result;
26508 });
26509 return result;
26510 }
26511
26512 /**
26513 * The base implementation of methods like `_.max` and `_.min` which accepts a
26514 * `comparator` to determine the extremum value.
26515 *
26516 * @private
26517 * @param {Array} array The array to iterate over.
26518 * @param {Function} iteratee The iteratee invoked per iteration.
26519 * @param {Function} comparator The comparator used to compare values.
26520 * @returns {*} Returns the extremum value.
26521 */
26522 function baseExtremum(array, iteratee, comparator) {
26523 var index = -1,
26524 length = array.length;
26525
26526 while (++index < length) {
26527 var value = array[index],
26528 current = iteratee(value);
26529
26530 if (current != null && (computed === undefined
26531 ? (current === current && !isSymbol(current))
26532 : comparator(current, computed)
26533 )) {
26534 var computed = current,
26535 result = value;
26536 }
26537 }
26538 return result;
26539 }
26540
26541 /**
26542 * The base implementation of `_.fill` without an iteratee call guard.
26543 *
26544 * @private
26545 * @param {Array} array The array to fill.
26546 * @param {*} value The value to fill `array` with.
26547 * @param {number} [start=0] The start position.
26548 * @param {number} [end=array.length] The end position.
26549 * @returns {Array} Returns `array`.
26550 */
26551 function baseFill(array, value, start, end) {
26552 var length = array.length;
26553
26554 start = toInteger(start);
26555 if (start < 0) {
26556 start = -start > length ? 0 : (length + start);
26557 }
26558 end = (end === undefined || end > length) ? length : toInteger(end);
26559 if (end < 0) {
26560 end += length;
26561 }
26562 end = start > end ? 0 : toLength(end);
26563 while (start < end) {
26564 array[start++] = value;
26565 }
26566 return array;
26567 }
26568
26569 /**
26570 * The base implementation of `_.filter` without support for iteratee shorthands.
26571 *
26572 * @private
26573 * @param {Array|Object} collection The collection to iterate over.
26574 * @param {Function} predicate The function invoked per iteration.
26575 * @returns {Array} Returns the new filtered array.
26576 */
26577 function baseFilter(collection, predicate) {
26578 var result = [];
26579 baseEach(collection, function(value, index, collection) {
26580 if (predicate(value, index, collection)) {
26581 result.push(value);
26582 }
26583 });
26584 return result;
26585 }
26586
26587 /**
26588 * The base implementation of `_.flatten` with support for restricting flattening.
26589 *
26590 * @private
26591 * @param {Array} array The array to flatten.
26592 * @param {number} depth The maximum recursion depth.
26593 * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
26594 * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
26595 * @param {Array} [result=[]] The initial result value.
26596 * @returns {Array} Returns the new flattened array.
26597 */
26598 function baseFlatten(array, depth, predicate, isStrict, result) {
26599 var index = -1,
26600 length = array.length;
26601
26602 predicate || (predicate = isFlattenable);
26603 result || (result = []);
26604
26605 while (++index < length) {
26606 var value = array[index];
26607 if (depth > 0 && predicate(value)) {
26608 if (depth > 1) {
26609 // Recursively flatten arrays (susceptible to call stack limits).
26610 baseFlatten(value, depth - 1, predicate, isStrict, result);
26611 } else {
26612 arrayPush(result, value);
26613 }
26614 } else if (!isStrict) {
26615 result[result.length] = value;
26616 }
26617 }
26618 return result;
26619 }
26620
26621 /**
26622 * The base implementation of `baseForOwn` which iterates over `object`
26623 * properties returned by `keysFunc` and invokes `iteratee` for each property.
26624 * Iteratee functions may exit iteration early by explicitly returning `false`.
26625 *
26626 * @private
26627 * @param {Object} object The object to iterate over.
26628 * @param {Function} iteratee The function invoked per iteration.
26629 * @param {Function} keysFunc The function to get the keys of `object`.
26630 * @returns {Object} Returns `object`.
26631 */
26632 var baseFor = createBaseFor();
26633
26634 /**
26635 * This function is like `baseFor` except that it iterates over properties
26636 * in the opposite order.
26637 *
26638 * @private
26639 * @param {Object} object The object to iterate over.
26640 * @param {Function} iteratee The function invoked per iteration.
26641 * @param {Function} keysFunc The function to get the keys of `object`.
26642 * @returns {Object} Returns `object`.
26643 */
26644 var baseForRight = createBaseFor(true);
26645
26646 /**
26647 * The base implementation of `_.forOwn` without support for iteratee shorthands.
26648 *
26649 * @private
26650 * @param {Object} object The object to iterate over.
26651 * @param {Function} iteratee The function invoked per iteration.
26652 * @returns {Object} Returns `object`.
26653 */
26654 function baseForOwn(object, iteratee) {
26655 return object && baseFor(object, iteratee, keys);
26656 }
26657
26658 /**
26659 * The base implementation of `_.forOwnRight` without support for iteratee shorthands.
26660 *
26661 * @private
26662 * @param {Object} object The object to iterate over.
26663 * @param {Function} iteratee The function invoked per iteration.
26664 * @returns {Object} Returns `object`.
26665 */
26666 function baseForOwnRight(object, iteratee) {
26667 return object && baseForRight(object, iteratee, keys);
26668 }
26669
26670 /**
26671 * The base implementation of `_.functions` which creates an array of
26672 * `object` function property names filtered from `props`.
26673 *
26674 * @private
26675 * @param {Object} object The object to inspect.
26676 * @param {Array} props The property names to filter.
26677 * @returns {Array} Returns the function names.
26678 */
26679 function baseFunctions(object, props) {
26680 return arrayFilter(props, function(key) {
26681 return isFunction(object[key]);
26682 });
26683 }
26684
26685 /**
26686 * The base implementation of `_.get` without support for default values.
26687 *
26688 * @private
26689 * @param {Object} object The object to query.
26690 * @param {Array|string} path The path of the property to get.
26691 * @returns {*} Returns the resolved value.
26692 */
26693 function baseGet(object, path) {
26694 path = isKey(path, object) ? [path] : castPath(path);
26695
26696 var index = 0,
26697 length = path.length;
26698
26699 while (object != null && index < length) {
26700 object = object[toKey(path[index++])];
26701 }
26702 return (index && index == length) ? object : undefined;
26703 }
26704
26705 /**
26706 * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
26707 * `keysFunc` and `symbolsFunc` to get the enumerable property names and
26708 * symbols of `object`.
26709 *
26710 * @private
26711 * @param {Object} object The object to query.
26712 * @param {Function} keysFunc The function to get the keys of `object`.
26713 * @param {Function} symbolsFunc The function to get the symbols of `object`.
26714 * @returns {Array} Returns the array of property names and symbols.
26715 */
26716 function baseGetAllKeys(object, keysFunc, symbolsFunc) {
26717 var result = keysFunc(object);
26718 return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
26719 }
26720
26721 /**
26722 * The base implementation of `getTag`.
26723 *
26724 * @private
26725 * @param {*} value The value to query.
26726 * @returns {string} Returns the `toStringTag`.
26727 */
26728 function baseGetTag(value) {
26729 return objectToString.call(value);
26730 }
26731
26732 /**
26733 * The base implementation of `_.gt` which doesn't coerce arguments.
26734 *
26735 * @private
26736 * @param {*} value The value to compare.
26737 * @param {*} other The other value to compare.
26738 * @returns {boolean} Returns `true` if `value` is greater than `other`,
26739 * else `false`.
26740 */
26741 function baseGt(value, other) {
26742 return value > other;
26743 }
26744
26745 /**
26746 * The base implementation of `_.has` without support for deep paths.
26747 *
26748 * @private
26749 * @param {Object} [object] The object to query.
26750 * @param {Array|string} key The key to check.
26751 * @returns {boolean} Returns `true` if `key` exists, else `false`.
26752 */
26753 function baseHas(object, key) {
26754 return object != null && hasOwnProperty.call(object, key);
26755 }
26756
26757 /**
26758 * The base implementation of `_.hasIn` without support for deep paths.
26759 *
26760 * @private
26761 * @param {Object} [object] The object to query.
26762 * @param {Array|string} key The key to check.
26763 * @returns {boolean} Returns `true` if `key` exists, else `false`.
26764 */
26765 function baseHasIn(object, key) {
26766 return object != null && key in Object(object);
26767 }
26768
26769 /**
26770 * The base implementation of `_.inRange` which doesn't coerce arguments.
26771 *
26772 * @private
26773 * @param {number} number The number to check.
26774 * @param {number} start The start of the range.
26775 * @param {number} end The end of the range.
26776 * @returns {boolean} Returns `true` if `number` is in the range, else `false`.
26777 */
26778 function baseInRange(number, start, end) {
26779 return number >= nativeMin(start, end) && number < nativeMax(start, end);
26780 }
26781
26782 /**
26783 * The base implementation of methods like `_.intersection`, without support
26784 * for iteratee shorthands, that accepts an array of arrays to inspect.
26785 *
26786 * @private
26787 * @param {Array} arrays The arrays to inspect.
26788 * @param {Function} [iteratee] The iteratee invoked per element.
26789 * @param {Function} [comparator] The comparator invoked per element.
26790 * @returns {Array} Returns the new array of shared values.
26791 */
26792 function baseIntersection(arrays, iteratee, comparator) {
26793 var includes = comparator ? arrayIncludesWith : arrayIncludes,
26794 length = arrays[0].length,
26795 othLength = arrays.length,
26796 othIndex = othLength,
26797 caches = Array(othLength),
26798 maxLength = Infinity,
26799 result = [];
26800
26801 while (othIndex--) {
26802 var array = arrays[othIndex];
26803 if (othIndex && iteratee) {
26804 array = arrayMap(array, baseUnary(iteratee));
26805 }
26806 maxLength = nativeMin(array.length, maxLength);
26807 caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))
26808 ? new SetCache(othIndex && array)
26809 : undefined;
26810 }
26811 array = arrays[0];
26812
26813 var index = -1,
26814 seen = caches[0];
26815
26816 outer:
26817 while (++index < length && result.length < maxLength) {
26818 var value = array[index],
26819 computed = iteratee ? iteratee(value) : value;
26820
26821 value = (comparator || value !== 0) ? value : 0;
26822 if (!(seen
26823 ? cacheHas(seen, computed)
26824 : includes(result, computed, comparator)
26825 )) {
26826 othIndex = othLength;
26827 while (--othIndex) {
26828 var cache = caches[othIndex];
26829 if (!(cache
26830 ? cacheHas(cache, computed)
26831 : includes(arrays[othIndex], computed, comparator))
26832 ) {
26833 continue outer;
26834 }
26835 }
26836 if (seen) {
26837 seen.push(computed);
26838 }
26839 result.push(value);
26840 }
26841 }
26842 return result;
26843 }
26844
26845 /**
26846 * The base implementation of `_.invert` and `_.invertBy` which inverts
26847 * `object` with values transformed by `iteratee` and set by `setter`.
26848 *
26849 * @private
26850 * @param {Object} object The object to iterate over.
26851 * @param {Function} setter The function to set `accumulator` values.
26852 * @param {Function} iteratee The iteratee to transform values.
26853 * @param {Object} accumulator The initial inverted object.
26854 * @returns {Function} Returns `accumulator`.
26855 */
26856 function baseInverter(object, setter, iteratee, accumulator) {
26857 baseForOwn(object, function(value, key, object) {
26858 setter(accumulator, iteratee(value), key, object);
26859 });
26860 return accumulator;
26861 }
26862
26863 /**
26864 * The base implementation of `_.invoke` without support for individual
26865 * method arguments.
26866 *
26867 * @private
26868 * @param {Object} object The object to query.
26869 * @param {Array|string} path The path of the method to invoke.
26870 * @param {Array} args The arguments to invoke the method with.
26871 * @returns {*} Returns the result of the invoked method.
26872 */
26873 function baseInvoke(object, path, args) {
26874 if (!isKey(path, object)) {
26875 path = castPath(path);
26876 object = parent(object, path);
26877 path = last(path);
26878 }
26879 var func = object == null ? object : object[toKey(path)];
26880 return func == null ? undefined : apply(func, object, args);
26881 }
26882
26883 /**
26884 * The base implementation of `_.isArguments`.
26885 *
26886 * @private
26887 * @param {*} value The value to check.
26888 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
26889 */
26890 function baseIsArguments(value) {
26891 return isObjectLike(value) && objectToString.call(value) == argsTag;
26892 }
26893
26894 /**
26895 * The base implementation of `_.isArrayBuffer` without Node.js optimizations.
26896 *
26897 * @private
26898 * @param {*} value The value to check.
26899 * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.
26900 */
26901 function baseIsArrayBuffer(value) {
26902 return isObjectLike(value) && objectToString.call(value) == arrayBufferTag;
26903 }
26904
26905 /**
26906 * The base implementation of `_.isDate` without Node.js optimizations.
26907 *
26908 * @private
26909 * @param {*} value The value to check.
26910 * @returns {boolean} Returns `true` if `value` is a date object, else `false`.
26911 */
26912 function baseIsDate(value) {
26913 return isObjectLike(value) && objectToString.call(value) == dateTag;
26914 }
26915
26916 /**
26917 * The base implementation of `_.isEqual` which supports partial comparisons
26918 * and tracks traversed objects.
26919 *
26920 * @private
26921 * @param {*} value The value to compare.
26922 * @param {*} other The other value to compare.
26923 * @param {Function} [customizer] The function to customize comparisons.
26924 * @param {boolean} [bitmask] The bitmask of comparison flags.
26925 * The bitmask may be composed of the following flags:
26926 * 1 - Unordered comparison
26927 * 2 - Partial comparison
26928 * @param {Object} [stack] Tracks traversed `value` and `other` objects.
26929 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
26930 */
26931 function baseIsEqual(value, other, customizer, bitmask, stack) {
26932 if (value === other) {
26933 return true;
26934 }
26935 if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
26936 return value !== value && other !== other;
26937 }
26938 return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack);
26939 }
26940
26941 /**
26942 * A specialized version of `baseIsEqual` for arrays and objects which performs
26943 * deep comparisons and tracks traversed objects enabling objects with circular
26944 * references to be compared.
26945 *
26946 * @private
26947 * @param {Object} object The object to compare.
26948 * @param {Object} other The other object to compare.
26949 * @param {Function} equalFunc The function to determine equivalents of values.
26950 * @param {Function} [customizer] The function to customize comparisons.
26951 * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual`
26952 * for more details.
26953 * @param {Object} [stack] Tracks traversed `object` and `other` objects.
26954 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
26955 */
26956 function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) {
26957 var objIsArr = isArray(object),
26958 othIsArr = isArray(other),
26959 objTag = arrayTag,
26960 othTag = arrayTag;
26961
26962 if (!objIsArr) {
26963 objTag = getTag(object);
26964 objTag = objTag == argsTag ? objectTag : objTag;
26965 }
26966 if (!othIsArr) {
26967 othTag = getTag(other);
26968 othTag = othTag == argsTag ? objectTag : othTag;
26969 }
26970 var objIsObj = objTag == objectTag,
26971 othIsObj = othTag == objectTag,
26972 isSameTag = objTag == othTag;
26973
26974 if (isSameTag && isBuffer(object)) {
26975 if (!isBuffer(other)) {
26976 return false;
26977 }
26978 objIsArr = true;
26979 objIsObj = false;
26980 }
26981 if (isSameTag && !objIsObj) {
26982 stack || (stack = new Stack);
26983 return (objIsArr || isTypedArray(object))
26984 ? equalArrays(object, other, equalFunc, customizer, bitmask, stack)
26985 : equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack);
26986 }
26987 if (!(bitmask & PARTIAL_COMPARE_FLAG)) {
26988 var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
26989 othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
26990
26991 if (objIsWrapped || othIsWrapped) {
26992 var objUnwrapped = objIsWrapped ? object.value() : object,
26993 othUnwrapped = othIsWrapped ? other.value() : other;
26994
26995 stack || (stack = new Stack);
26996 return equalFunc(objUnwrapped, othUnwrapped, customizer, bitmask, stack);
26997 }
26998 }
26999 if (!isSameTag) {
27000 return false;
27001 }
27002 stack || (stack = new Stack);
27003 return equalObjects(object, other, equalFunc, customizer, bitmask, stack);
27004 }
27005
27006 /**
27007 * The base implementation of `_.isMap` without Node.js optimizations.
27008 *
27009 * @private
27010 * @param {*} value The value to check.
27011 * @returns {boolean} Returns `true` if `value` is a map, else `false`.
27012 */
27013 function baseIsMap(value) {
27014 return isObjectLike(value) && getTag(value) == mapTag;
27015 }
27016
27017 /**
27018 * The base implementation of `_.isMatch` without support for iteratee shorthands.
27019 *
27020 * @private
27021 * @param {Object} object The object to inspect.
27022 * @param {Object} source The object of property values to match.
27023 * @param {Array} matchData The property names, values, and compare flags to match.
27024 * @param {Function} [customizer] The function to customize comparisons.
27025 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
27026 */
27027 function baseIsMatch(object, source, matchData, customizer) {
27028 var index = matchData.length,
27029 length = index,
27030 noCustomizer = !customizer;
27031
27032 if (object == null) {
27033 return !length;
27034 }
27035 object = Object(object);
27036 while (index--) {
27037 var data = matchData[index];
27038 if ((noCustomizer && data[2])
27039 ? data[1] !== object[data[0]]
27040 : !(data[0] in object)
27041 ) {
27042 return false;
27043 }
27044 }
27045 while (++index < length) {
27046 data = matchData[index];
27047 var key = data[0],
27048 objValue = object[key],
27049 srcValue = data[1];
27050
27051 if (noCustomizer && data[2]) {
27052 if (objValue === undefined && !(key in object)) {
27053 return false;
27054 }
27055 } else {
27056 var stack = new Stack;
27057 if (customizer) {
27058 var result = customizer(objValue, srcValue, key, object, source, stack);
27059 }
27060 if (!(result === undefined
27061 ? baseIsEqual(srcValue, objValue, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack)
27062 : result
27063 )) {
27064 return false;
27065 }
27066 }
27067 }
27068 return true;
27069 }
27070
27071 /**
27072 * The base implementation of `_.isNative` without bad shim checks.
27073 *
27074 * @private
27075 * @param {*} value The value to check.
27076 * @returns {boolean} Returns `true` if `value` is a native function,
27077 * else `false`.
27078 */
27079 function baseIsNative(value) {
27080 if (!isObject(value) || isMasked(value)) {
27081 return false;
27082 }
27083 var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
27084 return pattern.test(toSource(value));
27085 }
27086
27087 /**
27088 * The base implementation of `_.isRegExp` without Node.js optimizations.
27089 *
27090 * @private
27091 * @param {*} value The value to check.
27092 * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
27093 */
27094 function baseIsRegExp(value) {
27095 return isObject(value) && objectToString.call(value) == regexpTag;
27096 }
27097
27098 /**
27099 * The base implementation of `_.isSet` without Node.js optimizations.
27100 *
27101 * @private
27102 * @param {*} value The value to check.
27103 * @returns {boolean} Returns `true` if `value` is a set, else `false`.
27104 */
27105 function baseIsSet(value) {
27106 return isObjectLike(value) && getTag(value) == setTag;
27107 }
27108
27109 /**
27110 * The base implementation of `_.isTypedArray` without Node.js optimizations.
27111 *
27112 * @private
27113 * @param {*} value The value to check.
27114 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
27115 */
27116 function baseIsTypedArray(value) {
27117 return isObjectLike(value) &&
27118 isLength(value.length) && !!typedArrayTags[objectToString.call(value)];
27119 }
27120
27121 /**
27122 * The base implementation of `_.iteratee`.
27123 *
27124 * @private
27125 * @param {*} [value=_.identity] The value to convert to an iteratee.
27126 * @returns {Function} Returns the iteratee.
27127 */
27128 function baseIteratee(value) {
27129 // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
27130 // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
27131 if (typeof value == 'function') {
27132 return value;
27133 }
27134 if (value == null) {
27135 return identity;
27136 }
27137 if (typeof value == 'object') {
27138 return isArray(value)
27139 ? baseMatchesProperty(value[0], value[1])
27140 : baseMatches(value);
27141 }
27142 return property(value);
27143 }
27144
27145 /**
27146 * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
27147 *
27148 * @private
27149 * @param {Object} object The object to query.
27150 * @returns {Array} Returns the array of property names.
27151 */
27152 function baseKeys(object) {
27153 if (!isPrototype(object)) {
27154 return nativeKeys(object);
27155 }
27156 var result = [];
27157 for (var key in Object(object)) {
27158 if (hasOwnProperty.call(object, key) && key != 'constructor') {
27159 result.push(key);
27160 }
27161 }
27162 return result;
27163 }
27164
27165 /**
27166 * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
27167 *
27168 * @private
27169 * @param {Object} object The object to query.
27170 * @returns {Array} Returns the array of property names.
27171 */
27172 function baseKeysIn(object) {
27173 if (!isObject(object)) {
27174 return nativeKeysIn(object);
27175 }
27176 var isProto = isPrototype(object),
27177 result = [];
27178
27179 for (var key in object) {
27180 if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
27181 result.push(key);
27182 }
27183 }
27184 return result;
27185 }
27186
27187 /**
27188 * The base implementation of `_.lt` which doesn't coerce arguments.
27189 *
27190 * @private
27191 * @param {*} value The value to compare.
27192 * @param {*} other The other value to compare.
27193 * @returns {boolean} Returns `true` if `value` is less than `other`,
27194 * else `false`.
27195 */
27196 function baseLt(value, other) {
27197 return value < other;
27198 }
27199
27200 /**
27201 * The base implementation of `_.map` without support for iteratee shorthands.
27202 *
27203 * @private
27204 * @param {Array|Object} collection The collection to iterate over.
27205 * @param {Function} iteratee The function invoked per iteration.
27206 * @returns {Array} Returns the new mapped array.
27207 */
27208 function baseMap(collection, iteratee) {
27209 var index = -1,
27210 result = isArrayLike(collection) ? Array(collection.length) : [];
27211
27212 baseEach(collection, function(value, key, collection) {
27213 result[++index] = iteratee(value, key, collection);
27214 });
27215 return result;
27216 }
27217
27218 /**
27219 * The base implementation of `_.matches` which doesn't clone `source`.
27220 *
27221 * @private
27222 * @param {Object} source The object of property values to match.
27223 * @returns {Function} Returns the new spec function.
27224 */
27225 function baseMatches(source) {
27226 var matchData = getMatchData(source);
27227 if (matchData.length == 1 && matchData[0][2]) {
27228 return matchesStrictComparable(matchData[0][0], matchData[0][1]);
27229 }
27230 return function(object) {
27231 return object === source || baseIsMatch(object, source, matchData);
27232 };
27233 }
27234
27235 /**
27236 * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
27237 *
27238 * @private
27239 * @param {string} path The path of the property to get.
27240 * @param {*} srcValue The value to match.
27241 * @returns {Function} Returns the new spec function.
27242 */
27243 function baseMatchesProperty(path, srcValue) {
27244 if (isKey(path) && isStrictComparable(srcValue)) {
27245 return matchesStrictComparable(toKey(path), srcValue);
27246 }
27247 return function(object) {
27248 var objValue = get(object, path);
27249 return (objValue === undefined && objValue === srcValue)
27250 ? hasIn(object, path)
27251 : baseIsEqual(srcValue, objValue, undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG);
27252 };
27253 }
27254
27255 /**
27256 * The base implementation of `_.merge` without support for multiple sources.
27257 *
27258 * @private
27259 * @param {Object} object The destination object.
27260 * @param {Object} source The source object.
27261 * @param {number} srcIndex The index of `source`.
27262 * @param {Function} [customizer] The function to customize merged values.
27263 * @param {Object} [stack] Tracks traversed source values and their merged
27264 * counterparts.
27265 */
27266 function baseMerge(object, source, srcIndex, customizer, stack) {
27267 if (object === source) {
27268 return;
27269 }
27270 baseFor(source, function(srcValue, key) {
27271 if (isObject(srcValue)) {
27272 stack || (stack = new Stack);
27273 baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
27274 }
27275 else {
27276 var newValue = customizer
27277 ? customizer(object[key], srcValue, (key + ''), object, source, stack)
27278 : undefined;
27279
27280 if (newValue === undefined) {
27281 newValue = srcValue;
27282 }
27283 assignMergeValue(object, key, newValue);
27284 }
27285 }, keysIn);
27286 }
27287
27288 /**
27289 * A specialized version of `baseMerge` for arrays and objects which performs
27290 * deep merges and tracks traversed objects enabling objects with circular
27291 * references to be merged.
27292 *
27293 * @private
27294 * @param {Object} object The destination object.
27295 * @param {Object} source The source object.
27296 * @param {string} key The key of the value to merge.
27297 * @param {number} srcIndex The index of `source`.
27298 * @param {Function} mergeFunc The function to merge values.
27299 * @param {Function} [customizer] The function to customize assigned values.
27300 * @param {Object} [stack] Tracks traversed source values and their merged
27301 * counterparts.
27302 */
27303 function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
27304 var objValue = object[key],
27305 srcValue = source[key],
27306 stacked = stack.get(srcValue);
27307
27308 if (stacked) {
27309 assignMergeValue(object, key, stacked);
27310 return;
27311 }
27312 var newValue = customizer
27313 ? customizer(objValue, srcValue, (key + ''), object, source, stack)
27314 : undefined;
27315
27316 var isCommon = newValue === undefined;
27317
27318 if (isCommon) {
27319 var isArr = isArray(srcValue),
27320 isBuff = !isArr && isBuffer(srcValue),
27321 isTyped = !isArr && !isBuff && isTypedArray(srcValue);
27322
27323 newValue = srcValue;
27324 if (isArr || isBuff || isTyped) {
27325 if (isArray(objValue)) {
27326 newValue = objValue;
27327 }
27328 else if (isArrayLikeObject(objValue)) {
27329 newValue = copyArray(objValue);
27330 }
27331 else if (isBuff) {
27332 isCommon = false;
27333 newValue = cloneBuffer(srcValue, true);
27334 }
27335 else if (isTyped) {
27336 isCommon = false;
27337 newValue = cloneTypedArray(srcValue, true);
27338 }
27339 else {
27340 newValue = [];
27341 }
27342 }
27343 else if (isPlainObject(srcValue) || isArguments(srcValue)) {
27344 newValue = objValue;
27345 if (isArguments(objValue)) {
27346 newValue = toPlainObject(objValue);
27347 }
27348 else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) {
27349 newValue = initCloneObject(srcValue);
27350 }
27351 }
27352 else {
27353 isCommon = false;
27354 }
27355 }
27356 if (isCommon) {
27357 // Recursively merge objects and arrays (susceptible to call stack limits).
27358 stack.set(srcValue, newValue);
27359 mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
27360 stack['delete'](srcValue);
27361 }
27362 assignMergeValue(object, key, newValue);
27363 }
27364
27365 /**
27366 * The base implementation of `_.nth` which doesn't coerce arguments.
27367 *
27368 * @private
27369 * @param {Array} array The array to query.
27370 * @param {number} n The index of the element to return.
27371 * @returns {*} Returns the nth element of `array`.
27372 */
27373 function baseNth(array, n) {
27374 var length = array.length;
27375 if (!length) {
27376 return;
27377 }
27378 n += n < 0 ? length : 0;
27379 return isIndex(n, length) ? array[n] : undefined;
27380 }
27381
27382 /**
27383 * The base implementation of `_.orderBy` without param guards.
27384 *
27385 * @private
27386 * @param {Array|Object} collection The collection to iterate over.
27387 * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
27388 * @param {string[]} orders The sort orders of `iteratees`.
27389 * @returns {Array} Returns the new sorted array.
27390 */
27391 function baseOrderBy(collection, iteratees, orders) {
27392 var index = -1;
27393 iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(getIteratee()));
27394
27395 var result = baseMap(collection, function(value, key, collection) {
27396 var criteria = arrayMap(iteratees, function(iteratee) {
27397 return iteratee(value);
27398 });
27399 return { 'criteria': criteria, 'index': ++index, 'value': value };
27400 });
27401
27402 return baseSortBy(result, function(object, other) {
27403 return compareMultiple(object, other, orders);
27404 });
27405 }
27406
27407 /**
27408 * The base implementation of `_.pick` without support for individual
27409 * property identifiers.
27410 *
27411 * @private
27412 * @param {Object} object The source object.
27413 * @param {string[]} props The property identifiers to pick.
27414 * @returns {Object} Returns the new object.
27415 */
27416 function basePick(object, props) {
27417 object = Object(object);
27418 return basePickBy(object, props, function(value, key) {
27419 return key in object;
27420 });
27421 }
27422
27423 /**
27424 * The base implementation of `_.pickBy` without support for iteratee shorthands.
27425 *
27426 * @private
27427 * @param {Object} object The source object.
27428 * @param {string[]} props The property identifiers to pick from.
27429 * @param {Function} predicate The function invoked per property.
27430 * @returns {Object} Returns the new object.
27431 */
27432 function basePickBy(object, props, predicate) {
27433 var index = -1,
27434 length = props.length,
27435 result = {};
27436
27437 while (++index < length) {
27438 var key = props[index],
27439 value = object[key];
27440
27441 if (predicate(value, key)) {
27442 baseAssignValue(result, key, value);
27443 }
27444 }
27445 return result;
27446 }
27447
27448 /**
27449 * A specialized version of `baseProperty` which supports deep paths.
27450 *
27451 * @private
27452 * @param {Array|string} path The path of the property to get.
27453 * @returns {Function} Returns the new accessor function.
27454 */
27455 function basePropertyDeep(path) {
27456 return function(object) {
27457 return baseGet(object, path);
27458 };
27459 }
27460
27461 /**
27462 * The base implementation of `_.pullAllBy` without support for iteratee
27463 * shorthands.
27464 *
27465 * @private
27466 * @param {Array} array The array to modify.
27467 * @param {Array} values The values to remove.
27468 * @param {Function} [iteratee] The iteratee invoked per element.
27469 * @param {Function} [comparator] The comparator invoked per element.
27470 * @returns {Array} Returns `array`.
27471 */
27472 function basePullAll(array, values, iteratee, comparator) {
27473 var indexOf = comparator ? baseIndexOfWith : baseIndexOf,
27474 index = -1,
27475 length = values.length,
27476 seen = array;
27477
27478 if (array === values) {
27479 values = copyArray(values);
27480 }
27481 if (iteratee) {
27482 seen = arrayMap(array, baseUnary(iteratee));
27483 }
27484 while (++index < length) {
27485 var fromIndex = 0,
27486 value = values[index],
27487 computed = iteratee ? iteratee(value) : value;
27488
27489 while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) {
27490 if (seen !== array) {
27491 splice.call(seen, fromIndex, 1);
27492 }
27493 splice.call(array, fromIndex, 1);
27494 }
27495 }
27496 return array;
27497 }
27498
27499 /**
27500 * The base implementation of `_.pullAt` without support for individual
27501 * indexes or capturing the removed elements.
27502 *
27503 * @private
27504 * @param {Array} array The array to modify.
27505 * @param {number[]} indexes The indexes of elements to remove.
27506 * @returns {Array} Returns `array`.
27507 */
27508 function basePullAt(array, indexes) {
27509 var length = array ? indexes.length : 0,
27510 lastIndex = length - 1;
27511
27512 while (length--) {
27513 var index = indexes[length];
27514 if (length == lastIndex || index !== previous) {
27515 var previous = index;
27516 if (isIndex(index)) {
27517 splice.call(array, index, 1);
27518 }
27519 else if (!isKey(index, array)) {
27520 var path = castPath(index),
27521 object = parent(array, path);
27522
27523 if (object != null) {
27524 delete object[toKey(last(path))];
27525 }
27526 }
27527 else {
27528 delete array[toKey(index)];
27529 }
27530 }
27531 }
27532 return array;
27533 }
27534
27535 /**
27536 * The base implementation of `_.random` without support for returning
27537 * floating-point numbers.
27538 *
27539 * @private
27540 * @param {number} lower The lower bound.
27541 * @param {number} upper The upper bound.
27542 * @returns {number} Returns the random number.
27543 */
27544 function baseRandom(lower, upper) {
27545 return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
27546 }
27547
27548 /**
27549 * The base implementation of `_.range` and `_.rangeRight` which doesn't
27550 * coerce arguments.
27551 *
27552 * @private
27553 * @param {number} start The start of the range.
27554 * @param {number} end The end of the range.
27555 * @param {number} step The value to increment or decrement by.
27556 * @param {boolean} [fromRight] Specify iterating from right to left.
27557 * @returns {Array} Returns the range of numbers.
27558 */
27559 function baseRange(start, end, step, fromRight) {
27560 var index = -1,
27561 length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
27562 result = Array(length);
27563
27564 while (length--) {
27565 result[fromRight ? length : ++index] = start;
27566 start += step;
27567 }
27568 return result;
27569 }
27570
27571 /**
27572 * The base implementation of `_.repeat` which doesn't coerce arguments.
27573 *
27574 * @private
27575 * @param {string} string The string to repeat.
27576 * @param {number} n The number of times to repeat the string.
27577 * @returns {string} Returns the repeated string.
27578 */
27579 function baseRepeat(string, n) {
27580 var result = '';
27581 if (!string || n < 1 || n > MAX_SAFE_INTEGER) {
27582 return result;
27583 }
27584 // Leverage the exponentiation by squaring algorithm for a faster repeat.
27585 // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
27586 do {
27587 if (n % 2) {
27588 result += string;
27589 }
27590 n = nativeFloor(n / 2);
27591 if (n) {
27592 string += string;
27593 }
27594 } while (n);
27595
27596 return result;
27597 }
27598
27599 /**
27600 * The base implementation of `_.rest` which doesn't validate or coerce arguments.
27601 *
27602 * @private
27603 * @param {Function} func The function to apply a rest parameter to.
27604 * @param {number} [start=func.length-1] The start position of the rest parameter.
27605 * @returns {Function} Returns the new function.
27606 */
27607 function baseRest(func, start) {
27608 return setToString(overRest(func, start, identity), func + '');
27609 }
27610
27611 /**
27612 * The base implementation of `_.sample`.
27613 *
27614 * @private
27615 * @param {Array|Object} collection The collection to sample.
27616 * @returns {*} Returns the random element.
27617 */
27618 function baseSample(collection) {
27619 return arraySample(values(collection));
27620 }
27621
27622 /**
27623 * The base implementation of `_.sampleSize` without param guards.
27624 *
27625 * @private
27626 * @param {Array|Object} collection The collection to sample.
27627 * @param {number} n The number of elements to sample.
27628 * @returns {Array} Returns the random elements.
27629 */
27630 function baseSampleSize(collection, n) {
27631 var array = values(collection);
27632 return shuffleSelf(array, baseClamp(n, 0, array.length));
27633 }
27634
27635 /**
27636 * The base implementation of `_.set`.
27637 *
27638 * @private
27639 * @param {Object} object The object to modify.
27640 * @param {Array|string} path The path of the property to set.
27641 * @param {*} value The value to set.
27642 * @param {Function} [customizer] The function to customize path creation.
27643 * @returns {Object} Returns `object`.
27644 */
27645 function baseSet(object, path, value, customizer) {
27646 if (!isObject(object)) {
27647 return object;
27648 }
27649 path = isKey(path, object) ? [path] : castPath(path);
27650
27651 var index = -1,
27652 length = path.length,
27653 lastIndex = length - 1,
27654 nested = object;
27655
27656 while (nested != null && ++index < length) {
27657 var key = toKey(path[index]),
27658 newValue = value;
27659
27660 if (index != lastIndex) {
27661 var objValue = nested[key];
27662 newValue = customizer ? customizer(objValue, key, nested) : undefined;
27663 if (newValue === undefined) {
27664 newValue = isObject(objValue)
27665 ? objValue
27666 : (isIndex(path[index + 1]) ? [] : {});
27667 }
27668 }
27669 assignValue(nested, key, newValue);
27670 nested = nested[key];
27671 }
27672 return object;
27673 }
27674
27675 /**
27676 * The base implementation of `setData` without support for hot loop shorting.
27677 *
27678 * @private
27679 * @param {Function} func The function to associate metadata with.
27680 * @param {*} data The metadata.
27681 * @returns {Function} Returns `func`.
27682 */
27683 var baseSetData = !metaMap ? identity : function(func, data) {
27684 metaMap.set(func, data);
27685 return func;
27686 };
27687
27688 /**
27689 * The base implementation of `setToString` without support for hot loop shorting.
27690 *
27691 * @private
27692 * @param {Function} func The function to modify.
27693 * @param {Function} string The `toString` result.
27694 * @returns {Function} Returns `func`.
27695 */
27696 var baseSetToString = !defineProperty ? identity : function(func, string) {
27697 return defineProperty(func, 'toString', {
27698 'configurable': true,
27699 'enumerable': false,
27700 'value': constant(string),
27701 'writable': true
27702 });
27703 };
27704
27705 /**
27706 * The base implementation of `_.shuffle`.
27707 *
27708 * @private
27709 * @param {Array|Object} collection The collection to shuffle.
27710 * @returns {Array} Returns the new shuffled array.
27711 */
27712 function baseShuffle(collection) {
27713 return shuffleSelf(values(collection));
27714 }
27715
27716 /**
27717 * The base implementation of `_.slice` without an iteratee call guard.
27718 *
27719 * @private
27720 * @param {Array} array The array to slice.
27721 * @param {number} [start=0] The start position.
27722 * @param {number} [end=array.length] The end position.
27723 * @returns {Array} Returns the slice of `array`.
27724 */
27725 function baseSlice(array, start, end) {
27726 var index = -1,
27727 length = array.length;
27728
27729 if (start < 0) {
27730 start = -start > length ? 0 : (length + start);
27731 }
27732 end = end > length ? length : end;
27733 if (end < 0) {
27734 end += length;
27735 }
27736 length = start > end ? 0 : ((end - start) >>> 0);
27737 start >>>= 0;
27738
27739 var result = Array(length);
27740 while (++index < length) {
27741 result[index] = array[index + start];
27742 }
27743 return result;
27744 }
27745
27746 /**
27747 * The base implementation of `_.some` without support for iteratee shorthands.
27748 *
27749 * @private
27750 * @param {Array|Object} collection The collection to iterate over.
27751 * @param {Function} predicate The function invoked per iteration.
27752 * @returns {boolean} Returns `true` if any element passes the predicate check,
27753 * else `false`.
27754 */
27755 function baseSome(collection, predicate) {
27756 var result;
27757
27758 baseEach(collection, function(value, index, collection) {
27759 result = predicate(value, index, collection);
27760 return !result;
27761 });
27762 return !!result;
27763 }
27764
27765 /**
27766 * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which
27767 * performs a binary search of `array` to determine the index at which `value`
27768 * should be inserted into `array` in order to maintain its sort order.
27769 *
27770 * @private
27771 * @param {Array} array The sorted array to inspect.
27772 * @param {*} value The value to evaluate.
27773 * @param {boolean} [retHighest] Specify returning the highest qualified index.
27774 * @returns {number} Returns the index at which `value` should be inserted
27775 * into `array`.
27776 */
27777 function baseSortedIndex(array, value, retHighest) {
27778 var low = 0,
27779 high = array ? array.length : low;
27780
27781 if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
27782 while (low < high) {
27783 var mid = (low + high) >>> 1,
27784 computed = array[mid];
27785
27786 if (computed !== null && !isSymbol(computed) &&
27787 (retHighest ? (computed <= value) : (computed < value))) {
27788 low = mid + 1;
27789 } else {
27790 high = mid;
27791 }
27792 }
27793 return high;
27794 }
27795 return baseSortedIndexBy(array, value, identity, retHighest);
27796 }
27797
27798 /**
27799 * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy`
27800 * which invokes `iteratee` for `value` and each element of `array` to compute
27801 * their sort ranking. The iteratee is invoked with one argument; (value).
27802 *
27803 * @private
27804 * @param {Array} array The sorted array to inspect.
27805 * @param {*} value The value to evaluate.
27806 * @param {Function} iteratee The iteratee invoked per element.
27807 * @param {boolean} [retHighest] Specify returning the highest qualified index.
27808 * @returns {number} Returns the index at which `value` should be inserted
27809 * into `array`.
27810 */
27811 function baseSortedIndexBy(array, value, iteratee, retHighest) {
27812 value = iteratee(value);
27813
27814 var low = 0,
27815 high = array ? array.length : 0,
27816 valIsNaN = value !== value,
27817 valIsNull = value === null,
27818 valIsSymbol = isSymbol(value),
27819 valIsUndefined = value === undefined;
27820
27821 while (low < high) {
27822 var mid = nativeFloor((low + high) / 2),
27823 computed = iteratee(array[mid]),
27824 othIsDefined = computed !== undefined,
27825 othIsNull = computed === null,
27826 othIsReflexive = computed === computed,
27827 othIsSymbol = isSymbol(computed);
27828
27829 if (valIsNaN) {
27830 var setLow = retHighest || othIsReflexive;
27831 } else if (valIsUndefined) {
27832 setLow = othIsReflexive && (retHighest || othIsDefined);
27833 } else if (valIsNull) {
27834 setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull);
27835 } else if (valIsSymbol) {
27836 setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol);
27837 } else if (othIsNull || othIsSymbol) {
27838 setLow = false;
27839 } else {
27840 setLow = retHighest ? (computed <= value) : (computed < value);
27841 }
27842 if (setLow) {
27843 low = mid + 1;
27844 } else {
27845 high = mid;
27846 }
27847 }
27848 return nativeMin(high, MAX_ARRAY_INDEX);
27849 }
27850
27851 /**
27852 * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without
27853 * support for iteratee shorthands.
27854 *
27855 * @private
27856 * @param {Array} array The array to inspect.
27857 * @param {Function} [iteratee] The iteratee invoked per element.
27858 * @returns {Array} Returns the new duplicate free array.
27859 */
27860 function baseSortedUniq(array, iteratee) {
27861 var index = -1,
27862 length = array.length,
27863 resIndex = 0,
27864 result = [];
27865
27866 while (++index < length) {
27867 var value = array[index],
27868 computed = iteratee ? iteratee(value) : value;
27869
27870 if (!index || !eq(computed, seen)) {
27871 var seen = computed;
27872 result[resIndex++] = value === 0 ? 0 : value;
27873 }
27874 }
27875 return result;
27876 }
27877
27878 /**
27879 * The base implementation of `_.toNumber` which doesn't ensure correct
27880 * conversions of binary, hexadecimal, or octal string values.
27881 *
27882 * @private
27883 * @param {*} value The value to process.
27884 * @returns {number} Returns the number.
27885 */
27886 function baseToNumber(value) {
27887 if (typeof value == 'number') {
27888 return value;
27889 }
27890 if (isSymbol(value)) {
27891 return NAN;
27892 }
27893 return +value;
27894 }
27895
27896 /**
27897 * The base implementation of `_.toString` which doesn't convert nullish
27898 * values to empty strings.
27899 *
27900 * @private
27901 * @param {*} value The value to process.
27902 * @returns {string} Returns the string.
27903 */
27904 function baseToString(value) {
27905 // Exit early for strings to avoid a performance hit in some environments.
27906 if (typeof value == 'string') {
27907 return value;
27908 }
27909 if (isArray(value)) {
27910 // Recursively convert values (susceptible to call stack limits).
27911 return arrayMap(value, baseToString) + '';
27912 }
27913 if (isSymbol(value)) {
27914 return symbolToString ? symbolToString.call(value) : '';
27915 }
27916 var result = (value + '');
27917 return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
27918 }
27919
27920 /**
27921 * The base implementation of `_.uniqBy` without support for iteratee shorthands.
27922 *
27923 * @private
27924 * @param {Array} array The array to inspect.
27925 * @param {Function} [iteratee] The iteratee invoked per element.
27926 * @param {Function} [comparator] The comparator invoked per element.
27927 * @returns {Array} Returns the new duplicate free array.
27928 */
27929 function baseUniq(array, iteratee, comparator) {
27930 var index = -1,
27931 includes = arrayIncludes,
27932 length = array.length,
27933 isCommon = true,
27934 result = [],
27935 seen = result;
27936
27937 if (comparator) {
27938 isCommon = false;
27939 includes = arrayIncludesWith;
27940 }
27941 else if (length >= LARGE_ARRAY_SIZE) {
27942 var set = iteratee ? null : createSet(array);
27943 if (set) {
27944 return setToArray(set);
27945 }
27946 isCommon = false;
27947 includes = cacheHas;
27948 seen = new SetCache;
27949 }
27950 else {
27951 seen = iteratee ? [] : result;
27952 }
27953 outer:
27954 while (++index < length) {
27955 var value = array[index],
27956 computed = iteratee ? iteratee(value) : value;
27957
27958 value = (comparator || value !== 0) ? value : 0;
27959 if (isCommon && computed === computed) {
27960 var seenIndex = seen.length;
27961 while (seenIndex--) {
27962 if (seen[seenIndex] === computed) {
27963 continue outer;
27964 }
27965 }
27966 if (iteratee) {
27967 seen.push(computed);
27968 }
27969 result.push(value);
27970 }
27971 else if (!includes(seen, computed, comparator)) {
27972 if (seen !== result) {
27973 seen.push(computed);
27974 }
27975 result.push(value);
27976 }
27977 }
27978 return result;
27979 }
27980
27981 /**
27982 * The base implementation of `_.unset`.
27983 *
27984 * @private
27985 * @param {Object} object The object to modify.
27986 * @param {Array|string} path The path of the property to unset.
27987 * @returns {boolean} Returns `true` if the property is deleted, else `false`.
27988 */
27989 function baseUnset(object, path) {
27990 path = isKey(path, object) ? [path] : castPath(path);
27991 object = parent(object, path);
27992
27993 var key = toKey(last(path));
27994 return !(object != null && hasOwnProperty.call(object, key)) || delete object[key];
27995 }
27996
27997 /**
27998 * The base implementation of `_.update`.
27999 *
28000 * @private
28001 * @param {Object} object The object to modify.
28002 * @param {Array|string} path The path of the property to update.
28003 * @param {Function} updater The function to produce the updated value.
28004 * @param {Function} [customizer] The function to customize path creation.
28005 * @returns {Object} Returns `object`.
28006 */
28007 function baseUpdate(object, path, updater, customizer) {
28008 return baseSet(object, path, updater(baseGet(object, path)), customizer);
28009 }
28010
28011 /**
28012 * The base implementation of methods like `_.dropWhile` and `_.takeWhile`
28013 * without support for iteratee shorthands.
28014 *
28015 * @private
28016 * @param {Array} array The array to query.
28017 * @param {Function} predicate The function invoked per iteration.
28018 * @param {boolean} [isDrop] Specify dropping elements instead of taking them.
28019 * @param {boolean} [fromRight] Specify iterating from right to left.
28020 * @returns {Array} Returns the slice of `array`.
28021 */
28022 function baseWhile(array, predicate, isDrop, fromRight) {
28023 var length = array.length,
28024 index = fromRight ? length : -1;
28025
28026 while ((fromRight ? index-- : ++index < length) &&
28027 predicate(array[index], index, array)) {}
28028
28029 return isDrop
28030 ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))
28031 : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));
28032 }
28033
28034 /**
28035 * The base implementation of `wrapperValue` which returns the result of
28036 * performing a sequence of actions on the unwrapped `value`, where each
28037 * successive action is supplied the return value of the previous.
28038 *
28039 * @private
28040 * @param {*} value The unwrapped value.
28041 * @param {Array} actions Actions to perform to resolve the unwrapped value.
28042 * @returns {*} Returns the resolved value.
28043 */
28044 function baseWrapperValue(value, actions) {
28045 var result = value;
28046 if (result instanceof LazyWrapper) {
28047 result = result.value();
28048 }
28049 return arrayReduce(actions, function(result, action) {
28050 return action.func.apply(action.thisArg, arrayPush([result], action.args));
28051 }, result);
28052 }
28053
28054 /**
28055 * The base implementation of methods like `_.xor`, without support for
28056 * iteratee shorthands, that accepts an array of arrays to inspect.
28057 *
28058 * @private
28059 * @param {Array} arrays The arrays to inspect.
28060 * @param {Function} [iteratee] The iteratee invoked per element.
28061 * @param {Function} [comparator] The comparator invoked per element.
28062 * @returns {Array} Returns the new array of values.
28063 */
28064 function baseXor(arrays, iteratee, comparator) {
28065 var index = -1,
28066 length = arrays.length;
28067
28068 while (++index < length) {
28069 var result = result
28070 ? arrayPush(
28071 baseDifference(result, arrays[index], iteratee, comparator),
28072 baseDifference(arrays[index], result, iteratee, comparator)
28073 )
28074 : arrays[index];
28075 }
28076 return (result && result.length) ? baseUniq(result, iteratee, comparator) : [];
28077 }
28078
28079 /**
28080 * This base implementation of `_.zipObject` which assigns values using `assignFunc`.
28081 *
28082 * @private
28083 * @param {Array} props The property identifiers.
28084 * @param {Array} values The property values.
28085 * @param {Function} assignFunc The function to assign values.
28086 * @returns {Object} Returns the new object.
28087 */
28088 function baseZipObject(props, values, assignFunc) {
28089 var index = -1,
28090 length = props.length,
28091 valsLength = values.length,
28092 result = {};
28093
28094 while (++index < length) {
28095 var value = index < valsLength ? values[index] : undefined;
28096 assignFunc(result, props[index], value);
28097 }
28098 return result;
28099 }
28100
28101 /**
28102 * Casts `value` to an empty array if it's not an array like object.
28103 *
28104 * @private
28105 * @param {*} value The value to inspect.
28106 * @returns {Array|Object} Returns the cast array-like object.
28107 */
28108 function castArrayLikeObject(value) {
28109 return isArrayLikeObject(value) ? value : [];
28110 }
28111
28112 /**
28113 * Casts `value` to `identity` if it's not a function.
28114 *
28115 * @private
28116 * @param {*} value The value to inspect.
28117 * @returns {Function} Returns cast function.
28118 */
28119 function castFunction(value) {
28120 return typeof value == 'function' ? value : identity;
28121 }
28122
28123 /**
28124 * Casts `value` to a path array if it's not one.
28125 *
28126 * @private
28127 * @param {*} value The value to inspect.
28128 * @returns {Array} Returns the cast property path array.
28129 */
28130 function castPath(value) {
28131 return isArray(value) ? value : stringToPath(value);
28132 }
28133
28134 /**
28135 * A `baseRest` alias which can be replaced with `identity` by module
28136 * replacement plugins.
28137 *
28138 * @private
28139 * @type {Function}
28140 * @param {Function} func The function to apply a rest parameter to.
28141 * @returns {Function} Returns the new function.
28142 */
28143 var castRest = baseRest;
28144
28145 /**
28146 * Casts `array` to a slice if it's needed.
28147 *
28148 * @private
28149 * @param {Array} array The array to inspect.
28150 * @param {number} start The start position.
28151 * @param {number} [end=array.length] The end position.
28152 * @returns {Array} Returns the cast slice.
28153 */
28154 function castSlice(array, start, end) {
28155 var length = array.length;
28156 end = end === undefined ? length : end;
28157 return (!start && end >= length) ? array : baseSlice(array, start, end);
28158 }
28159
28160 /**
28161 * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout).
28162 *
28163 * @private
28164 * @param {number|Object} id The timer id or timeout object of the timer to clear.
28165 */
28166 var clearTimeout = ctxClearTimeout || function(id) {
28167 return root.clearTimeout(id);
28168 };
28169
28170 /**
28171 * Creates a clone of `buffer`.
28172 *
28173 * @private
28174 * @param {Buffer} buffer The buffer to clone.
28175 * @param {boolean} [isDeep] Specify a deep clone.
28176 * @returns {Buffer} Returns the cloned buffer.
28177 */
28178 function cloneBuffer(buffer, isDeep) {
28179 if (isDeep) {
28180 return buffer.slice();
28181 }
28182 var length = buffer.length,
28183 result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
28184
28185 buffer.copy(result);
28186 return result;
28187 }
28188
28189 /**
28190 * Creates a clone of `arrayBuffer`.
28191 *
28192 * @private
28193 * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
28194 * @returns {ArrayBuffer} Returns the cloned array buffer.
28195 */
28196 function cloneArrayBuffer(arrayBuffer) {
28197 var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
28198 new Uint8Array(result).set(new Uint8Array(arrayBuffer));
28199 return result;
28200 }
28201
28202 /**
28203 * Creates a clone of `dataView`.
28204 *
28205 * @private
28206 * @param {Object} dataView The data view to clone.
28207 * @param {boolean} [isDeep] Specify a deep clone.
28208 * @returns {Object} Returns the cloned data view.
28209 */
28210 function cloneDataView(dataView, isDeep) {
28211 var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
28212 return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
28213 }
28214
28215 /**
28216 * Creates a clone of `map`.
28217 *
28218 * @private
28219 * @param {Object} map The map to clone.
28220 * @param {Function} cloneFunc The function to clone values.
28221 * @param {boolean} [isDeep] Specify a deep clone.
28222 * @returns {Object} Returns the cloned map.
28223 */
28224 function cloneMap(map, isDeep, cloneFunc) {
28225 var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map);
28226 return arrayReduce(array, addMapEntry, new map.constructor);
28227 }
28228
28229 /**
28230 * Creates a clone of `regexp`.
28231 *
28232 * @private
28233 * @param {Object} regexp The regexp to clone.
28234 * @returns {Object} Returns the cloned regexp.
28235 */
28236 function cloneRegExp(regexp) {
28237 var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
28238 result.lastIndex = regexp.lastIndex;
28239 return result;
28240 }
28241
28242 /**
28243 * Creates a clone of `set`.
28244 *
28245 * @private
28246 * @param {Object} set The set to clone.
28247 * @param {Function} cloneFunc The function to clone values.
28248 * @param {boolean} [isDeep] Specify a deep clone.
28249 * @returns {Object} Returns the cloned set.
28250 */
28251 function cloneSet(set, isDeep, cloneFunc) {
28252 var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set);
28253 return arrayReduce(array, addSetEntry, new set.constructor);
28254 }
28255
28256 /**
28257 * Creates a clone of the `symbol` object.
28258 *
28259 * @private
28260 * @param {Object} symbol The symbol object to clone.
28261 * @returns {Object} Returns the cloned symbol object.
28262 */
28263 function cloneSymbol(symbol) {
28264 return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
28265 }
28266
28267 /**
28268 * Creates a clone of `typedArray`.
28269 *
28270 * @private
28271 * @param {Object} typedArray The typed array to clone.
28272 * @param {boolean} [isDeep] Specify a deep clone.
28273 * @returns {Object} Returns the cloned typed array.
28274 */
28275 function cloneTypedArray(typedArray, isDeep) {
28276 var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
28277 return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
28278 }
28279
28280 /**
28281 * Compares values to sort them in ascending order.
28282 *
28283 * @private
28284 * @param {*} value The value to compare.
28285 * @param {*} other The other value to compare.
28286 * @returns {number} Returns the sort order indicator for `value`.
28287 */
28288 function compareAscending(value, other) {
28289 if (value !== other) {
28290 var valIsDefined = value !== undefined,
28291 valIsNull = value === null,
28292 valIsReflexive = value === value,
28293 valIsSymbol = isSymbol(value);
28294
28295 var othIsDefined = other !== undefined,
28296 othIsNull = other === null,
28297 othIsReflexive = other === other,
28298 othIsSymbol = isSymbol(other);
28299
28300 if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||
28301 (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||
28302 (valIsNull && othIsDefined && othIsReflexive) ||
28303 (!valIsDefined && othIsReflexive) ||
28304 !valIsReflexive) {
28305 return 1;
28306 }
28307 if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||
28308 (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||
28309 (othIsNull && valIsDefined && valIsReflexive) ||
28310 (!othIsDefined && valIsReflexive) ||
28311 !othIsReflexive) {
28312 return -1;
28313 }
28314 }
28315 return 0;
28316 }
28317
28318 /**
28319 * Used by `_.orderBy` to compare multiple properties of a value to another
28320 * and stable sort them.
28321 *
28322 * If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
28323 * specify an order of "desc" for descending or "asc" for ascending sort order
28324 * of corresponding values.
28325 *
28326 * @private
28327 * @param {Object} object The object to compare.
28328 * @param {Object} other The other object to compare.
28329 * @param {boolean[]|string[]} orders The order to sort by for each property.
28330 * @returns {number} Returns the sort order indicator for `object`.
28331 */
28332 function compareMultiple(object, other, orders) {
28333 var index = -1,
28334 objCriteria = object.criteria,
28335 othCriteria = other.criteria,
28336 length = objCriteria.length,
28337 ordersLength = orders.length;
28338
28339 while (++index < length) {
28340 var result = compareAscending(objCriteria[index], othCriteria[index]);
28341 if (result) {
28342 if (index >= ordersLength) {
28343 return result;
28344 }
28345 var order = orders[index];
28346 return result * (order == 'desc' ? -1 : 1);
28347 }
28348 }
28349 // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
28350 // that causes it, under certain circumstances, to provide the same value for
28351 // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
28352 // for more details.
28353 //
28354 // This also ensures a stable sort in V8 and other engines.
28355 // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
28356 return object.index - other.index;
28357 }
28358
28359 /**
28360 * Creates an array that is the composition of partially applied arguments,
28361 * placeholders, and provided arguments into a single array of arguments.
28362 *
28363 * @private
28364 * @param {Array} args The provided arguments.
28365 * @param {Array} partials The arguments to prepend to those provided.
28366 * @param {Array} holders The `partials` placeholder indexes.
28367 * @params {boolean} [isCurried] Specify composing for a curried function.
28368 * @returns {Array} Returns the new array of composed arguments.
28369 */
28370 function composeArgs(args, partials, holders, isCurried) {
28371 var argsIndex = -1,
28372 argsLength = args.length,
28373 holdersLength = holders.length,
28374 leftIndex = -1,
28375 leftLength = partials.length,
28376 rangeLength = nativeMax(argsLength - holdersLength, 0),
28377 result = Array(leftLength + rangeLength),
28378 isUncurried = !isCurried;
28379
28380 while (++leftIndex < leftLength) {
28381 result[leftIndex] = partials[leftIndex];
28382 }
28383 while (++argsIndex < holdersLength) {
28384 if (isUncurried || argsIndex < argsLength) {
28385 result[holders[argsIndex]] = args[argsIndex];
28386 }
28387 }
28388 while (rangeLength--) {
28389 result[leftIndex++] = args[argsIndex++];
28390 }
28391 return result;
28392 }
28393
28394 /**
28395 * This function is like `composeArgs` except that the arguments composition
28396 * is tailored for `_.partialRight`.
28397 *
28398 * @private
28399 * @param {Array} args The provided arguments.
28400 * @param {Array} partials The arguments to append to those provided.
28401 * @param {Array} holders The `partials` placeholder indexes.
28402 * @params {boolean} [isCurried] Specify composing for a curried function.
28403 * @returns {Array} Returns the new array of composed arguments.
28404 */
28405 function composeArgsRight(args, partials, holders, isCurried) {
28406 var argsIndex = -1,
28407 argsLength = args.length,
28408 holdersIndex = -1,
28409 holdersLength = holders.length,
28410 rightIndex = -1,
28411 rightLength = partials.length,
28412 rangeLength = nativeMax(argsLength - holdersLength, 0),
28413 result = Array(rangeLength + rightLength),
28414 isUncurried = !isCurried;
28415
28416 while (++argsIndex < rangeLength) {
28417 result[argsIndex] = args[argsIndex];
28418 }
28419 var offset = argsIndex;
28420 while (++rightIndex < rightLength) {
28421 result[offset + rightIndex] = partials[rightIndex];
28422 }
28423 while (++holdersIndex < holdersLength) {
28424 if (isUncurried || argsIndex < argsLength) {
28425 result[offset + holders[holdersIndex]] = args[argsIndex++];
28426 }
28427 }
28428 return result;
28429 }
28430
28431 /**
28432 * Copies the values of `source` to `array`.
28433 *
28434 * @private
28435 * @param {Array} source The array to copy values from.
28436 * @param {Array} [array=[]] The array to copy values to.
28437 * @returns {Array} Returns `array`.
28438 */
28439 function copyArray(source, array) {
28440 var index = -1,
28441 length = source.length;
28442
28443 array || (array = Array(length));
28444 while (++index < length) {
28445 array[index] = source[index];
28446 }
28447 return array;
28448 }
28449
28450 /**
28451 * Copies properties of `source` to `object`.
28452 *
28453 * @private
28454 * @param {Object} source The object to copy properties from.
28455 * @param {Array} props The property identifiers to copy.
28456 * @param {Object} [object={}] The object to copy properties to.
28457 * @param {Function} [customizer] The function to customize copied values.
28458 * @returns {Object} Returns `object`.
28459 */
28460 function copyObject(source, props, object, customizer) {
28461 var isNew = !object;
28462 object || (object = {});
28463
28464 var index = -1,
28465 length = props.length;
28466
28467 while (++index < length) {
28468 var key = props[index];
28469
28470 var newValue = customizer
28471 ? customizer(object[key], source[key], key, object, source)
28472 : undefined;
28473
28474 if (newValue === undefined) {
28475 newValue = source[key];
28476 }
28477 if (isNew) {
28478 baseAssignValue(object, key, newValue);
28479 } else {
28480 assignValue(object, key, newValue);
28481 }
28482 }
28483 return object;
28484 }
28485
28486 /**
28487 * Copies own symbol properties of `source` to `object`.
28488 *
28489 * @private
28490 * @param {Object} source The object to copy symbols from.
28491 * @param {Object} [object={}] The object to copy symbols to.
28492 * @returns {Object} Returns `object`.
28493 */
28494 function copySymbols(source, object) {
28495 return copyObject(source, getSymbols(source), object);
28496 }
28497
28498 /**
28499 * Creates a function like `_.groupBy`.
28500 *
28501 * @private
28502 * @param {Function} setter The function to set accumulator values.
28503 * @param {Function} [initializer] The accumulator object initializer.
28504 * @returns {Function} Returns the new aggregator function.
28505 */
28506 function createAggregator(setter, initializer) {
28507 return function(collection, iteratee) {
28508 var func = isArray(collection) ? arrayAggregator : baseAggregator,
28509 accumulator = initializer ? initializer() : {};
28510
28511 return func(collection, setter, getIteratee(iteratee, 2), accumulator);
28512 };
28513 }
28514
28515 /**
28516 * Creates a function like `_.assign`.
28517 *
28518 * @private
28519 * @param {Function} assigner The function to assign values.
28520 * @returns {Function} Returns the new assigner function.
28521 */
28522 function createAssigner(assigner) {
28523 return baseRest(function(object, sources) {
28524 var index = -1,
28525 length = sources.length,
28526 customizer = length > 1 ? sources[length - 1] : undefined,
28527 guard = length > 2 ? sources[2] : undefined;
28528
28529 customizer = (assigner.length > 3 && typeof customizer == 'function')
28530 ? (length--, customizer)
28531 : undefined;
28532
28533 if (guard && isIterateeCall(sources[0], sources[1], guard)) {
28534 customizer = length < 3 ? undefined : customizer;
28535 length = 1;
28536 }
28537 object = Object(object);
28538 while (++index < length) {
28539 var source = sources[index];
28540 if (source) {
28541 assigner(object, source, index, customizer);
28542 }
28543 }
28544 return object;
28545 });
28546 }
28547
28548 /**
28549 * Creates a `baseEach` or `baseEachRight` function.
28550 *
28551 * @private
28552 * @param {Function} eachFunc The function to iterate over a collection.
28553 * @param {boolean} [fromRight] Specify iterating from right to left.
28554 * @returns {Function} Returns the new base function.
28555 */
28556 function createBaseEach(eachFunc, fromRight) {
28557 return function(collection, iteratee) {
28558 if (collection == null) {
28559 return collection;
28560 }
28561 if (!isArrayLike(collection)) {
28562 return eachFunc(collection, iteratee);
28563 }
28564 var length = collection.length,
28565 index = fromRight ? length : -1,
28566 iterable = Object(collection);
28567
28568 while ((fromRight ? index-- : ++index < length)) {
28569 if (iteratee(iterable[index], index, iterable) === false) {
28570 break;
28571 }
28572 }
28573 return collection;
28574 };
28575 }
28576
28577 /**
28578 * Creates a base function for methods like `_.forIn` and `_.forOwn`.
28579 *
28580 * @private
28581 * @param {boolean} [fromRight] Specify iterating from right to left.
28582 * @returns {Function} Returns the new base function.
28583 */
28584 function createBaseFor(fromRight) {
28585 return function(object, iteratee, keysFunc) {
28586 var index = -1,
28587 iterable = Object(object),
28588 props = keysFunc(object),
28589 length = props.length;
28590
28591 while (length--) {
28592 var key = props[fromRight ? length : ++index];
28593 if (iteratee(iterable[key], key, iterable) === false) {
28594 break;
28595 }
28596 }
28597 return object;
28598 };
28599 }
28600
28601 /**
28602 * Creates a function that wraps `func` to invoke it with the optional `this`
28603 * binding of `thisArg`.
28604 *
28605 * @private
28606 * @param {Function} func The function to wrap.
28607 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
28608 * @param {*} [thisArg] The `this` binding of `func`.
28609 * @returns {Function} Returns the new wrapped function.
28610 */
28611 function createBind(func, bitmask, thisArg) {
28612 var isBind = bitmask & BIND_FLAG,
28613 Ctor = createCtor(func);
28614
28615 function wrapper() {
28616 var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
28617 return fn.apply(isBind ? thisArg : this, arguments);
28618 }
28619 return wrapper;
28620 }
28621
28622 /**
28623 * Creates a function like `_.lowerFirst`.
28624 *
28625 * @private
28626 * @param {string} methodName The name of the `String` case method to use.
28627 * @returns {Function} Returns the new case function.
28628 */
28629 function createCaseFirst(methodName) {
28630 return function(string) {
28631 string = toString(string);
28632
28633 var strSymbols = hasUnicode(string)
28634 ? stringToArray(string)
28635 : undefined;
28636
28637 var chr = strSymbols
28638 ? strSymbols[0]
28639 : string.charAt(0);
28640
28641 var trailing = strSymbols
28642 ? castSlice(strSymbols, 1).join('')
28643 : string.slice(1);
28644
28645 return chr[methodName]() + trailing;
28646 };
28647 }
28648
28649 /**
28650 * Creates a function like `_.camelCase`.
28651 *
28652 * @private
28653 * @param {Function} callback The function to combine each word.
28654 * @returns {Function} Returns the new compounder function.
28655 */
28656 function createCompounder(callback) {
28657 return function(string) {
28658 return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
28659 };
28660 }
28661
28662 /**
28663 * Creates a function that produces an instance of `Ctor` regardless of
28664 * whether it was invoked as part of a `new` expression or by `call` or `apply`.
28665 *
28666 * @private
28667 * @param {Function} Ctor The constructor to wrap.
28668 * @returns {Function} Returns the new wrapped function.
28669 */
28670 function createCtor(Ctor) {
28671 return function() {
28672 // Use a `switch` statement to work with class constructors. See
28673 // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
28674 // for more details.
28675 var args = arguments;
28676 switch (args.length) {
28677 case 0: return new Ctor;
28678 case 1: return new Ctor(args[0]);
28679 case 2: return new Ctor(args[0], args[1]);
28680 case 3: return new Ctor(args[0], args[1], args[2]);
28681 case 4: return new Ctor(args[0], args[1], args[2], args[3]);
28682 case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
28683 case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
28684 case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
28685 }
28686 var thisBinding = baseCreate(Ctor.prototype),
28687 result = Ctor.apply(thisBinding, args);
28688
28689 // Mimic the constructor's `return` behavior.
28690 // See https://es5.github.io/#x13.2.2 for more details.
28691 return isObject(result) ? result : thisBinding;
28692 };
28693 }
28694
28695 /**
28696 * Creates a function that wraps `func` to enable currying.
28697 *
28698 * @private
28699 * @param {Function} func The function to wrap.
28700 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
28701 * @param {number} arity The arity of `func`.
28702 * @returns {Function} Returns the new wrapped function.
28703 */
28704 function createCurry(func, bitmask, arity) {
28705 var Ctor = createCtor(func);
28706
28707 function wrapper() {
28708 var length = arguments.length,
28709 args = Array(length),
28710 index = length,
28711 placeholder = getHolder(wrapper);
28712
28713 while (index--) {
28714 args[index] = arguments[index];
28715 }
28716 var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
28717 ? []
28718 : replaceHolders(args, placeholder);
28719
28720 length -= holders.length;
28721 if (length < arity) {
28722 return createRecurry(
28723 func, bitmask, createHybrid, wrapper.placeholder, undefined,
28724 args, holders, undefined, undefined, arity - length);
28725 }
28726 var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
28727 return apply(fn, this, args);
28728 }
28729 return wrapper;
28730 }
28731
28732 /**
28733 * Creates a `_.find` or `_.findLast` function.
28734 *
28735 * @private
28736 * @param {Function} findIndexFunc The function to find the collection index.
28737 * @returns {Function} Returns the new find function.
28738 */
28739 function createFind(findIndexFunc) {
28740 return function(collection, predicate, fromIndex) {
28741 var iterable = Object(collection);
28742 if (!isArrayLike(collection)) {
28743 var iteratee = getIteratee(predicate, 3);
28744 collection = keys(collection);
28745 predicate = function(key) { return iteratee(iterable[key], key, iterable); };
28746 }
28747 var index = findIndexFunc(collection, predicate, fromIndex);
28748 return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
28749 };
28750 }
28751
28752 /**
28753 * Creates a `_.flow` or `_.flowRight` function.
28754 *
28755 * @private
28756 * @param {boolean} [fromRight] Specify iterating from right to left.
28757 * @returns {Function} Returns the new flow function.
28758 */
28759 function createFlow(fromRight) {
28760 return flatRest(function(funcs) {
28761 var length = funcs.length,
28762 index = length,
28763 prereq = LodashWrapper.prototype.thru;
28764
28765 if (fromRight) {
28766 funcs.reverse();
28767 }
28768 while (index--) {
28769 var func = funcs[index];
28770 if (typeof func != 'function') {
28771 throw new TypeError(FUNC_ERROR_TEXT);
28772 }
28773 if (prereq && !wrapper && getFuncName(func) == 'wrapper') {
28774 var wrapper = new LodashWrapper([], true);
28775 }
28776 }
28777 index = wrapper ? index : length;
28778 while (++index < length) {
28779 func = funcs[index];
28780
28781 var funcName = getFuncName(func),
28782 data = funcName == 'wrapper' ? getData(func) : undefined;
28783
28784 if (data && isLaziable(data[0]) &&
28785 data[1] == (ARY_FLAG | CURRY_FLAG | PARTIAL_FLAG | REARG_FLAG) &&
28786 !data[4].length && data[9] == 1
28787 ) {
28788 wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);
28789 } else {
28790 wrapper = (func.length == 1 && isLaziable(func))
28791 ? wrapper[funcName]()
28792 : wrapper.thru(func);
28793 }
28794 }
28795 return function() {
28796 var args = arguments,
28797 value = args[0];
28798
28799 if (wrapper && args.length == 1 &&
28800 isArray(value) && value.length >= LARGE_ARRAY_SIZE) {
28801 return wrapper.plant(value).value();
28802 }
28803 var index = 0,
28804 result = length ? funcs[index].apply(this, args) : value;
28805
28806 while (++index < length) {
28807 result = funcs[index].call(this, result);
28808 }
28809 return result;
28810 };
28811 });
28812 }
28813
28814 /**
28815 * Creates a function that wraps `func` to invoke it with optional `this`
28816 * binding of `thisArg`, partial application, and currying.
28817 *
28818 * @private
28819 * @param {Function|string} func The function or method name to wrap.
28820 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
28821 * @param {*} [thisArg] The `this` binding of `func`.
28822 * @param {Array} [partials] The arguments to prepend to those provided to
28823 * the new function.
28824 * @param {Array} [holders] The `partials` placeholder indexes.
28825 * @param {Array} [partialsRight] The arguments to append to those provided
28826 * to the new function.
28827 * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
28828 * @param {Array} [argPos] The argument positions of the new function.
28829 * @param {number} [ary] The arity cap of `func`.
28830 * @param {number} [arity] The arity of `func`.
28831 * @returns {Function} Returns the new wrapped function.
28832 */
28833 function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
28834 var isAry = bitmask & ARY_FLAG,
28835 isBind = bitmask & BIND_FLAG,
28836 isBindKey = bitmask & BIND_KEY_FLAG,
28837 isCurried = bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG),
28838 isFlip = bitmask & FLIP_FLAG,
28839 Ctor = isBindKey ? undefined : createCtor(func);
28840
28841 function wrapper() {
28842 var length = arguments.length,
28843 args = Array(length),
28844 index = length;
28845
28846 while (index--) {
28847 args[index] = arguments[index];
28848 }
28849 if (isCurried) {
28850 var placeholder = getHolder(wrapper),
28851 holdersCount = countHolders(args, placeholder);
28852 }
28853 if (partials) {
28854 args = composeArgs(args, partials, holders, isCurried);
28855 }
28856 if (partialsRight) {
28857 args = composeArgsRight(args, partialsRight, holdersRight, isCurried);
28858 }
28859 length -= holdersCount;
28860 if (isCurried && length < arity) {
28861 var newHolders = replaceHolders(args, placeholder);
28862 return createRecurry(
28863 func, bitmask, createHybrid, wrapper.placeholder, thisArg,
28864 args, newHolders, argPos, ary, arity - length
28865 );
28866 }
28867 var thisBinding = isBind ? thisArg : this,
28868 fn = isBindKey ? thisBinding[func] : func;
28869
28870 length = args.length;
28871 if (argPos) {
28872 args = reorder(args, argPos);
28873 } else if (isFlip && length > 1) {
28874 args.reverse();
28875 }
28876 if (isAry && ary < length) {
28877 args.length = ary;
28878 }
28879 if (this && this !== root && this instanceof wrapper) {
28880 fn = Ctor || createCtor(fn);
28881 }
28882 return fn.apply(thisBinding, args);
28883 }
28884 return wrapper;
28885 }
28886
28887 /**
28888 * Creates a function like `_.invertBy`.
28889 *
28890 * @private
28891 * @param {Function} setter The function to set accumulator values.
28892 * @param {Function} toIteratee The function to resolve iteratees.
28893 * @returns {Function} Returns the new inverter function.
28894 */
28895 function createInverter(setter, toIteratee) {
28896 return function(object, iteratee) {
28897 return baseInverter(object, setter, toIteratee(iteratee), {});
28898 };
28899 }
28900
28901 /**
28902 * Creates a function that performs a mathematical operation on two values.
28903 *
28904 * @private
28905 * @param {Function} operator The function to perform the operation.
28906 * @param {number} [defaultValue] The value used for `undefined` arguments.
28907 * @returns {Function} Returns the new mathematical operation function.
28908 */
28909 function createMathOperation(operator, defaultValue) {
28910 return function(value, other) {
28911 var result;
28912 if (value === undefined && other === undefined) {
28913 return defaultValue;
28914 }
28915 if (value !== undefined) {
28916 result = value;
28917 }
28918 if (other !== undefined) {
28919 if (result === undefined) {
28920 return other;
28921 }
28922 if (typeof value == 'string' || typeof other == 'string') {
28923 value = baseToString(value);
28924 other = baseToString(other);
28925 } else {
28926 value = baseToNumber(value);
28927 other = baseToNumber(other);
28928 }
28929 result = operator(value, other);
28930 }
28931 return result;
28932 };
28933 }
28934
28935 /**
28936 * Creates a function like `_.over`.
28937 *
28938 * @private
28939 * @param {Function} arrayFunc The function to iterate over iteratees.
28940 * @returns {Function} Returns the new over function.
28941 */
28942 function createOver(arrayFunc) {
28943 return flatRest(function(iteratees) {
28944 iteratees = arrayMap(iteratees, baseUnary(getIteratee()));
28945 return baseRest(function(args) {
28946 var thisArg = this;
28947 return arrayFunc(iteratees, function(iteratee) {
28948 return apply(iteratee, thisArg, args);
28949 });
28950 });
28951 });
28952 }
28953
28954 /**
28955 * Creates the padding for `string` based on `length`. The `chars` string
28956 * is truncated if the number of characters exceeds `length`.
28957 *
28958 * @private
28959 * @param {number} length The padding length.
28960 * @param {string} [chars=' '] The string used as padding.
28961 * @returns {string} Returns the padding for `string`.
28962 */
28963 function createPadding(length, chars) {
28964 chars = chars === undefined ? ' ' : baseToString(chars);
28965
28966 var charsLength = chars.length;
28967 if (charsLength < 2) {
28968 return charsLength ? baseRepeat(chars, length) : chars;
28969 }
28970 var result = baseRepeat(chars, nativeCeil(length / stringSize(chars)));
28971 return hasUnicode(chars)
28972 ? castSlice(stringToArray(result), 0, length).join('')
28973 : result.slice(0, length);
28974 }
28975
28976 /**
28977 * Creates a function that wraps `func` to invoke it with the `this` binding
28978 * of `thisArg` and `partials` prepended to the arguments it receives.
28979 *
28980 * @private
28981 * @param {Function} func The function to wrap.
28982 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
28983 * @param {*} thisArg The `this` binding of `func`.
28984 * @param {Array} partials The arguments to prepend to those provided to
28985 * the new function.
28986 * @returns {Function} Returns the new wrapped function.
28987 */
28988 function createPartial(func, bitmask, thisArg, partials) {
28989 var isBind = bitmask & BIND_FLAG,
28990 Ctor = createCtor(func);
28991
28992 function wrapper() {
28993 var argsIndex = -1,
28994 argsLength = arguments.length,
28995 leftIndex = -1,
28996 leftLength = partials.length,
28997 args = Array(leftLength + argsLength),
28998 fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
28999
29000 while (++leftIndex < leftLength) {
29001 args[leftIndex] = partials[leftIndex];
29002 }
29003 while (argsLength--) {
29004 args[leftIndex++] = arguments[++argsIndex];
29005 }
29006 return apply(fn, isBind ? thisArg : this, args);
29007 }
29008 return wrapper;
29009 }
29010
29011 /**
29012 * Creates a `_.range` or `_.rangeRight` function.
29013 *
29014 * @private
29015 * @param {boolean} [fromRight] Specify iterating from right to left.
29016 * @returns {Function} Returns the new range function.
29017 */
29018 function createRange(fromRight) {
29019 return function(start, end, step) {
29020 if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {
29021 end = step = undefined;
29022 }
29023 // Ensure the sign of `-0` is preserved.
29024 start = toFinite(start);
29025 if (end === undefined) {
29026 end = start;
29027 start = 0;
29028 } else {
29029 end = toFinite(end);
29030 }
29031 step = step === undefined ? (start < end ? 1 : -1) : toFinite(step);
29032 return baseRange(start, end, step, fromRight);
29033 };
29034 }
29035
29036 /**
29037 * Creates a function that performs a relational operation on two values.
29038 *
29039 * @private
29040 * @param {Function} operator The function to perform the operation.
29041 * @returns {Function} Returns the new relational operation function.
29042 */
29043 function createRelationalOperation(operator) {
29044 return function(value, other) {
29045 if (!(typeof value == 'string' && typeof other == 'string')) {
29046 value = toNumber(value);
29047 other = toNumber(other);
29048 }
29049 return operator(value, other);
29050 };
29051 }
29052
29053 /**
29054 * Creates a function that wraps `func` to continue currying.
29055 *
29056 * @private
29057 * @param {Function} func The function to wrap.
29058 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
29059 * @param {Function} wrapFunc The function to create the `func` wrapper.
29060 * @param {*} placeholder The placeholder value.
29061 * @param {*} [thisArg] The `this` binding of `func`.
29062 * @param {Array} [partials] The arguments to prepend to those provided to
29063 * the new function.
29064 * @param {Array} [holders] The `partials` placeholder indexes.
29065 * @param {Array} [argPos] The argument positions of the new function.
29066 * @param {number} [ary] The arity cap of `func`.
29067 * @param {number} [arity] The arity of `func`.
29068 * @returns {Function} Returns the new wrapped function.
29069 */
29070 function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
29071 var isCurry = bitmask & CURRY_FLAG,
29072 newHolders = isCurry ? holders : undefined,
29073 newHoldersRight = isCurry ? undefined : holders,
29074 newPartials = isCurry ? partials : undefined,
29075 newPartialsRight = isCurry ? undefined : partials;
29076
29077 bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG);
29078 bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG);
29079
29080 if (!(bitmask & CURRY_BOUND_FLAG)) {
29081 bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG);
29082 }
29083 var newData = [
29084 func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,
29085 newHoldersRight, argPos, ary, arity
29086 ];
29087
29088 var result = wrapFunc.apply(undefined, newData);
29089 if (isLaziable(func)) {
29090 setData(result, newData);
29091 }
29092 result.placeholder = placeholder;
29093 return setWrapToString(result, func, bitmask);
29094 }
29095
29096 /**
29097 * Creates a function like `_.round`.
29098 *
29099 * @private
29100 * @param {string} methodName The name of the `Math` method to use when rounding.
29101 * @returns {Function} Returns the new round function.
29102 */
29103 function createRound(methodName) {
29104 var func = Math[methodName];
29105 return function(number, precision) {
29106 number = toNumber(number);
29107 precision = nativeMin(toInteger(precision), 292);
29108 if (precision) {
29109 // Shift with exponential notation to avoid floating-point issues.
29110 // See [MDN](https://mdn.io/round#Examples) for more details.
29111 var pair = (toString(number) + 'e').split('e'),
29112 value = func(pair[0] + 'e' + (+pair[1] + precision));
29113
29114 pair = (toString(value) + 'e').split('e');
29115 return +(pair[0] + 'e' + (+pair[1] - precision));
29116 }
29117 return func(number);
29118 };
29119 }
29120
29121 /**
29122 * Creates a set object of `values`.
29123 *
29124 * @private
29125 * @param {Array} values The values to add to the set.
29126 * @returns {Object} Returns the new set.
29127 */
29128 var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {
29129 return new Set(values);
29130 };
29131
29132 /**
29133 * Creates a `_.toPairs` or `_.toPairsIn` function.
29134 *
29135 * @private
29136 * @param {Function} keysFunc The function to get the keys of a given object.
29137 * @returns {Function} Returns the new pairs function.
29138 */
29139 function createToPairs(keysFunc) {
29140 return function(object) {
29141 var tag = getTag(object);
29142 if (tag == mapTag) {
29143 return mapToArray(object);
29144 }
29145 if (tag == setTag) {
29146 return setToPairs(object);
29147 }
29148 return baseToPairs(object, keysFunc(object));
29149 };
29150 }
29151
29152 /**
29153 * Creates a function that either curries or invokes `func` with optional
29154 * `this` binding and partially applied arguments.
29155 *
29156 * @private
29157 * @param {Function|string} func The function or method name to wrap.
29158 * @param {number} bitmask The bitmask flags.
29159 * The bitmask may be composed of the following flags:
29160 * 1 - `_.bind`
29161 * 2 - `_.bindKey`
29162 * 4 - `_.curry` or `_.curryRight` of a bound function
29163 * 8 - `_.curry`
29164 * 16 - `_.curryRight`
29165 * 32 - `_.partial`
29166 * 64 - `_.partialRight`
29167 * 128 - `_.rearg`
29168 * 256 - `_.ary`
29169 * 512 - `_.flip`
29170 * @param {*} [thisArg] The `this` binding of `func`.
29171 * @param {Array} [partials] The arguments to be partially applied.
29172 * @param {Array} [holders] The `partials` placeholder indexes.
29173 * @param {Array} [argPos] The argument positions of the new function.
29174 * @param {number} [ary] The arity cap of `func`.
29175 * @param {number} [arity] The arity of `func`.
29176 * @returns {Function} Returns the new wrapped function.
29177 */
29178 function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
29179 var isBindKey = bitmask & BIND_KEY_FLAG;
29180 if (!isBindKey && typeof func != 'function') {
29181 throw new TypeError(FUNC_ERROR_TEXT);
29182 }
29183 var length = partials ? partials.length : 0;
29184 if (!length) {
29185 bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG);
29186 partials = holders = undefined;
29187 }
29188 ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);
29189 arity = arity === undefined ? arity : toInteger(arity);
29190 length -= holders ? holders.length : 0;
29191
29192 if (bitmask & PARTIAL_RIGHT_FLAG) {
29193 var partialsRight = partials,
29194 holdersRight = holders;
29195
29196 partials = holders = undefined;
29197 }
29198 var data = isBindKey ? undefined : getData(func);
29199
29200 var newData = [
29201 func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
29202 argPos, ary, arity
29203 ];
29204
29205 if (data) {
29206 mergeData(newData, data);
29207 }
29208 func = newData[0];
29209 bitmask = newData[1];
29210 thisArg = newData[2];
29211 partials = newData[3];
29212 holders = newData[4];
29213 arity = newData[9] = newData[9] == null
29214 ? (isBindKey ? 0 : func.length)
29215 : nativeMax(newData[9] - length, 0);
29216
29217 if (!arity && bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG)) {
29218 bitmask &= ~(CURRY_FLAG | CURRY_RIGHT_FLAG);
29219 }
29220 if (!bitmask || bitmask == BIND_FLAG) {
29221 var result = createBind(func, bitmask, thisArg);
29222 } else if (bitmask == CURRY_FLAG || bitmask == CURRY_RIGHT_FLAG) {
29223 result = createCurry(func, bitmask, arity);
29224 } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !holders.length) {
29225 result = createPartial(func, bitmask, thisArg, partials);
29226 } else {
29227 result = createHybrid.apply(undefined, newData);
29228 }
29229 var setter = data ? baseSetData : setData;
29230 return setWrapToString(setter(result, newData), func, bitmask);
29231 }
29232
29233 /**
29234 * A specialized version of `baseIsEqualDeep` for arrays with support for
29235 * partial deep comparisons.
29236 *
29237 * @private
29238 * @param {Array} array The array to compare.
29239 * @param {Array} other The other array to compare.
29240 * @param {Function} equalFunc The function to determine equivalents of values.
29241 * @param {Function} customizer The function to customize comparisons.
29242 * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
29243 * for more details.
29244 * @param {Object} stack Tracks traversed `array` and `other` objects.
29245 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
29246 */
29247 function equalArrays(array, other, equalFunc, customizer, bitmask, stack) {
29248 var isPartial = bitmask & PARTIAL_COMPARE_FLAG,
29249 arrLength = array.length,
29250 othLength = other.length;
29251
29252 if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
29253 return false;
29254 }
29255 // Assume cyclic values are equal.
29256 var stacked = stack.get(array);
29257 if (stacked && stack.get(other)) {
29258 return stacked == other;
29259 }
29260 var index = -1,
29261 result = true,
29262 seen = (bitmask & UNORDERED_COMPARE_FLAG) ? new SetCache : undefined;
29263
29264 stack.set(array, other);
29265 stack.set(other, array);
29266
29267 // Ignore non-index properties.
29268 while (++index < arrLength) {
29269 var arrValue = array[index],
29270 othValue = other[index];
29271
29272 if (customizer) {
29273 var compared = isPartial
29274 ? customizer(othValue, arrValue, index, other, array, stack)
29275 : customizer(arrValue, othValue, index, array, other, stack);
29276 }
29277 if (compared !== undefined) {
29278 if (compared) {
29279 continue;
29280 }
29281 result = false;
29282 break;
29283 }
29284 // Recursively compare arrays (susceptible to call stack limits).
29285 if (seen) {
29286 if (!arraySome(other, function(othValue, othIndex) {
29287 if (!cacheHas(seen, othIndex) &&
29288 (arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) {
29289 return seen.push(othIndex);
29290 }
29291 })) {
29292 result = false;
29293 break;
29294 }
29295 } else if (!(
29296 arrValue === othValue ||
29297 equalFunc(arrValue, othValue, customizer, bitmask, stack)
29298 )) {
29299 result = false;
29300 break;
29301 }
29302 }
29303 stack['delete'](array);
29304 stack['delete'](other);
29305 return result;
29306 }
29307
29308 /**
29309 * A specialized version of `baseIsEqualDeep` for comparing objects of
29310 * the same `toStringTag`.
29311 *
29312 * **Note:** This function only supports comparing values with tags of
29313 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
29314 *
29315 * @private
29316 * @param {Object} object The object to compare.
29317 * @param {Object} other The other object to compare.
29318 * @param {string} tag The `toStringTag` of the objects to compare.
29319 * @param {Function} equalFunc The function to determine equivalents of values.
29320 * @param {Function} customizer The function to customize comparisons.
29321 * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
29322 * for more details.
29323 * @param {Object} stack Tracks traversed `object` and `other` objects.
29324 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
29325 */
29326 function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) {
29327 switch (tag) {
29328 case dataViewTag:
29329 if ((object.byteLength != other.byteLength) ||
29330 (object.byteOffset != other.byteOffset)) {
29331 return false;
29332 }
29333 object = object.buffer;
29334 other = other.buffer;
29335
29336 case arrayBufferTag:
29337 if ((object.byteLength != other.byteLength) ||
29338 !equalFunc(new Uint8Array(object), new Uint8Array(other))) {
29339 return false;
29340 }
29341 return true;
29342
29343 case boolTag:
29344 case dateTag:
29345 case numberTag:
29346 // Coerce booleans to `1` or `0` and dates to milliseconds.
29347 // Invalid dates are coerced to `NaN`.
29348 return eq(+object, +other);
29349
29350 case errorTag:
29351 return object.name == other.name && object.message == other.message;
29352
29353 case regexpTag:
29354 case stringTag:
29355 // Coerce regexes to strings and treat strings, primitives and objects,
29356 // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
29357 // for more details.
29358 return object == (other + '');
29359
29360 case mapTag:
29361 var convert = mapToArray;
29362
29363 case setTag:
29364 var isPartial = bitmask & PARTIAL_COMPARE_FLAG;
29365 convert || (convert = setToArray);
29366
29367 if (object.size != other.size && !isPartial) {
29368 return false;
29369 }
29370 // Assume cyclic values are equal.
29371 var stacked = stack.get(object);
29372 if (stacked) {
29373 return stacked == other;
29374 }
29375 bitmask |= UNORDERED_COMPARE_FLAG;
29376
29377 // Recursively compare objects (susceptible to call stack limits).
29378 stack.set(object, other);
29379 var result = equalArrays(convert(object), convert(other), equalFunc, customizer, bitmask, stack);
29380 stack['delete'](object);
29381 return result;
29382
29383 case symbolTag:
29384 if (symbolValueOf) {
29385 return symbolValueOf.call(object) == symbolValueOf.call(other);
29386 }
29387 }
29388 return false;
29389 }
29390
29391 /**
29392 * A specialized version of `baseIsEqualDeep` for objects with support for
29393 * partial deep comparisons.
29394 *
29395 * @private
29396 * @param {Object} object The object to compare.
29397 * @param {Object} other The other object to compare.
29398 * @param {Function} equalFunc The function to determine equivalents of values.
29399 * @param {Function} customizer The function to customize comparisons.
29400 * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
29401 * for more details.
29402 * @param {Object} stack Tracks traversed `object` and `other` objects.
29403 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
29404 */
29405 function equalObjects(object, other, equalFunc, customizer, bitmask, stack) {
29406 var isPartial = bitmask & PARTIAL_COMPARE_FLAG,
29407 objProps = keys(object),
29408 objLength = objProps.length,
29409 othProps = keys(other),
29410 othLength = othProps.length;
29411
29412 if (objLength != othLength && !isPartial) {
29413 return false;
29414 }
29415 var index = objLength;
29416 while (index--) {
29417 var key = objProps[index];
29418 if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
29419 return false;
29420 }
29421 }
29422 // Assume cyclic values are equal.
29423 var stacked = stack.get(object);
29424 if (stacked && stack.get(other)) {
29425 return stacked == other;
29426 }
29427 var result = true;
29428 stack.set(object, other);
29429 stack.set(other, object);
29430
29431 var skipCtor = isPartial;
29432 while (++index < objLength) {
29433 key = objProps[index];
29434 var objValue = object[key],
29435 othValue = other[key];
29436
29437 if (customizer) {
29438 var compared = isPartial
29439 ? customizer(othValue, objValue, key, other, object, stack)
29440 : customizer(objValue, othValue, key, object, other, stack);
29441 }
29442 // Recursively compare objects (susceptible to call stack limits).
29443 if (!(compared === undefined
29444 ? (objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack))
29445 : compared
29446 )) {
29447 result = false;
29448 break;
29449 }
29450 skipCtor || (skipCtor = key == 'constructor');
29451 }
29452 if (result && !skipCtor) {
29453 var objCtor = object.constructor,
29454 othCtor = other.constructor;
29455
29456 // Non `Object` object instances with different constructors are not equal.
29457 if (objCtor != othCtor &&
29458 ('constructor' in object && 'constructor' in other) &&
29459 !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
29460 typeof othCtor == 'function' && othCtor instanceof othCtor)) {
29461 result = false;
29462 }
29463 }
29464 stack['delete'](object);
29465 stack['delete'](other);
29466 return result;
29467 }
29468
29469 /**
29470 * A specialized version of `baseRest` which flattens the rest array.
29471 *
29472 * @private
29473 * @param {Function} func The function to apply a rest parameter to.
29474 * @returns {Function} Returns the new function.
29475 */
29476 function flatRest(func) {
29477 return setToString(overRest(func, undefined, flatten), func + '');
29478 }
29479
29480 /**
29481 * Creates an array of own enumerable property names and symbols of `object`.
29482 *
29483 * @private
29484 * @param {Object} object The object to query.
29485 * @returns {Array} Returns the array of property names and symbols.
29486 */
29487 function getAllKeys(object) {
29488 return baseGetAllKeys(object, keys, getSymbols);
29489 }
29490
29491 /**
29492 * Creates an array of own and inherited enumerable property names and
29493 * symbols of `object`.
29494 *
29495 * @private
29496 * @param {Object} object The object to query.
29497 * @returns {Array} Returns the array of property names and symbols.
29498 */
29499 function getAllKeysIn(object) {
29500 return baseGetAllKeys(object, keysIn, getSymbolsIn);
29501 }
29502
29503 /**
29504 * Gets metadata for `func`.
29505 *
29506 * @private
29507 * @param {Function} func The function to query.
29508 * @returns {*} Returns the metadata for `func`.
29509 */
29510 var getData = !metaMap ? noop : function(func) {
29511 return metaMap.get(func);
29512 };
29513
29514 /**
29515 * Gets the name of `func`.
29516 *
29517 * @private
29518 * @param {Function} func The function to query.
29519 * @returns {string} Returns the function name.
29520 */
29521 function getFuncName(func) {
29522 var result = (func.name + ''),
29523 array = realNames[result],
29524 length = hasOwnProperty.call(realNames, result) ? array.length : 0;
29525
29526 while (length--) {
29527 var data = array[length],
29528 otherFunc = data.func;
29529 if (otherFunc == null || otherFunc == func) {
29530 return data.name;
29531 }
29532 }
29533 return result;
29534 }
29535
29536 /**
29537 * Gets the argument placeholder value for `func`.
29538 *
29539 * @private
29540 * @param {Function} func The function to inspect.
29541 * @returns {*} Returns the placeholder value.
29542 */
29543 function getHolder(func) {
29544 var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func;
29545 return object.placeholder;
29546 }
29547
29548 /**
29549 * Gets the appropriate "iteratee" function. If `_.iteratee` is customized,
29550 * this function returns the custom method, otherwise it returns `baseIteratee`.
29551 * If arguments are provided, the chosen function is invoked with them and
29552 * its result is returned.
29553 *
29554 * @private
29555 * @param {*} [value] The value to convert to an iteratee.
29556 * @param {number} [arity] The arity of the created iteratee.
29557 * @returns {Function} Returns the chosen function or its result.
29558 */
29559 function getIteratee() {
29560 var result = lodash.iteratee || iteratee;
29561 result = result === iteratee ? baseIteratee : result;
29562 return arguments.length ? result(arguments[0], arguments[1]) : result;
29563 }
29564
29565 /**
29566 * Gets the data for `map`.
29567 *
29568 * @private
29569 * @param {Object} map The map to query.
29570 * @param {string} key The reference key.
29571 * @returns {*} Returns the map data.
29572 */
29573 function getMapData(map, key) {
29574 var data = map.__data__;
29575 return isKeyable(key)
29576 ? data[typeof key == 'string' ? 'string' : 'hash']
29577 : data.map;
29578 }
29579
29580 /**
29581 * Gets the property names, values, and compare flags of `object`.
29582 *
29583 * @private
29584 * @param {Object} object The object to query.
29585 * @returns {Array} Returns the match data of `object`.
29586 */
29587 function getMatchData(object) {
29588 var result = keys(object),
29589 length = result.length;
29590
29591 while (length--) {
29592 var key = result[length],
29593 value = object[key];
29594
29595 result[length] = [key, value, isStrictComparable(value)];
29596 }
29597 return result;
29598 }
29599
29600 /**
29601 * Gets the native function at `key` of `object`.
29602 *
29603 * @private
29604 * @param {Object} object The object to query.
29605 * @param {string} key The key of the method to get.
29606 * @returns {*} Returns the function if it's native, else `undefined`.
29607 */
29608 function getNative(object, key) {
29609 var value = getValue(object, key);
29610 return baseIsNative(value) ? value : undefined;
29611 }
29612
29613 /**
29614 * Creates an array of the own enumerable symbol properties of `object`.
29615 *
29616 * @private
29617 * @param {Object} object The object to query.
29618 * @returns {Array} Returns the array of symbols.
29619 */
29620 var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray;
29621
29622 /**
29623 * Creates an array of the own and inherited enumerable symbol properties
29624 * of `object`.
29625 *
29626 * @private
29627 * @param {Object} object The object to query.
29628 * @returns {Array} Returns the array of symbols.
29629 */
29630 var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {
29631 var result = [];
29632 while (object) {
29633 arrayPush(result, getSymbols(object));
29634 object = getPrototype(object);
29635 }
29636 return result;
29637 };
29638
29639 /**
29640 * Gets the `toStringTag` of `value`.
29641 *
29642 * @private
29643 * @param {*} value The value to query.
29644 * @returns {string} Returns the `toStringTag`.
29645 */
29646 var getTag = baseGetTag;
29647
29648 // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
29649 if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
29650 (Map && getTag(new Map) != mapTag) ||
29651 (Promise && getTag(Promise.resolve()) != promiseTag) ||
29652 (Set && getTag(new Set) != setTag) ||
29653 (WeakMap && getTag(new WeakMap) != weakMapTag)) {
29654 getTag = function(value) {
29655 var result = objectToString.call(value),
29656 Ctor = result == objectTag ? value.constructor : undefined,
29657 ctorString = Ctor ? toSource(Ctor) : undefined;
29658
29659 if (ctorString) {
29660 switch (ctorString) {
29661 case dataViewCtorString: return dataViewTag;
29662 case mapCtorString: return mapTag;
29663 case promiseCtorString: return promiseTag;
29664 case setCtorString: return setTag;
29665 case weakMapCtorString: return weakMapTag;
29666 }
29667 }
29668 return result;
29669 };
29670 }
29671
29672 /**
29673 * Gets the view, applying any `transforms` to the `start` and `end` positions.
29674 *
29675 * @private
29676 * @param {number} start The start of the view.
29677 * @param {number} end The end of the view.
29678 * @param {Array} transforms The transformations to apply to the view.
29679 * @returns {Object} Returns an object containing the `start` and `end`
29680 * positions of the view.
29681 */
29682 function getView(start, end, transforms) {
29683 var index = -1,
29684 length = transforms.length;
29685
29686 while (++index < length) {
29687 var data = transforms[index],
29688 size = data.size;
29689
29690 switch (data.type) {
29691 case 'drop': start += size; break;
29692 case 'dropRight': end -= size; break;
29693 case 'take': end = nativeMin(end, start + size); break;
29694 case 'takeRight': start = nativeMax(start, end - size); break;
29695 }
29696 }
29697 return { 'start': start, 'end': end };
29698 }
29699
29700 /**
29701 * Extracts wrapper details from the `source` body comment.
29702 *
29703 * @private
29704 * @param {string} source The source to inspect.
29705 * @returns {Array} Returns the wrapper details.
29706 */
29707 function getWrapDetails(source) {
29708 var match = source.match(reWrapDetails);
29709 return match ? match[1].split(reSplitDetails) : [];
29710 }
29711
29712 /**
29713 * Checks if `path` exists on `object`.
29714 *
29715 * @private
29716 * @param {Object} object The object to query.
29717 * @param {Array|string} path The path to check.
29718 * @param {Function} hasFunc The function to check properties.
29719 * @returns {boolean} Returns `true` if `path` exists, else `false`.
29720 */
29721 function hasPath(object, path, hasFunc) {
29722 path = isKey(path, object) ? [path] : castPath(path);
29723
29724 var index = -1,
29725 length = path.length,
29726 result = false;
29727
29728 while (++index < length) {
29729 var key = toKey(path[index]);
29730 if (!(result = object != null && hasFunc(object, key))) {
29731 break;
29732 }
29733 object = object[key];
29734 }
29735 if (result || ++index != length) {
29736 return result;
29737 }
29738 length = object ? object.length : 0;
29739 return !!length && isLength(length) && isIndex(key, length) &&
29740 (isArray(object) || isArguments(object));
29741 }
29742
29743 /**
29744 * Initializes an array clone.
29745 *
29746 * @private
29747 * @param {Array} array The array to clone.
29748 * @returns {Array} Returns the initialized clone.
29749 */
29750 function initCloneArray(array) {
29751 var length = array.length,
29752 result = array.constructor(length);
29753
29754 // Add properties assigned by `RegExp#exec`.
29755 if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
29756 result.index = array.index;
29757 result.input = array.input;
29758 }
29759 return result;
29760 }
29761
29762 /**
29763 * Initializes an object clone.
29764 *
29765 * @private
29766 * @param {Object} object The object to clone.
29767 * @returns {Object} Returns the initialized clone.
29768 */
29769 function initCloneObject(object) {
29770 return (typeof object.constructor == 'function' && !isPrototype(object))
29771 ? baseCreate(getPrototype(object))
29772 : {};
29773 }
29774
29775 /**
29776 * Initializes an object clone based on its `toStringTag`.
29777 *
29778 * **Note:** This function only supports cloning values with tags of
29779 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
29780 *
29781 * @private
29782 * @param {Object} object The object to clone.
29783 * @param {string} tag The `toStringTag` of the object to clone.
29784 * @param {Function} cloneFunc The function to clone values.
29785 * @param {boolean} [isDeep] Specify a deep clone.
29786 * @returns {Object} Returns the initialized clone.
29787 */
29788 function initCloneByTag(object, tag, cloneFunc, isDeep) {
29789 var Ctor = object.constructor;
29790 switch (tag) {
29791 case arrayBufferTag:
29792 return cloneArrayBuffer(object);
29793
29794 case boolTag:
29795 case dateTag:
29796 return new Ctor(+object);
29797
29798 case dataViewTag:
29799 return cloneDataView(object, isDeep);
29800
29801 case float32Tag: case float64Tag:
29802 case int8Tag: case int16Tag: case int32Tag:
29803 case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
29804 return cloneTypedArray(object, isDeep);
29805
29806 case mapTag:
29807 return cloneMap(object, isDeep, cloneFunc);
29808
29809 case numberTag:
29810 case stringTag:
29811 return new Ctor(object);
29812
29813 case regexpTag:
29814 return cloneRegExp(object);
29815
29816 case setTag:
29817 return cloneSet(object, isDeep, cloneFunc);
29818
29819 case symbolTag:
29820 return cloneSymbol(object);
29821 }
29822 }
29823
29824 /**
29825 * Inserts wrapper `details` in a comment at the top of the `source` body.
29826 *
29827 * @private
29828 * @param {string} source The source to modify.
29829 * @returns {Array} details The details to insert.
29830 * @returns {string} Returns the modified source.
29831 */
29832 function insertWrapDetails(source, details) {
29833 var length = details.length;
29834 if (!length) {
29835 return source;
29836 }
29837 var lastIndex = length - 1;
29838 details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];
29839 details = details.join(length > 2 ? ', ' : ' ');
29840 return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n');
29841 }
29842
29843 /**
29844 * Checks if `value` is a flattenable `arguments` object or array.
29845 *
29846 * @private
29847 * @param {*} value The value to check.
29848 * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
29849 */
29850 function isFlattenable(value) {
29851 return isArray(value) || isArguments(value) ||
29852 !!(spreadableSymbol && value && value[spreadableSymbol]);
29853 }
29854
29855 /**
29856 * Checks if `value` is a valid array-like index.
29857 *
29858 * @private
29859 * @param {*} value The value to check.
29860 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
29861 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
29862 */
29863 function isIndex(value, length) {
29864 length = length == null ? MAX_SAFE_INTEGER : length;
29865 return !!length &&
29866 (typeof value == 'number' || reIsUint.test(value)) &&
29867 (value > -1 && value % 1 == 0 && value < length);
29868 }
29869
29870 /**
29871 * Checks if the given arguments are from an iteratee call.
29872 *
29873 * @private
29874 * @param {*} value The potential iteratee value argument.
29875 * @param {*} index The potential iteratee index or key argument.
29876 * @param {*} object The potential iteratee object argument.
29877 * @returns {boolean} Returns `true` if the arguments are from an iteratee call,
29878 * else `false`.
29879 */
29880 function isIterateeCall(value, index, object) {
29881 if (!isObject(object)) {
29882 return false;
29883 }
29884 var type = typeof index;
29885 if (type == 'number'
29886 ? (isArrayLike(object) && isIndex(index, object.length))
29887 : (type == 'string' && index in object)
29888 ) {
29889 return eq(object[index], value);
29890 }
29891 return false;
29892 }
29893
29894 /**
29895 * Checks if `value` is a property name and not a property path.
29896 *
29897 * @private
29898 * @param {*} value The value to check.
29899 * @param {Object} [object] The object to query keys on.
29900 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
29901 */
29902 function isKey(value, object) {
29903 if (isArray(value)) {
29904 return false;
29905 }
29906 var type = typeof value;
29907 if (type == 'number' || type == 'symbol' || type == 'boolean' ||
29908 value == null || isSymbol(value)) {
29909 return true;
29910 }
29911 return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
29912 (object != null && value in Object(object));
29913 }
29914
29915 /**
29916 * Checks if `value` is suitable for use as unique object key.
29917 *
29918 * @private
29919 * @param {*} value The value to check.
29920 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
29921 */
29922 function isKeyable(value) {
29923 var type = typeof value;
29924 return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
29925 ? (value !== '__proto__')
29926 : (value === null);
29927 }
29928
29929 /**
29930 * Checks if `func` has a lazy counterpart.
29931 *
29932 * @private
29933 * @param {Function} func The function to check.
29934 * @returns {boolean} Returns `true` if `func` has a lazy counterpart,
29935 * else `false`.
29936 */
29937 function isLaziable(func) {
29938 var funcName = getFuncName(func),
29939 other = lodash[funcName];
29940
29941 if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {
29942 return false;
29943 }
29944 if (func === other) {
29945 return true;
29946 }
29947 var data = getData(other);
29948 return !!data && func === data[0];
29949 }
29950
29951 /**
29952 * Checks if `func` has its source masked.
29953 *
29954 * @private
29955 * @param {Function} func The function to check.
29956 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
29957 */
29958 function isMasked(func) {
29959 return !!maskSrcKey && (maskSrcKey in func);
29960 }
29961
29962 /**
29963 * Checks if `func` is capable of being masked.
29964 *
29965 * @private
29966 * @param {*} value The value to check.
29967 * @returns {boolean} Returns `true` if `func` is maskable, else `false`.
29968 */
29969 var isMaskable = coreJsData ? isFunction : stubFalse;
29970
29971 /**
29972 * Checks if `value` is likely a prototype object.
29973 *
29974 * @private
29975 * @param {*} value The value to check.
29976 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
29977 */
29978 function isPrototype(value) {
29979 var Ctor = value && value.constructor,
29980 proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
29981
29982 return value === proto;
29983 }
29984
29985 /**
29986 * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
29987 *
29988 * @private
29989 * @param {*} value The value to check.
29990 * @returns {boolean} Returns `true` if `value` if suitable for strict
29991 * equality comparisons, else `false`.
29992 */
29993 function isStrictComparable(value) {
29994 return value === value && !isObject(value);
29995 }
29996
29997 /**
29998 * A specialized version of `matchesProperty` for source values suitable
29999 * for strict equality comparisons, i.e. `===`.
30000 *
30001 * @private
30002 * @param {string} key The key of the property to get.
30003 * @param {*} srcValue The value to match.
30004 * @returns {Function} Returns the new spec function.
30005 */
30006 function matchesStrictComparable(key, srcValue) {
30007 return function(object) {
30008 if (object == null) {
30009 return false;
30010 }
30011 return object[key] === srcValue &&
30012 (srcValue !== undefined || (key in Object(object)));
30013 };
30014 }
30015
30016 /**
30017 * A specialized version of `_.memoize` which clears the memoized function's
30018 * cache when it exceeds `MAX_MEMOIZE_SIZE`.
30019 *
30020 * @private
30021 * @param {Function} func The function to have its output memoized.
30022 * @returns {Function} Returns the new memoized function.
30023 */
30024 function memoizeCapped(func) {
30025 var result = memoize(func, function(key) {
30026 if (cache.size === MAX_MEMOIZE_SIZE) {
30027 cache.clear();
30028 }
30029 return key;
30030 });
30031
30032 var cache = result.cache;
30033 return result;
30034 }
30035
30036 /**
30037 * Merges the function metadata of `source` into `data`.
30038 *
30039 * Merging metadata reduces the number of wrappers used to invoke a function.
30040 * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
30041 * may be applied regardless of execution order. Methods like `_.ary` and
30042 * `_.rearg` modify function arguments, making the order in which they are
30043 * executed important, preventing the merging of metadata. However, we make
30044 * an exception for a safe combined case where curried functions have `_.ary`
30045 * and or `_.rearg` applied.
30046 *
30047 * @private
30048 * @param {Array} data The destination metadata.
30049 * @param {Array} source The source metadata.
30050 * @returns {Array} Returns `data`.
30051 */
30052 function mergeData(data, source) {
30053 var bitmask = data[1],
30054 srcBitmask = source[1],
30055 newBitmask = bitmask | srcBitmask,
30056 isCommon = newBitmask < (BIND_FLAG | BIND_KEY_FLAG | ARY_FLAG);
30057
30058 var isCombo =
30059 ((srcBitmask == ARY_FLAG) && (bitmask == CURRY_FLAG)) ||
30060 ((srcBitmask == ARY_FLAG) && (bitmask == REARG_FLAG) && (data[7].length <= source[8])) ||
30061 ((srcBitmask == (ARY_FLAG | REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == CURRY_FLAG));
30062
30063 // Exit early if metadata can't be merged.
30064 if (!(isCommon || isCombo)) {
30065 return data;
30066 }
30067 // Use source `thisArg` if available.
30068 if (srcBitmask & BIND_FLAG) {
30069 data[2] = source[2];
30070 // Set when currying a bound function.
30071 newBitmask |= bitmask & BIND_FLAG ? 0 : CURRY_BOUND_FLAG;
30072 }
30073 // Compose partial arguments.
30074 var value = source[3];
30075 if (value) {
30076 var partials = data[3];
30077 data[3] = partials ? composeArgs(partials, value, source[4]) : value;
30078 data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];
30079 }
30080 // Compose partial right arguments.
30081 value = source[5];
30082 if (value) {
30083 partials = data[5];
30084 data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;
30085 data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];
30086 }
30087 // Use source `argPos` if available.
30088 value = source[7];
30089 if (value) {
30090 data[7] = value;
30091 }
30092 // Use source `ary` if it's smaller.
30093 if (srcBitmask & ARY_FLAG) {
30094 data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
30095 }
30096 // Use source `arity` if one is not provided.
30097 if (data[9] == null) {
30098 data[9] = source[9];
30099 }
30100 // Use source `func` and merge bitmasks.
30101 data[0] = source[0];
30102 data[1] = newBitmask;
30103
30104 return data;
30105 }
30106
30107 /**
30108 * Used by `_.defaultsDeep` to customize its `_.merge` use.
30109 *
30110 * @private
30111 * @param {*} objValue The destination value.
30112 * @param {*} srcValue The source value.
30113 * @param {string} key The key of the property to merge.
30114 * @param {Object} object The parent object of `objValue`.
30115 * @param {Object} source The parent object of `srcValue`.
30116 * @param {Object} [stack] Tracks traversed source values and their merged
30117 * counterparts.
30118 * @returns {*} Returns the value to assign.
30119 */
30120 function mergeDefaults(objValue, srcValue, key, object, source, stack) {
30121 if (isObject(objValue) && isObject(srcValue)) {
30122 // Recursively merge objects and arrays (susceptible to call stack limits).
30123 stack.set(srcValue, objValue);
30124 baseMerge(objValue, srcValue, undefined, mergeDefaults, stack);
30125 stack['delete'](srcValue);
30126 }
30127 return objValue;
30128 }
30129
30130 /**
30131 * This function is like
30132 * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
30133 * except that it includes inherited enumerable properties.
30134 *
30135 * @private
30136 * @param {Object} object The object to query.
30137 * @returns {Array} Returns the array of property names.
30138 */
30139 function nativeKeysIn(object) {
30140 var result = [];
30141 if (object != null) {
30142 for (var key in Object(object)) {
30143 result.push(key);
30144 }
30145 }
30146 return result;
30147 }
30148
30149 /**
30150 * A specialized version of `baseRest` which transforms the rest array.
30151 *
30152 * @private
30153 * @param {Function} func The function to apply a rest parameter to.
30154 * @param {number} [start=func.length-1] The start position of the rest parameter.
30155 * @param {Function} transform The rest array transform.
30156 * @returns {Function} Returns the new function.
30157 */
30158 function overRest(func, start, transform) {
30159 start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
30160 return function() {
30161 var args = arguments,
30162 index = -1,
30163 length = nativeMax(args.length - start, 0),
30164 array = Array(length);
30165
30166 while (++index < length) {
30167 array[index] = args[start + index];
30168 }
30169 index = -1;
30170 var otherArgs = Array(start + 1);
30171 while (++index < start) {
30172 otherArgs[index] = args[index];
30173 }
30174 otherArgs[start] = transform(array);
30175 return apply(func, this, otherArgs);
30176 };
30177 }
30178
30179 /**
30180 * Gets the parent value at `path` of `object`.
30181 *
30182 * @private
30183 * @param {Object} object The object to query.
30184 * @param {Array} path The path to get the parent value of.
30185 * @returns {*} Returns the parent value.
30186 */
30187 function parent(object, path) {
30188 return path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
30189 }
30190
30191 /**
30192 * Reorder `array` according to the specified indexes where the element at
30193 * the first index is assigned as the first element, the element at
30194 * the second index is assigned as the second element, and so on.
30195 *
30196 * @private
30197 * @param {Array} array The array to reorder.
30198 * @param {Array} indexes The arranged array indexes.
30199 * @returns {Array} Returns `array`.
30200 */
30201 function reorder(array, indexes) {
30202 var arrLength = array.length,
30203 length = nativeMin(indexes.length, arrLength),
30204 oldArray = copyArray(array);
30205
30206 while (length--) {
30207 var index = indexes[length];
30208 array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
30209 }
30210 return array;
30211 }
30212
30213 /**
30214 * Sets metadata for `func`.
30215 *
30216 * **Note:** If this function becomes hot, i.e. is invoked a lot in a short
30217 * period of time, it will trip its breaker and transition to an identity
30218 * function to avoid garbage collection pauses in V8. See
30219 * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
30220 * for more details.
30221 *
30222 * @private
30223 * @param {Function} func The function to associate metadata with.
30224 * @param {*} data The metadata.
30225 * @returns {Function} Returns `func`.
30226 */
30227 var setData = shortOut(baseSetData);
30228
30229 /**
30230 * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout).
30231 *
30232 * @private
30233 * @param {Function} func The function to delay.
30234 * @param {number} wait The number of milliseconds to delay invocation.
30235 * @returns {number|Object} Returns the timer id or timeout object.
30236 */
30237 var setTimeout = ctxSetTimeout || function(func, wait) {
30238 return root.setTimeout(func, wait);
30239 };
30240
30241 /**
30242 * Sets the `toString` method of `func` to return `string`.
30243 *
30244 * @private
30245 * @param {Function} func The function to modify.
30246 * @param {Function} string The `toString` result.
30247 * @returns {Function} Returns `func`.
30248 */
30249 var setToString = shortOut(baseSetToString);
30250
30251 /**
30252 * Sets the `toString` method of `wrapper` to mimic the source of `reference`
30253 * with wrapper details in a comment at the top of the source body.
30254 *
30255 * @private
30256 * @param {Function} wrapper The function to modify.
30257 * @param {Function} reference The reference function.
30258 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
30259 * @returns {Function} Returns `wrapper`.
30260 */
30261 function setWrapToString(wrapper, reference, bitmask) {
30262 var source = (reference + '');
30263 return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));
30264 }
30265
30266 /**
30267 * Creates a function that'll short out and invoke `identity` instead
30268 * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
30269 * milliseconds.
30270 *
30271 * @private
30272 * @param {Function} func The function to restrict.
30273 * @returns {Function} Returns the new shortable function.
30274 */
30275 function shortOut(func) {
30276 var count = 0,
30277 lastCalled = 0;
30278
30279 return function() {
30280 var stamp = nativeNow(),
30281 remaining = HOT_SPAN - (stamp - lastCalled);
30282
30283 lastCalled = stamp;
30284 if (remaining > 0) {
30285 if (++count >= HOT_COUNT) {
30286 return arguments[0];
30287 }
30288 } else {
30289 count = 0;
30290 }
30291 return func.apply(undefined, arguments);
30292 };
30293 }
30294
30295 /**
30296 * A specialized version of `_.shuffle` which mutates and sets the size of `array`.
30297 *
30298 * @private
30299 * @param {Array} array The array to shuffle.
30300 * @param {number} [size=array.length] The size of `array`.
30301 * @returns {Array} Returns `array`.
30302 */
30303 function shuffleSelf(array, size) {
30304 var index = -1,
30305 length = array.length,
30306 lastIndex = length - 1;
30307
30308 size = size === undefined ? length : size;
30309 while (++index < size) {
30310 var rand = baseRandom(index, lastIndex),
30311 value = array[rand];
30312
30313 array[rand] = array[index];
30314 array[index] = value;
30315 }
30316 array.length = size;
30317 return array;
30318 }
30319
30320 /**
30321 * Converts `string` to a property path array.
30322 *
30323 * @private
30324 * @param {string} string The string to convert.
30325 * @returns {Array} Returns the property path array.
30326 */
30327 var stringToPath = memoizeCapped(function(string) {
30328 string = toString(string);
30329
30330 var result = [];
30331 if (reLeadingDot.test(string)) {
30332 result.push('');
30333 }
30334 string.replace(rePropName, function(match, number, quote, string) {
30335 result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
30336 });
30337 return result;
30338 });
30339
30340 /**
30341 * Converts `value` to a string key if it's not a string or symbol.
30342 *
30343 * @private
30344 * @param {*} value The value to inspect.
30345 * @returns {string|symbol} Returns the key.
30346 */
30347 function toKey(value) {
30348 if (typeof value == 'string' || isSymbol(value)) {
30349 return value;
30350 }
30351 var result = (value + '');
30352 return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
30353 }
30354
30355 /**
30356 * Converts `func` to its source code.
30357 *
30358 * @private
30359 * @param {Function} func The function to process.
30360 * @returns {string} Returns the source code.
30361 */
30362 function toSource(func) {
30363 if (func != null) {
30364 try {
30365 return funcToString.call(func);
30366 } catch (e) {}
30367 try {
30368 return (func + '');
30369 } catch (e) {}
30370 }
30371 return '';
30372 }
30373
30374 /**
30375 * Updates wrapper `details` based on `bitmask` flags.
30376 *
30377 * @private
30378 * @returns {Array} details The details to modify.
30379 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
30380 * @returns {Array} Returns `details`.
30381 */
30382 function updateWrapDetails(details, bitmask) {
30383 arrayEach(wrapFlags, function(pair) {
30384 var value = '_.' + pair[0];
30385 if ((bitmask & pair[1]) && !arrayIncludes(details, value)) {
30386 details.push(value);
30387 }
30388 });
30389 return details.sort();
30390 }
30391
30392 /**
30393 * Creates a clone of `wrapper`.
30394 *
30395 * @private
30396 * @param {Object} wrapper The wrapper to clone.
30397 * @returns {Object} Returns the cloned wrapper.
30398 */
30399 function wrapperClone(wrapper) {
30400 if (wrapper instanceof LazyWrapper) {
30401 return wrapper.clone();
30402 }
30403 var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
30404 result.__actions__ = copyArray(wrapper.__actions__);
30405 result.__index__ = wrapper.__index__;
30406 result.__values__ = wrapper.__values__;
30407 return result;
30408 }
30409
30410 /*------------------------------------------------------------------------*/
30411
30412 /**
30413 * Creates an array of elements split into groups the length of `size`.
30414 * If `array` can't be split evenly, the final chunk will be the remaining
30415 * elements.
30416 *
30417 * @static
30418 * @memberOf _
30419 * @since 3.0.0
30420 * @category Array
30421 * @param {Array} array The array to process.
30422 * @param {number} [size=1] The length of each chunk
30423 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
30424 * @returns {Array} Returns the new array of chunks.
30425 * @example
30426 *
30427 * _.chunk(['a', 'b', 'c', 'd'], 2);
30428 * // => [['a', 'b'], ['c', 'd']]
30429 *
30430 * _.chunk(['a', 'b', 'c', 'd'], 3);
30431 * // => [['a', 'b', 'c'], ['d']]
30432 */
30433 function chunk(array, size, guard) {
30434 if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) {
30435 size = 1;
30436 } else {
30437 size = nativeMax(toInteger(size), 0);
30438 }
30439 var length = array ? array.length : 0;
30440 if (!length || size < 1) {
30441 return [];
30442 }
30443 var index = 0,
30444 resIndex = 0,
30445 result = Array(nativeCeil(length / size));
30446
30447 while (index < length) {
30448 result[resIndex++] = baseSlice(array, index, (index += size));
30449 }
30450 return result;
30451 }
30452
30453 /**
30454 * Creates an array with all falsey values removed. The values `false`, `null`,
30455 * `0`, `""`, `undefined`, and `NaN` are falsey.
30456 *
30457 * @static
30458 * @memberOf _
30459 * @since 0.1.0
30460 * @category Array
30461 * @param {Array} array The array to compact.
30462 * @returns {Array} Returns the new array of filtered values.
30463 * @example
30464 *
30465 * _.compact([0, 1, false, 2, '', 3]);
30466 * // => [1, 2, 3]
30467 */
30468 function compact(array) {
30469 var index = -1,
30470 length = array ? array.length : 0,
30471 resIndex = 0,
30472 result = [];
30473
30474 while (++index < length) {
30475 var value = array[index];
30476 if (value) {
30477 result[resIndex++] = value;
30478 }
30479 }
30480 return result;
30481 }
30482
30483 /**
30484 * Creates a new array concatenating `array` with any additional arrays
30485 * and/or values.
30486 *
30487 * @static
30488 * @memberOf _
30489 * @since 4.0.0
30490 * @category Array
30491 * @param {Array} array The array to concatenate.
30492 * @param {...*} [values] The values to concatenate.
30493 * @returns {Array} Returns the new concatenated array.
30494 * @example
30495 *
30496 * var array = [1];
30497 * var other = _.concat(array, 2, [3], [[4]]);
30498 *
30499 * console.log(other);
30500 * // => [1, 2, 3, [4]]
30501 *
30502 * console.log(array);
30503 * // => [1]
30504 */
30505 function concat() {
30506 var length = arguments.length;
30507 if (!length) {
30508 return [];
30509 }
30510 var args = Array(length - 1),
30511 array = arguments[0],
30512 index = length;
30513
30514 while (index--) {
30515 args[index - 1] = arguments[index];
30516 }
30517 return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1));
30518 }
30519
30520 /**
30521 * Creates an array of `array` values not included in the other given arrays
30522 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
30523 * for equality comparisons. The order and references of result values are
30524 * determined by the first array.
30525 *
30526 * **Note:** Unlike `_.pullAll`, this method returns a new array.
30527 *
30528 * @static
30529 * @memberOf _
30530 * @since 0.1.0
30531 * @category Array
30532 * @param {Array} array The array to inspect.
30533 * @param {...Array} [values] The values to exclude.
30534 * @returns {Array} Returns the new array of filtered values.
30535 * @see _.without, _.xor
30536 * @example
30537 *
30538 * _.difference([2, 1], [2, 3]);
30539 * // => [1]
30540 */
30541 var difference = baseRest(function(array, values) {
30542 return isArrayLikeObject(array)
30543 ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true))
30544 : [];
30545 });
30546
30547 /**
30548 * This method is like `_.difference` except that it accepts `iteratee` which
30549 * is invoked for each element of `array` and `values` to generate the criterion
30550 * by which they're compared. The order and references of result values are
30551 * determined by the first array. The iteratee is invoked with one argument:
30552 * (value).
30553 *
30554 * **Note:** Unlike `_.pullAllBy`, this method returns a new array.
30555 *
30556 * @static
30557 * @memberOf _
30558 * @since 4.0.0
30559 * @category Array
30560 * @param {Array} array The array to inspect.
30561 * @param {...Array} [values] The values to exclude.
30562 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
30563 * @returns {Array} Returns the new array of filtered values.
30564 * @example
30565 *
30566 * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);
30567 * // => [1.2]
30568 *
30569 * // The `_.property` iteratee shorthand.
30570 * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');
30571 * // => [{ 'x': 2 }]
30572 */
30573 var differenceBy = baseRest(function(array, values) {
30574 var iteratee = last(values);
30575 if (isArrayLikeObject(iteratee)) {
30576 iteratee = undefined;
30577 }
30578 return isArrayLikeObject(array)
30579 ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2))
30580 : [];
30581 });
30582
30583 /**
30584 * This method is like `_.difference` except that it accepts `comparator`
30585 * which is invoked to compare elements of `array` to `values`. The order and
30586 * references of result values are determined by the first array. The comparator
30587 * is invoked with two arguments: (arrVal, othVal).
30588 *
30589 * **Note:** Unlike `_.pullAllWith`, this method returns a new array.
30590 *
30591 * @static
30592 * @memberOf _
30593 * @since 4.0.0
30594 * @category Array
30595 * @param {Array} array The array to inspect.
30596 * @param {...Array} [values] The values to exclude.
30597 * @param {Function} [comparator] The comparator invoked per element.
30598 * @returns {Array} Returns the new array of filtered values.
30599 * @example
30600 *
30601 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
30602 *
30603 * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);
30604 * // => [{ 'x': 2, 'y': 1 }]
30605 */
30606 var differenceWith = baseRest(function(array, values) {
30607 var comparator = last(values);
30608 if (isArrayLikeObject(comparator)) {
30609 comparator = undefined;
30610 }
30611 return isArrayLikeObject(array)
30612 ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator)
30613 : [];
30614 });
30615
30616 /**
30617 * Creates a slice of `array` with `n` elements dropped from the beginning.
30618 *
30619 * @static
30620 * @memberOf _
30621 * @since 0.5.0
30622 * @category Array
30623 * @param {Array} array The array to query.
30624 * @param {number} [n=1] The number of elements to drop.
30625 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
30626 * @returns {Array} Returns the slice of `array`.
30627 * @example
30628 *
30629 * _.drop([1, 2, 3]);
30630 * // => [2, 3]
30631 *
30632 * _.drop([1, 2, 3], 2);
30633 * // => [3]
30634 *
30635 * _.drop([1, 2, 3], 5);
30636 * // => []
30637 *
30638 * _.drop([1, 2, 3], 0);
30639 * // => [1, 2, 3]
30640 */
30641 function drop(array, n, guard) {
30642 var length = array ? array.length : 0;
30643 if (!length) {
30644 return [];
30645 }
30646 n = (guard || n === undefined) ? 1 : toInteger(n);
30647 return baseSlice(array, n < 0 ? 0 : n, length);
30648 }
30649
30650 /**
30651 * Creates a slice of `array` with `n` elements dropped from the end.
30652 *
30653 * @static
30654 * @memberOf _
30655 * @since 3.0.0
30656 * @category Array
30657 * @param {Array} array The array to query.
30658 * @param {number} [n=1] The number of elements to drop.
30659 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
30660 * @returns {Array} Returns the slice of `array`.
30661 * @example
30662 *
30663 * _.dropRight([1, 2, 3]);
30664 * // => [1, 2]
30665 *
30666 * _.dropRight([1, 2, 3], 2);
30667 * // => [1]
30668 *
30669 * _.dropRight([1, 2, 3], 5);
30670 * // => []
30671 *
30672 * _.dropRight([1, 2, 3], 0);
30673 * // => [1, 2, 3]
30674 */
30675 function dropRight(array, n, guard) {
30676 var length = array ? array.length : 0;
30677 if (!length) {
30678 return [];
30679 }
30680 n = (guard || n === undefined) ? 1 : toInteger(n);
30681 n = length - n;
30682 return baseSlice(array, 0, n < 0 ? 0 : n);
30683 }
30684
30685 /**
30686 * Creates a slice of `array` excluding elements dropped from the end.
30687 * Elements are dropped until `predicate` returns falsey. The predicate is
30688 * invoked with three arguments: (value, index, array).
30689 *
30690 * @static
30691 * @memberOf _
30692 * @since 3.0.0
30693 * @category Array
30694 * @param {Array} array The array to query.
30695 * @param {Function} [predicate=_.identity] The function invoked per iteration.
30696 * @returns {Array} Returns the slice of `array`.
30697 * @example
30698 *
30699 * var users = [
30700 * { 'user': 'barney', 'active': true },
30701 * { 'user': 'fred', 'active': false },
30702 * { 'user': 'pebbles', 'active': false }
30703 * ];
30704 *
30705 * _.dropRightWhile(users, function(o) { return !o.active; });
30706 * // => objects for ['barney']
30707 *
30708 * // The `_.matches` iteratee shorthand.
30709 * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false });
30710 * // => objects for ['barney', 'fred']
30711 *
30712 * // The `_.matchesProperty` iteratee shorthand.
30713 * _.dropRightWhile(users, ['active', false]);
30714 * // => objects for ['barney']
30715 *
30716 * // The `_.property` iteratee shorthand.
30717 * _.dropRightWhile(users, 'active');
30718 * // => objects for ['barney', 'fred', 'pebbles']
30719 */
30720 function dropRightWhile(array, predicate) {
30721 return (array && array.length)
30722 ? baseWhile(array, getIteratee(predicate, 3), true, true)
30723 : [];
30724 }
30725
30726 /**
30727 * Creates a slice of `array` excluding elements dropped from the beginning.
30728 * Elements are dropped until `predicate` returns falsey. The predicate is
30729 * invoked with three arguments: (value, index, array).
30730 *
30731 * @static
30732 * @memberOf _
30733 * @since 3.0.0
30734 * @category Array
30735 * @param {Array} array The array to query.
30736 * @param {Function} [predicate=_.identity]
30737 * The function invoked per iteration.
30738 * @returns {Array} Returns the slice of `array`.
30739 * @example
30740 *
30741 * var users = [
30742 * { 'user': 'barney', 'active': false },
30743 * { 'user': 'fred', 'active': false },
30744 * { 'user': 'pebbles', 'active': true }
30745 * ];
30746 *
30747 * _.dropWhile(users, function(o) { return !o.active; });
30748 * // => objects for ['pebbles']
30749 *
30750 * // The `_.matches` iteratee shorthand.
30751 * _.dropWhile(users, { 'user': 'barney', 'active': false });
30752 * // => objects for ['fred', 'pebbles']
30753 *
30754 * // The `_.matchesProperty` iteratee shorthand.
30755 * _.dropWhile(users, ['active', false]);
30756 * // => objects for ['pebbles']
30757 *
30758 * // The `_.property` iteratee shorthand.
30759 * _.dropWhile(users, 'active');
30760 * // => objects for ['barney', 'fred', 'pebbles']
30761 */
30762 function dropWhile(array, predicate) {
30763 return (array && array.length)
30764 ? baseWhile(array, getIteratee(predicate, 3), true)
30765 : [];
30766 }
30767
30768 /**
30769 * Fills elements of `array` with `value` from `start` up to, but not
30770 * including, `end`.
30771 *
30772 * **Note:** This method mutates `array`.
30773 *
30774 * @static
30775 * @memberOf _
30776 * @since 3.2.0
30777 * @category Array
30778 * @param {Array} array The array to fill.
30779 * @param {*} value The value to fill `array` with.
30780 * @param {number} [start=0] The start position.
30781 * @param {number} [end=array.length] The end position.
30782 * @returns {Array} Returns `array`.
30783 * @example
30784 *
30785 * var array = [1, 2, 3];
30786 *
30787 * _.fill(array, 'a');
30788 * console.log(array);
30789 * // => ['a', 'a', 'a']
30790 *
30791 * _.fill(Array(3), 2);
30792 * // => [2, 2, 2]
30793 *
30794 * _.fill([4, 6, 8, 10], '*', 1, 3);
30795 * // => [4, '*', '*', 10]
30796 */
30797 function fill(array, value, start, end) {
30798 var length = array ? array.length : 0;
30799 if (!length) {
30800 return [];
30801 }
30802 if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {
30803 start = 0;
30804 end = length;
30805 }
30806 return baseFill(array, value, start, end);
30807 }
30808
30809 /**
30810 * This method is like `_.find` except that it returns the index of the first
30811 * element `predicate` returns truthy for instead of the element itself.
30812 *
30813 * @static
30814 * @memberOf _
30815 * @since 1.1.0
30816 * @category Array
30817 * @param {Array} array The array to inspect.
30818 * @param {Function} [predicate=_.identity]
30819 * The function invoked per iteration.
30820 * @param {number} [fromIndex=0] The index to search from.
30821 * @returns {number} Returns the index of the found element, else `-1`.
30822 * @example
30823 *
30824 * var users = [
30825 * { 'user': 'barney', 'active': false },
30826 * { 'user': 'fred', 'active': false },
30827 * { 'user': 'pebbles', 'active': true }
30828 * ];
30829 *
30830 * _.findIndex(users, function(o) { return o.user == 'barney'; });
30831 * // => 0
30832 *
30833 * // The `_.matches` iteratee shorthand.
30834 * _.findIndex(users, { 'user': 'fred', 'active': false });
30835 * // => 1
30836 *
30837 * // The `_.matchesProperty` iteratee shorthand.
30838 * _.findIndex(users, ['active', false]);
30839 * // => 0
30840 *
30841 * // The `_.property` iteratee shorthand.
30842 * _.findIndex(users, 'active');
30843 * // => 2
30844 */
30845 function findIndex(array, predicate, fromIndex) {
30846 var length = array ? array.length : 0;
30847 if (!length) {
30848 return -1;
30849 }
30850 var index = fromIndex == null ? 0 : toInteger(fromIndex);
30851 if (index < 0) {
30852 index = nativeMax(length + index, 0);
30853 }
30854 return baseFindIndex(array, getIteratee(predicate, 3), index);
30855 }
30856
30857 /**
30858 * This method is like `_.findIndex` except that it iterates over elements
30859 * of `collection` from right to left.
30860 *
30861 * @static
30862 * @memberOf _
30863 * @since 2.0.0
30864 * @category Array
30865 * @param {Array} array The array to inspect.
30866 * @param {Function} [predicate=_.identity]
30867 * The function invoked per iteration.
30868 * @param {number} [fromIndex=array.length-1] The index to search from.
30869 * @returns {number} Returns the index of the found element, else `-1`.
30870 * @example
30871 *
30872 * var users = [
30873 * { 'user': 'barney', 'active': true },
30874 * { 'user': 'fred', 'active': false },
30875 * { 'user': 'pebbles', 'active': false }
30876 * ];
30877 *
30878 * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });
30879 * // => 2
30880 *
30881 * // The `_.matches` iteratee shorthand.
30882 * _.findLastIndex(users, { 'user': 'barney', 'active': true });
30883 * // => 0
30884 *
30885 * // The `_.matchesProperty` iteratee shorthand.
30886 * _.findLastIndex(users, ['active', false]);
30887 * // => 2
30888 *
30889 * // The `_.property` iteratee shorthand.
30890 * _.findLastIndex(users, 'active');
30891 * // => 0
30892 */
30893 function findLastIndex(array, predicate, fromIndex) {
30894 var length = array ? array.length : 0;
30895 if (!length) {
30896 return -1;
30897 }
30898 var index = length - 1;
30899 if (fromIndex !== undefined) {
30900 index = toInteger(fromIndex);
30901 index = fromIndex < 0
30902 ? nativeMax(length + index, 0)
30903 : nativeMin(index, length - 1);
30904 }
30905 return baseFindIndex(array, getIteratee(predicate, 3), index, true);
30906 }
30907
30908 /**
30909 * Flattens `array` a single level deep.
30910 *
30911 * @static
30912 * @memberOf _
30913 * @since 0.1.0
30914 * @category Array
30915 * @param {Array} array The array to flatten.
30916 * @returns {Array} Returns the new flattened array.
30917 * @example
30918 *
30919 * _.flatten([1, [2, [3, [4]], 5]]);
30920 * // => [1, 2, [3, [4]], 5]
30921 */
30922 function flatten(array) {
30923 var length = array ? array.length : 0;
30924 return length ? baseFlatten(array, 1) : [];
30925 }
30926
30927 /**
30928 * Recursively flattens `array`.
30929 *
30930 * @static
30931 * @memberOf _
30932 * @since 3.0.0
30933 * @category Array
30934 * @param {Array} array The array to flatten.
30935 * @returns {Array} Returns the new flattened array.
30936 * @example
30937 *
30938 * _.flattenDeep([1, [2, [3, [4]], 5]]);
30939 * // => [1, 2, 3, 4, 5]
30940 */
30941 function flattenDeep(array) {
30942 var length = array ? array.length : 0;
30943 return length ? baseFlatten(array, INFINITY) : [];
30944 }
30945
30946 /**
30947 * Recursively flatten `array` up to `depth` times.
30948 *
30949 * @static
30950 * @memberOf _
30951 * @since 4.4.0
30952 * @category Array
30953 * @param {Array} array The array to flatten.
30954 * @param {number} [depth=1] The maximum recursion depth.
30955 * @returns {Array} Returns the new flattened array.
30956 * @example
30957 *
30958 * var array = [1, [2, [3, [4]], 5]];
30959 *
30960 * _.flattenDepth(array, 1);
30961 * // => [1, 2, [3, [4]], 5]
30962 *
30963 * _.flattenDepth(array, 2);
30964 * // => [1, 2, 3, [4], 5]
30965 */
30966 function flattenDepth(array, depth) {
30967 var length = array ? array.length : 0;
30968 if (!length) {
30969 return [];
30970 }
30971 depth = depth === undefined ? 1 : toInteger(depth);
30972 return baseFlatten(array, depth);
30973 }
30974
30975 /**
30976 * The inverse of `_.toPairs`; this method returns an object composed
30977 * from key-value `pairs`.
30978 *
30979 * @static
30980 * @memberOf _
30981 * @since 4.0.0
30982 * @category Array
30983 * @param {Array} pairs The key-value pairs.
30984 * @returns {Object} Returns the new object.
30985 * @example
30986 *
30987 * _.fromPairs([['a', 1], ['b', 2]]);
30988 * // => { 'a': 1, 'b': 2 }
30989 */
30990 function fromPairs(pairs) {
30991 var index = -1,
30992 length = pairs ? pairs.length : 0,
30993 result = {};
30994
30995 while (++index < length) {
30996 var pair = pairs[index];
30997 result[pair[0]] = pair[1];
30998 }
30999 return result;
31000 }
31001
31002 /**
31003 * Gets the first element of `array`.
31004 *
31005 * @static
31006 * @memberOf _
31007 * @since 0.1.0
31008 * @alias first
31009 * @category Array
31010 * @param {Array} array The array to query.
31011 * @returns {*} Returns the first element of `array`.
31012 * @example
31013 *
31014 * _.head([1, 2, 3]);
31015 * // => 1
31016 *
31017 * _.head([]);
31018 * // => undefined
31019 */
31020 function head(array) {
31021 return (array && array.length) ? array[0] : undefined;
31022 }
31023
31024 /**
31025 * Gets the index at which the first occurrence of `value` is found in `array`
31026 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
31027 * for equality comparisons. If `fromIndex` is negative, it's used as the
31028 * offset from the end of `array`.
31029 *
31030 * @static
31031 * @memberOf _
31032 * @since 0.1.0
31033 * @category Array
31034 * @param {Array} array The array to inspect.
31035 * @param {*} value The value to search for.
31036 * @param {number} [fromIndex=0] The index to search from.
31037 * @returns {number} Returns the index of the matched value, else `-1`.
31038 * @example
31039 *
31040 * _.indexOf([1, 2, 1, 2], 2);
31041 * // => 1
31042 *
31043 * // Search from the `fromIndex`.
31044 * _.indexOf([1, 2, 1, 2], 2, 2);
31045 * // => 3
31046 */
31047 function indexOf(array, value, fromIndex) {
31048 var length = array ? array.length : 0;
31049 if (!length) {
31050 return -1;
31051 }
31052 var index = fromIndex == null ? 0 : toInteger(fromIndex);
31053 if (index < 0) {
31054 index = nativeMax(length + index, 0);
31055 }
31056 return baseIndexOf(array, value, index);
31057 }
31058
31059 /**
31060 * Gets all but the last element of `array`.
31061 *
31062 * @static
31063 * @memberOf _
31064 * @since 0.1.0
31065 * @category Array
31066 * @param {Array} array The array to query.
31067 * @returns {Array} Returns the slice of `array`.
31068 * @example
31069 *
31070 * _.initial([1, 2, 3]);
31071 * // => [1, 2]
31072 */
31073 function initial(array) {
31074 var length = array ? array.length : 0;
31075 return length ? baseSlice(array, 0, -1) : [];
31076 }
31077
31078 /**
31079 * Creates an array of unique values that are included in all given arrays
31080 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
31081 * for equality comparisons. The order and references of result values are
31082 * determined by the first array.
31083 *
31084 * @static
31085 * @memberOf _
31086 * @since 0.1.0
31087 * @category Array
31088 * @param {...Array} [arrays] The arrays to inspect.
31089 * @returns {Array} Returns the new array of intersecting values.
31090 * @example
31091 *
31092 * _.intersection([2, 1], [2, 3]);
31093 * // => [2]
31094 */
31095 var intersection = baseRest(function(arrays) {
31096 var mapped = arrayMap(arrays, castArrayLikeObject);
31097 return (mapped.length && mapped[0] === arrays[0])
31098 ? baseIntersection(mapped)
31099 : [];
31100 });
31101
31102 /**
31103 * This method is like `_.intersection` except that it accepts `iteratee`
31104 * which is invoked for each element of each `arrays` to generate the criterion
31105 * by which they're compared. The order and references of result values are
31106 * determined by the first array. The iteratee is invoked with one argument:
31107 * (value).
31108 *
31109 * @static
31110 * @memberOf _
31111 * @since 4.0.0
31112 * @category Array
31113 * @param {...Array} [arrays] The arrays to inspect.
31114 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
31115 * @returns {Array} Returns the new array of intersecting values.
31116 * @example
31117 *
31118 * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor);
31119 * // => [2.1]
31120 *
31121 * // The `_.property` iteratee shorthand.
31122 * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
31123 * // => [{ 'x': 1 }]
31124 */
31125 var intersectionBy = baseRest(function(arrays) {
31126 var iteratee = last(arrays),
31127 mapped = arrayMap(arrays, castArrayLikeObject);
31128
31129 if (iteratee === last(mapped)) {
31130 iteratee = undefined;
31131 } else {
31132 mapped.pop();
31133 }
31134 return (mapped.length && mapped[0] === arrays[0])
31135 ? baseIntersection(mapped, getIteratee(iteratee, 2))
31136 : [];
31137 });
31138
31139 /**
31140 * This method is like `_.intersection` except that it accepts `comparator`
31141 * which is invoked to compare elements of `arrays`. The order and references
31142 * of result values are determined by the first array. The comparator is
31143 * invoked with two arguments: (arrVal, othVal).
31144 *
31145 * @static
31146 * @memberOf _
31147 * @since 4.0.0
31148 * @category Array
31149 * @param {...Array} [arrays] The arrays to inspect.
31150 * @param {Function} [comparator] The comparator invoked per element.
31151 * @returns {Array} Returns the new array of intersecting values.
31152 * @example
31153 *
31154 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
31155 * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
31156 *
31157 * _.intersectionWith(objects, others, _.isEqual);
31158 * // => [{ 'x': 1, 'y': 2 }]
31159 */
31160 var intersectionWith = baseRest(function(arrays) {
31161 var comparator = last(arrays),
31162 mapped = arrayMap(arrays, castArrayLikeObject);
31163
31164 if (comparator === last(mapped)) {
31165 comparator = undefined;
31166 } else {
31167 mapped.pop();
31168 }
31169 return (mapped.length && mapped[0] === arrays[0])
31170 ? baseIntersection(mapped, undefined, comparator)
31171 : [];
31172 });
31173
31174 /**
31175 * Converts all elements in `array` into a string separated by `separator`.
31176 *
31177 * @static
31178 * @memberOf _
31179 * @since 4.0.0
31180 * @category Array
31181 * @param {Array} array The array to convert.
31182 * @param {string} [separator=','] The element separator.
31183 * @returns {string} Returns the joined string.
31184 * @example
31185 *
31186 * _.join(['a', 'b', 'c'], '~');
31187 * // => 'a~b~c'
31188 */
31189 function join(array, separator) {
31190 return array ? nativeJoin.call(array, separator) : '';
31191 }
31192
31193 /**
31194 * Gets the last element of `array`.
31195 *
31196 * @static
31197 * @memberOf _
31198 * @since 0.1.0
31199 * @category Array
31200 * @param {Array} array The array to query.
31201 * @returns {*} Returns the last element of `array`.
31202 * @example
31203 *
31204 * _.last([1, 2, 3]);
31205 * // => 3
31206 */
31207 function last(array) {
31208 var length = array ? array.length : 0;
31209 return length ? array[length - 1] : undefined;
31210 }
31211
31212 /**
31213 * This method is like `_.indexOf` except that it iterates over elements of
31214 * `array` from right to left.
31215 *
31216 * @static
31217 * @memberOf _
31218 * @since 0.1.0
31219 * @category Array
31220 * @param {Array} array The array to inspect.
31221 * @param {*} value The value to search for.
31222 * @param {number} [fromIndex=array.length-1] The index to search from.
31223 * @returns {number} Returns the index of the matched value, else `-1`.
31224 * @example
31225 *
31226 * _.lastIndexOf([1, 2, 1, 2], 2);
31227 * // => 3
31228 *
31229 * // Search from the `fromIndex`.
31230 * _.lastIndexOf([1, 2, 1, 2], 2, 2);
31231 * // => 1
31232 */
31233 function lastIndexOf(array, value, fromIndex) {
31234 var length = array ? array.length : 0;
31235 if (!length) {
31236 return -1;
31237 }
31238 var index = length;
31239 if (fromIndex !== undefined) {
31240 index = toInteger(fromIndex);
31241 index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1);
31242 }
31243 return value === value
31244 ? strictLastIndexOf(array, value, index)
31245 : baseFindIndex(array, baseIsNaN, index, true);
31246 }
31247
31248 /**
31249 * Gets the element at index `n` of `array`. If `n` is negative, the nth
31250 * element from the end is returned.
31251 *
31252 * @static
31253 * @memberOf _
31254 * @since 4.11.0
31255 * @category Array
31256 * @param {Array} array The array to query.
31257 * @param {number} [n=0] The index of the element to return.
31258 * @returns {*} Returns the nth element of `array`.
31259 * @example
31260 *
31261 * var array = ['a', 'b', 'c', 'd'];
31262 *
31263 * _.nth(array, 1);
31264 * // => 'b'
31265 *
31266 * _.nth(array, -2);
31267 * // => 'c';
31268 */
31269 function nth(array, n) {
31270 return (array && array.length) ? baseNth(array, toInteger(n)) : undefined;
31271 }
31272
31273 /**
31274 * Removes all given values from `array` using
31275 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
31276 * for equality comparisons.
31277 *
31278 * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove`
31279 * to remove elements from an array by predicate.
31280 *
31281 * @static
31282 * @memberOf _
31283 * @since 2.0.0
31284 * @category Array
31285 * @param {Array} array The array to modify.
31286 * @param {...*} [values] The values to remove.
31287 * @returns {Array} Returns `array`.
31288 * @example
31289 *
31290 * var array = ['a', 'b', 'c', 'a', 'b', 'c'];
31291 *
31292 * _.pull(array, 'a', 'c');
31293 * console.log(array);
31294 * // => ['b', 'b']
31295 */
31296 var pull = baseRest(pullAll);
31297
31298 /**
31299 * This method is like `_.pull` except that it accepts an array of values to remove.
31300 *
31301 * **Note:** Unlike `_.difference`, this method mutates `array`.
31302 *
31303 * @static
31304 * @memberOf _
31305 * @since 4.0.0
31306 * @category Array
31307 * @param {Array} array The array to modify.
31308 * @param {Array} values The values to remove.
31309 * @returns {Array} Returns `array`.
31310 * @example
31311 *
31312 * var array = ['a', 'b', 'c', 'a', 'b', 'c'];
31313 *
31314 * _.pullAll(array, ['a', 'c']);
31315 * console.log(array);
31316 * // => ['b', 'b']
31317 */
31318 function pullAll(array, values) {
31319 return (array && array.length && values && values.length)
31320 ? basePullAll(array, values)
31321 : array;
31322 }
31323
31324 /**
31325 * This method is like `_.pullAll` except that it accepts `iteratee` which is
31326 * invoked for each element of `array` and `values` to generate the criterion
31327 * by which they're compared. The iteratee is invoked with one argument: (value).
31328 *
31329 * **Note:** Unlike `_.differenceBy`, this method mutates `array`.
31330 *
31331 * @static
31332 * @memberOf _
31333 * @since 4.0.0
31334 * @category Array
31335 * @param {Array} array The array to modify.
31336 * @param {Array} values The values to remove.
31337 * @param {Function} [iteratee=_.identity]
31338 * The iteratee invoked per element.
31339 * @returns {Array} Returns `array`.
31340 * @example
31341 *
31342 * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];
31343 *
31344 * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');
31345 * console.log(array);
31346 * // => [{ 'x': 2 }]
31347 */
31348 function pullAllBy(array, values, iteratee) {
31349 return (array && array.length && values && values.length)
31350 ? basePullAll(array, values, getIteratee(iteratee, 2))
31351 : array;
31352 }
31353
31354 /**
31355 * This method is like `_.pullAll` except that it accepts `comparator` which
31356 * is invoked to compare elements of `array` to `values`. The comparator is
31357 * invoked with two arguments: (arrVal, othVal).
31358 *
31359 * **Note:** Unlike `_.differenceWith`, this method mutates `array`.
31360 *
31361 * @static
31362 * @memberOf _
31363 * @since 4.6.0
31364 * @category Array
31365 * @param {Array} array The array to modify.
31366 * @param {Array} values The values to remove.
31367 * @param {Function} [comparator] The comparator invoked per element.
31368 * @returns {Array} Returns `array`.
31369 * @example
31370 *
31371 * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }];
31372 *
31373 * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual);
31374 * console.log(array);
31375 * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]
31376 */
31377 function pullAllWith(array, values, comparator) {
31378 return (array && array.length && values && values.length)
31379 ? basePullAll(array, values, undefined, comparator)
31380 : array;
31381 }
31382
31383 /**
31384 * Removes elements from `array` corresponding to `indexes` and returns an
31385 * array of removed elements.
31386 *
31387 * **Note:** Unlike `_.at`, this method mutates `array`.
31388 *
31389 * @static
31390 * @memberOf _
31391 * @since 3.0.0
31392 * @category Array
31393 * @param {Array} array The array to modify.
31394 * @param {...(number|number[])} [indexes] The indexes of elements to remove.
31395 * @returns {Array} Returns the new array of removed elements.
31396 * @example
31397 *
31398 * var array = ['a', 'b', 'c', 'd'];
31399 * var pulled = _.pullAt(array, [1, 3]);
31400 *
31401 * console.log(array);
31402 * // => ['a', 'c']
31403 *
31404 * console.log(pulled);
31405 * // => ['b', 'd']
31406 */
31407 var pullAt = flatRest(function(array, indexes) {
31408 var length = array ? array.length : 0,
31409 result = baseAt(array, indexes);
31410
31411 basePullAt(array, arrayMap(indexes, function(index) {
31412 return isIndex(index, length) ? +index : index;
31413 }).sort(compareAscending));
31414
31415 return result;
31416 });
31417
31418 /**
31419 * Removes all elements from `array` that `predicate` returns truthy for
31420 * and returns an array of the removed elements. The predicate is invoked
31421 * with three arguments: (value, index, array).
31422 *
31423 * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`
31424 * to pull elements from an array by value.
31425 *
31426 * @static
31427 * @memberOf _
31428 * @since 2.0.0
31429 * @category Array
31430 * @param {Array} array The array to modify.
31431 * @param {Function} [predicate=_.identity]
31432 * The function invoked per iteration.
31433 * @returns {Array} Returns the new array of removed elements.
31434 * @example
31435 *
31436 * var array = [1, 2, 3, 4];
31437 * var evens = _.remove(array, function(n) {
31438 * return n % 2 == 0;
31439 * });
31440 *
31441 * console.log(array);
31442 * // => [1, 3]
31443 *
31444 * console.log(evens);
31445 * // => [2, 4]
31446 */
31447 function remove(array, predicate) {
31448 var result = [];
31449 if (!(array && array.length)) {
31450 return result;
31451 }
31452 var index = -1,
31453 indexes = [],
31454 length = array.length;
31455
31456 predicate = getIteratee(predicate, 3);
31457 while (++index < length) {
31458 var value = array[index];
31459 if (predicate(value, index, array)) {
31460 result.push(value);
31461 indexes.push(index);
31462 }
31463 }
31464 basePullAt(array, indexes);
31465 return result;
31466 }
31467
31468 /**
31469 * Reverses `array` so that the first element becomes the last, the second
31470 * element becomes the second to last, and so on.
31471 *
31472 * **Note:** This method mutates `array` and is based on
31473 * [`Array#reverse`](https://mdn.io/Array/reverse).
31474 *
31475 * @static
31476 * @memberOf _
31477 * @since 4.0.0
31478 * @category Array
31479 * @param {Array} array The array to modify.
31480 * @returns {Array} Returns `array`.
31481 * @example
31482 *
31483 * var array = [1, 2, 3];
31484 *
31485 * _.reverse(array);
31486 * // => [3, 2, 1]
31487 *
31488 * console.log(array);
31489 * // => [3, 2, 1]
31490 */
31491 function reverse(array) {
31492 return array ? nativeReverse.call(array) : array;
31493 }
31494
31495 /**
31496 * Creates a slice of `array` from `start` up to, but not including, `end`.
31497 *
31498 * **Note:** This method is used instead of
31499 * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are
31500 * returned.
31501 *
31502 * @static
31503 * @memberOf _
31504 * @since 3.0.0
31505 * @category Array
31506 * @param {Array} array The array to slice.
31507 * @param {number} [start=0] The start position.
31508 * @param {number} [end=array.length] The end position.
31509 * @returns {Array} Returns the slice of `array`.
31510 */
31511 function slice(array, start, end) {
31512 var length = array ? array.length : 0;
31513 if (!length) {
31514 return [];
31515 }
31516 if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {
31517 start = 0;
31518 end = length;
31519 }
31520 else {
31521 start = start == null ? 0 : toInteger(start);
31522 end = end === undefined ? length : toInteger(end);
31523 }
31524 return baseSlice(array, start, end);
31525 }
31526
31527 /**
31528 * Uses a binary search to determine the lowest index at which `value`
31529 * should be inserted into `array` in order to maintain its sort order.
31530 *
31531 * @static
31532 * @memberOf _
31533 * @since 0.1.0
31534 * @category Array
31535 * @param {Array} array The sorted array to inspect.
31536 * @param {*} value The value to evaluate.
31537 * @returns {number} Returns the index at which `value` should be inserted
31538 * into `array`.
31539 * @example
31540 *
31541 * _.sortedIndex([30, 50], 40);
31542 * // => 1
31543 */
31544 function sortedIndex(array, value) {
31545 return baseSortedIndex(array, value);
31546 }
31547
31548 /**
31549 * This method is like `_.sortedIndex` except that it accepts `iteratee`
31550 * which is invoked for `value` and each element of `array` to compute their
31551 * sort ranking. The iteratee is invoked with one argument: (value).
31552 *
31553 * @static
31554 * @memberOf _
31555 * @since 4.0.0
31556 * @category Array
31557 * @param {Array} array The sorted array to inspect.
31558 * @param {*} value The value to evaluate.
31559 * @param {Function} [iteratee=_.identity]
31560 * The iteratee invoked per element.
31561 * @returns {number} Returns the index at which `value` should be inserted
31562 * into `array`.
31563 * @example
31564 *
31565 * var objects = [{ 'x': 4 }, { 'x': 5 }];
31566 *
31567 * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });
31568 * // => 0
31569 *
31570 * // The `_.property` iteratee shorthand.
31571 * _.sortedIndexBy(objects, { 'x': 4 }, 'x');
31572 * // => 0
31573 */
31574 function sortedIndexBy(array, value, iteratee) {
31575 return baseSortedIndexBy(array, value, getIteratee(iteratee, 2));
31576 }
31577
31578 /**
31579 * This method is like `_.indexOf` except that it performs a binary
31580 * search on a sorted `array`.
31581 *
31582 * @static
31583 * @memberOf _
31584 * @since 4.0.0
31585 * @category Array
31586 * @param {Array} array The array to inspect.
31587 * @param {*} value The value to search for.
31588 * @returns {number} Returns the index of the matched value, else `-1`.
31589 * @example
31590 *
31591 * _.sortedIndexOf([4, 5, 5, 5, 6], 5);
31592 * // => 1
31593 */
31594 function sortedIndexOf(array, value) {
31595 var length = array ? array.length : 0;
31596 if (length) {
31597 var index = baseSortedIndex(array, value);
31598 if (index < length && eq(array[index], value)) {
31599 return index;
31600 }
31601 }
31602 return -1;
31603 }
31604
31605 /**
31606 * This method is like `_.sortedIndex` except that it returns the highest
31607 * index at which `value` should be inserted into `array` in order to
31608 * maintain its sort order.
31609 *
31610 * @static
31611 * @memberOf _
31612 * @since 3.0.0
31613 * @category Array
31614 * @param {Array} array The sorted array to inspect.
31615 * @param {*} value The value to evaluate.
31616 * @returns {number} Returns the index at which `value` should be inserted
31617 * into `array`.
31618 * @example
31619 *
31620 * _.sortedLastIndex([4, 5, 5, 5, 6], 5);
31621 * // => 4
31622 */
31623 function sortedLastIndex(array, value) {
31624 return baseSortedIndex(array, value, true);
31625 }
31626
31627 /**
31628 * This method is like `_.sortedLastIndex` except that it accepts `iteratee`
31629 * which is invoked for `value` and each element of `array` to compute their
31630 * sort ranking. The iteratee is invoked with one argument: (value).
31631 *
31632 * @static
31633 * @memberOf _
31634 * @since 4.0.0
31635 * @category Array
31636 * @param {Array} array The sorted array to inspect.
31637 * @param {*} value The value to evaluate.
31638 * @param {Function} [iteratee=_.identity]
31639 * The iteratee invoked per element.
31640 * @returns {number} Returns the index at which `value` should be inserted
31641 * into `array`.
31642 * @example
31643 *
31644 * var objects = [{ 'x': 4 }, { 'x': 5 }];
31645 *
31646 * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });
31647 * // => 1
31648 *
31649 * // The `_.property` iteratee shorthand.
31650 * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x');
31651 * // => 1
31652 */
31653 function sortedLastIndexBy(array, value, iteratee) {
31654 return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true);
31655 }
31656
31657 /**
31658 * This method is like `_.lastIndexOf` except that it performs a binary
31659 * search on a sorted `array`.
31660 *
31661 * @static
31662 * @memberOf _
31663 * @since 4.0.0
31664 * @category Array
31665 * @param {Array} array The array to inspect.
31666 * @param {*} value The value to search for.
31667 * @returns {number} Returns the index of the matched value, else `-1`.
31668 * @example
31669 *
31670 * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5);
31671 * // => 3
31672 */
31673 function sortedLastIndexOf(array, value) {
31674 var length = array ? array.length : 0;
31675 if (length) {
31676 var index = baseSortedIndex(array, value, true) - 1;
31677 if (eq(array[index], value)) {
31678 return index;
31679 }
31680 }
31681 return -1;
31682 }
31683
31684 /**
31685 * This method is like `_.uniq` except that it's designed and optimized
31686 * for sorted arrays.
31687 *
31688 * @static
31689 * @memberOf _
31690 * @since 4.0.0
31691 * @category Array
31692 * @param {Array} array The array to inspect.
31693 * @returns {Array} Returns the new duplicate free array.
31694 * @example
31695 *
31696 * _.sortedUniq([1, 1, 2]);
31697 * // => [1, 2]
31698 */
31699 function sortedUniq(array) {
31700 return (array && array.length)
31701 ? baseSortedUniq(array)
31702 : [];
31703 }
31704
31705 /**
31706 * This method is like `_.uniqBy` except that it's designed and optimized
31707 * for sorted arrays.
31708 *
31709 * @static
31710 * @memberOf _
31711 * @since 4.0.0
31712 * @category Array
31713 * @param {Array} array The array to inspect.
31714 * @param {Function} [iteratee] The iteratee invoked per element.
31715 * @returns {Array} Returns the new duplicate free array.
31716 * @example
31717 *
31718 * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);
31719 * // => [1.1, 2.3]
31720 */
31721 function sortedUniqBy(array, iteratee) {
31722 return (array && array.length)
31723 ? baseSortedUniq(array, getIteratee(iteratee, 2))
31724 : [];
31725 }
31726
31727 /**
31728 * Gets all but the first element of `array`.
31729 *
31730 * @static
31731 * @memberOf _
31732 * @since 4.0.0
31733 * @category Array
31734 * @param {Array} array The array to query.
31735 * @returns {Array} Returns the slice of `array`.
31736 * @example
31737 *
31738 * _.tail([1, 2, 3]);
31739 * // => [2, 3]
31740 */
31741 function tail(array) {
31742 var length = array ? array.length : 0;
31743 return length ? baseSlice(array, 1, length) : [];
31744 }
31745
31746 /**
31747 * Creates a slice of `array` with `n` elements taken from the beginning.
31748 *
31749 * @static
31750 * @memberOf _
31751 * @since 0.1.0
31752 * @category Array
31753 * @param {Array} array The array to query.
31754 * @param {number} [n=1] The number of elements to take.
31755 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
31756 * @returns {Array} Returns the slice of `array`.
31757 * @example
31758 *
31759 * _.take([1, 2, 3]);
31760 * // => [1]
31761 *
31762 * _.take([1, 2, 3], 2);
31763 * // => [1, 2]
31764 *
31765 * _.take([1, 2, 3], 5);
31766 * // => [1, 2, 3]
31767 *
31768 * _.take([1, 2, 3], 0);
31769 * // => []
31770 */
31771 function take(array, n, guard) {
31772 if (!(array && array.length)) {
31773 return [];
31774 }
31775 n = (guard || n === undefined) ? 1 : toInteger(n);
31776 return baseSlice(array, 0, n < 0 ? 0 : n);
31777 }
31778
31779 /**
31780 * Creates a slice of `array` with `n` elements taken from the end.
31781 *
31782 * @static
31783 * @memberOf _
31784 * @since 3.0.0
31785 * @category Array
31786 * @param {Array} array The array to query.
31787 * @param {number} [n=1] The number of elements to take.
31788 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
31789 * @returns {Array} Returns the slice of `array`.
31790 * @example
31791 *
31792 * _.takeRight([1, 2, 3]);
31793 * // => [3]
31794 *
31795 * _.takeRight([1, 2, 3], 2);
31796 * // => [2, 3]
31797 *
31798 * _.takeRight([1, 2, 3], 5);
31799 * // => [1, 2, 3]
31800 *
31801 * _.takeRight([1, 2, 3], 0);
31802 * // => []
31803 */
31804 function takeRight(array, n, guard) {
31805 var length = array ? array.length : 0;
31806 if (!length) {
31807 return [];
31808 }
31809 n = (guard || n === undefined) ? 1 : toInteger(n);
31810 n = length - n;
31811 return baseSlice(array, n < 0 ? 0 : n, length);
31812 }
31813
31814 /**
31815 * Creates a slice of `array` with elements taken from the end. Elements are
31816 * taken until `predicate` returns falsey. The predicate is invoked with
31817 * three arguments: (value, index, array).
31818 *
31819 * @static
31820 * @memberOf _
31821 * @since 3.0.0
31822 * @category Array
31823 * @param {Array} array The array to query.
31824 * @param {Function} [predicate=_.identity]
31825 * The function invoked per iteration.
31826 * @returns {Array} Returns the slice of `array`.
31827 * @example
31828 *
31829 * var users = [
31830 * { 'user': 'barney', 'active': true },
31831 * { 'user': 'fred', 'active': false },
31832 * { 'user': 'pebbles', 'active': false }
31833 * ];
31834 *
31835 * _.takeRightWhile(users, function(o) { return !o.active; });
31836 * // => objects for ['fred', 'pebbles']
31837 *
31838 * // The `_.matches` iteratee shorthand.
31839 * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false });
31840 * // => objects for ['pebbles']
31841 *
31842 * // The `_.matchesProperty` iteratee shorthand.
31843 * _.takeRightWhile(users, ['active', false]);
31844 * // => objects for ['fred', 'pebbles']
31845 *
31846 * // The `_.property` iteratee shorthand.
31847 * _.takeRightWhile(users, 'active');
31848 * // => []
31849 */
31850 function takeRightWhile(array, predicate) {
31851 return (array && array.length)
31852 ? baseWhile(array, getIteratee(predicate, 3), false, true)
31853 : [];
31854 }
31855
31856 /**
31857 * Creates a slice of `array` with elements taken from the beginning. Elements
31858 * are taken until `predicate` returns falsey. The predicate is invoked with
31859 * three arguments: (value, index, array).
31860 *
31861 * @static
31862 * @memberOf _
31863 * @since 3.0.0
31864 * @category Array
31865 * @param {Array} array The array to query.
31866 * @param {Function} [predicate=_.identity]
31867 * The function invoked per iteration.
31868 * @returns {Array} Returns the slice of `array`.
31869 * @example
31870 *
31871 * var users = [
31872 * { 'user': 'barney', 'active': false },
31873 * { 'user': 'fred', 'active': false},
31874 * { 'user': 'pebbles', 'active': true }
31875 * ];
31876 *
31877 * _.takeWhile(users, function(o) { return !o.active; });
31878 * // => objects for ['barney', 'fred']
31879 *
31880 * // The `_.matches` iteratee shorthand.
31881 * _.takeWhile(users, { 'user': 'barney', 'active': false });
31882 * // => objects for ['barney']
31883 *
31884 * // The `_.matchesProperty` iteratee shorthand.
31885 * _.takeWhile(users, ['active', false]);
31886 * // => objects for ['barney', 'fred']
31887 *
31888 * // The `_.property` iteratee shorthand.
31889 * _.takeWhile(users, 'active');
31890 * // => []
31891 */
31892 function takeWhile(array, predicate) {
31893 return (array && array.length)
31894 ? baseWhile(array, getIteratee(predicate, 3))
31895 : [];
31896 }
31897
31898 /**
31899 * Creates an array of unique values, in order, from all given arrays using
31900 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
31901 * for equality comparisons.
31902 *
31903 * @static
31904 * @memberOf _
31905 * @since 0.1.0
31906 * @category Array
31907 * @param {...Array} [arrays] The arrays to inspect.
31908 * @returns {Array} Returns the new array of combined values.
31909 * @example
31910 *
31911 * _.union([2], [1, 2]);
31912 * // => [2, 1]
31913 */
31914 var union = baseRest(function(arrays) {
31915 return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));
31916 });
31917
31918 /**
31919 * This method is like `_.union` except that it accepts `iteratee` which is
31920 * invoked for each element of each `arrays` to generate the criterion by
31921 * which uniqueness is computed. Result values are chosen from the first
31922 * array in which the value occurs. The iteratee is invoked with one argument:
31923 * (value).
31924 *
31925 * @static
31926 * @memberOf _
31927 * @since 4.0.0
31928 * @category Array
31929 * @param {...Array} [arrays] The arrays to inspect.
31930 * @param {Function} [iteratee=_.identity]
31931 * The iteratee invoked per element.
31932 * @returns {Array} Returns the new array of combined values.
31933 * @example
31934 *
31935 * _.unionBy([2.1], [1.2, 2.3], Math.floor);
31936 * // => [2.1, 1.2]
31937 *
31938 * // The `_.property` iteratee shorthand.
31939 * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
31940 * // => [{ 'x': 1 }, { 'x': 2 }]
31941 */
31942 var unionBy = baseRest(function(arrays) {
31943 var iteratee = last(arrays);
31944 if (isArrayLikeObject(iteratee)) {
31945 iteratee = undefined;
31946 }
31947 return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2));
31948 });
31949
31950 /**
31951 * This method is like `_.union` except that it accepts `comparator` which
31952 * is invoked to compare elements of `arrays`. Result values are chosen from
31953 * the first array in which the value occurs. The comparator is invoked
31954 * with two arguments: (arrVal, othVal).
31955 *
31956 * @static
31957 * @memberOf _
31958 * @since 4.0.0
31959 * @category Array
31960 * @param {...Array} [arrays] The arrays to inspect.
31961 * @param {Function} [comparator] The comparator invoked per element.
31962 * @returns {Array} Returns the new array of combined values.
31963 * @example
31964 *
31965 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
31966 * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
31967 *
31968 * _.unionWith(objects, others, _.isEqual);
31969 * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
31970 */
31971 var unionWith = baseRest(function(arrays) {
31972 var comparator = last(arrays);
31973 if (isArrayLikeObject(comparator)) {
31974 comparator = undefined;
31975 }
31976 return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator);
31977 });
31978
31979 /**
31980 * Creates a duplicate-free version of an array, using
31981 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
31982 * for equality comparisons, in which only the first occurrence of each element
31983 * is kept. The order of result values is determined by the order they occur
31984 * in the array.
31985 *
31986 * @static
31987 * @memberOf _
31988 * @since 0.1.0
31989 * @category Array
31990 * @param {Array} array The array to inspect.
31991 * @returns {Array} Returns the new duplicate free array.
31992 * @example
31993 *
31994 * _.uniq([2, 1, 2]);
31995 * // => [2, 1]
31996 */
31997 function uniq(array) {
31998 return (array && array.length)
31999 ? baseUniq(array)
32000 : [];
32001 }
32002
32003 /**
32004 * This method is like `_.uniq` except that it accepts `iteratee` which is
32005 * invoked for each element in `array` to generate the criterion by which
32006 * uniqueness is computed. The order of result values is determined by the
32007 * order they occur in the array. The iteratee is invoked with one argument:
32008 * (value).
32009 *
32010 * @static
32011 * @memberOf _
32012 * @since 4.0.0
32013 * @category Array
32014 * @param {Array} array The array to inspect.
32015 * @param {Function} [iteratee=_.identity]
32016 * The iteratee invoked per element.
32017 * @returns {Array} Returns the new duplicate free array.
32018 * @example
32019 *
32020 * _.uniqBy([2.1, 1.2, 2.3], Math.floor);
32021 * // => [2.1, 1.2]
32022 *
32023 * // The `_.property` iteratee shorthand.
32024 * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
32025 * // => [{ 'x': 1 }, { 'x': 2 }]
32026 */
32027 function uniqBy(array, iteratee) {
32028 return (array && array.length)
32029 ? baseUniq(array, getIteratee(iteratee, 2))
32030 : [];
32031 }
32032
32033 /**
32034 * This method is like `_.uniq` except that it accepts `comparator` which
32035 * is invoked to compare elements of `array`. The order of result values is
32036 * determined by the order they occur in the array.The comparator is invoked
32037 * with two arguments: (arrVal, othVal).
32038 *
32039 * @static
32040 * @memberOf _
32041 * @since 4.0.0
32042 * @category Array
32043 * @param {Array} array The array to inspect.
32044 * @param {Function} [comparator] The comparator invoked per element.
32045 * @returns {Array} Returns the new duplicate free array.
32046 * @example
32047 *
32048 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
32049 *
32050 * _.uniqWith(objects, _.isEqual);
32051 * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
32052 */
32053 function uniqWith(array, comparator) {
32054 return (array && array.length)
32055 ? baseUniq(array, undefined, comparator)
32056 : [];
32057 }
32058
32059 /**
32060 * This method is like `_.zip` except that it accepts an array of grouped
32061 * elements and creates an array regrouping the elements to their pre-zip
32062 * configuration.
32063 *
32064 * @static
32065 * @memberOf _
32066 * @since 1.2.0
32067 * @category Array
32068 * @param {Array} array The array of grouped elements to process.
32069 * @returns {Array} Returns the new array of regrouped elements.
32070 * @example
32071 *
32072 * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]);
32073 * // => [['a', 1, true], ['b', 2, false]]
32074 *
32075 * _.unzip(zipped);
32076 * // => [['a', 'b'], [1, 2], [true, false]]
32077 */
32078 function unzip(array) {
32079 if (!(array && array.length)) {
32080 return [];
32081 }
32082 var length = 0;
32083 array = arrayFilter(array, function(group) {
32084 if (isArrayLikeObject(group)) {
32085 length = nativeMax(group.length, length);
32086 return true;
32087 }
32088 });
32089 return baseTimes(length, function(index) {
32090 return arrayMap(array, baseProperty(index));
32091 });
32092 }
32093
32094 /**
32095 * This method is like `_.unzip` except that it accepts `iteratee` to specify
32096 * how regrouped values should be combined. The iteratee is invoked with the
32097 * elements of each group: (...group).
32098 *
32099 * @static
32100 * @memberOf _
32101 * @since 3.8.0
32102 * @category Array
32103 * @param {Array} array The array of grouped elements to process.
32104 * @param {Function} [iteratee=_.identity] The function to combine
32105 * regrouped values.
32106 * @returns {Array} Returns the new array of regrouped elements.
32107 * @example
32108 *
32109 * var zipped = _.zip([1, 2], [10, 20], [100, 200]);
32110 * // => [[1, 10, 100], [2, 20, 200]]
32111 *
32112 * _.unzipWith(zipped, _.add);
32113 * // => [3, 30, 300]
32114 */
32115 function unzipWith(array, iteratee) {
32116 if (!(array && array.length)) {
32117 return [];
32118 }
32119 var result = unzip(array);
32120 if (iteratee == null) {
32121 return result;
32122 }
32123 return arrayMap(result, function(group) {
32124 return apply(iteratee, undefined, group);
32125 });
32126 }
32127
32128 /**
32129 * Creates an array excluding all given values using
32130 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
32131 * for equality comparisons.
32132 *
32133 * **Note:** Unlike `_.pull`, this method returns a new array.
32134 *
32135 * @static
32136 * @memberOf _
32137 * @since 0.1.0
32138 * @category Array
32139 * @param {Array} array The array to inspect.
32140 * @param {...*} [values] The values to exclude.
32141 * @returns {Array} Returns the new array of filtered values.
32142 * @see _.difference, _.xor
32143 * @example
32144 *
32145 * _.without([2, 1, 2, 3], 1, 2);
32146 * // => [3]
32147 */
32148 var without = baseRest(function(array, values) {
32149 return isArrayLikeObject(array)
32150 ? baseDifference(array, values)
32151 : [];
32152 });
32153
32154 /**
32155 * Creates an array of unique values that is the
32156 * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)
32157 * of the given arrays. The order of result values is determined by the order
32158 * they occur in the arrays.
32159 *
32160 * @static
32161 * @memberOf _
32162 * @since 2.4.0
32163 * @category Array
32164 * @param {...Array} [arrays] The arrays to inspect.
32165 * @returns {Array} Returns the new array of filtered values.
32166 * @see _.difference, _.without
32167 * @example
32168 *
32169 * _.xor([2, 1], [2, 3]);
32170 * // => [1, 3]
32171 */
32172 var xor = baseRest(function(arrays) {
32173 return baseXor(arrayFilter(arrays, isArrayLikeObject));
32174 });
32175
32176 /**
32177 * This method is like `_.xor` except that it accepts `iteratee` which is
32178 * invoked for each element of each `arrays` to generate the criterion by
32179 * which by which they're compared. The order of result values is determined
32180 * by the order they occur in the arrays. The iteratee is invoked with one
32181 * argument: (value).
32182 *
32183 * @static
32184 * @memberOf _
32185 * @since 4.0.0
32186 * @category Array
32187 * @param {...Array} [arrays] The arrays to inspect.
32188 * @param {Function} [iteratee=_.identity]
32189 * The iteratee invoked per element.
32190 * @returns {Array} Returns the new array of filtered values.
32191 * @example
32192 *
32193 * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor);
32194 * // => [1.2, 3.4]
32195 *
32196 * // The `_.property` iteratee shorthand.
32197 * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
32198 * // => [{ 'x': 2 }]
32199 */
32200 var xorBy = baseRest(function(arrays) {
32201 var iteratee = last(arrays);
32202 if (isArrayLikeObject(iteratee)) {
32203 iteratee = undefined;
32204 }
32205 return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2));
32206 });
32207
32208 /**
32209 * This method is like `_.xor` except that it accepts `comparator` which is
32210 * invoked to compare elements of `arrays`. The order of result values is
32211 * determined by the order they occur in the arrays. The comparator is invoked
32212 * with two arguments: (arrVal, othVal).
32213 *
32214 * @static
32215 * @memberOf _
32216 * @since 4.0.0
32217 * @category Array
32218 * @param {...Array} [arrays] The arrays to inspect.
32219 * @param {Function} [comparator] The comparator invoked per element.
32220 * @returns {Array} Returns the new array of filtered values.
32221 * @example
32222 *
32223 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
32224 * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
32225 *
32226 * _.xorWith(objects, others, _.isEqual);
32227 * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
32228 */
32229 var xorWith = baseRest(function(arrays) {
32230 var comparator = last(arrays);
32231 if (isArrayLikeObject(comparator)) {
32232 comparator = undefined;
32233 }
32234 return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator);
32235 });
32236
32237 /**
32238 * Creates an array of grouped elements, the first of which contains the
32239 * first elements of the given arrays, the second of which contains the
32240 * second elements of the given arrays, and so on.
32241 *
32242 * @static
32243 * @memberOf _
32244 * @since 0.1.0
32245 * @category Array
32246 * @param {...Array} [arrays] The arrays to process.
32247 * @returns {Array} Returns the new array of grouped elements.
32248 * @example
32249 *
32250 * _.zip(['a', 'b'], [1, 2], [true, false]);
32251 * // => [['a', 1, true], ['b', 2, false]]
32252 */
32253 var zip = baseRest(unzip);
32254
32255 /**
32256 * This method is like `_.fromPairs` except that it accepts two arrays,
32257 * one of property identifiers and one of corresponding values.
32258 *
32259 * @static
32260 * @memberOf _
32261 * @since 0.4.0
32262 * @category Array
32263 * @param {Array} [props=[]] The property identifiers.
32264 * @param {Array} [values=[]] The property values.
32265 * @returns {Object} Returns the new object.
32266 * @example
32267 *
32268 * _.zipObject(['a', 'b'], [1, 2]);
32269 * // => { 'a': 1, 'b': 2 }
32270 */
32271 function zipObject(props, values) {
32272 return baseZipObject(props || [], values || [], assignValue);
32273 }
32274
32275 /**
32276 * This method is like `_.zipObject` except that it supports property paths.
32277 *
32278 * @static
32279 * @memberOf _
32280 * @since 4.1.0
32281 * @category Array
32282 * @param {Array} [props=[]] The property identifiers.
32283 * @param {Array} [values=[]] The property values.
32284 * @returns {Object} Returns the new object.
32285 * @example
32286 *
32287 * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);
32288 * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }
32289 */
32290 function zipObjectDeep(props, values) {
32291 return baseZipObject(props || [], values || [], baseSet);
32292 }
32293
32294 /**
32295 * This method is like `_.zip` except that it accepts `iteratee` to specify
32296 * how grouped values should be combined. The iteratee is invoked with the
32297 * elements of each group: (...group).
32298 *
32299 * @static
32300 * @memberOf _
32301 * @since 3.8.0
32302 * @category Array
32303 * @param {...Array} [arrays] The arrays to process.
32304 * @param {Function} [iteratee=_.identity] The function to combine grouped values.
32305 * @returns {Array} Returns the new array of grouped elements.
32306 * @example
32307 *
32308 * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) {
32309 * return a + b + c;
32310 * });
32311 * // => [111, 222]
32312 */
32313 var zipWith = baseRest(function(arrays) {
32314 var length = arrays.length,
32315 iteratee = length > 1 ? arrays[length - 1] : undefined;
32316
32317 iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined;
32318 return unzipWith(arrays, iteratee);
32319 });
32320
32321 /*------------------------------------------------------------------------*/
32322
32323 /**
32324 * Creates a `lodash` wrapper instance that wraps `value` with explicit method
32325 * chain sequences enabled. The result of such sequences must be unwrapped
32326 * with `_#value`.
32327 *
32328 * @static
32329 * @memberOf _
32330 * @since 1.3.0
32331 * @category Seq
32332 * @param {*} value The value to wrap.
32333 * @returns {Object} Returns the new `lodash` wrapper instance.
32334 * @example
32335 *
32336 * var users = [
32337 * { 'user': 'barney', 'age': 36 },
32338 * { 'user': 'fred', 'age': 40 },
32339 * { 'user': 'pebbles', 'age': 1 }
32340 * ];
32341 *
32342 * var youngest = _
32343 * .chain(users)
32344 * .sortBy('age')
32345 * .map(function(o) {
32346 * return o.user + ' is ' + o.age;
32347 * })
32348 * .head()
32349 * .value();
32350 * // => 'pebbles is 1'
32351 */
32352 function chain(value) {
32353 var result = lodash(value);
32354 result.__chain__ = true;
32355 return result;
32356 }
32357
32358 /**
32359 * This method invokes `interceptor` and returns `value`. The interceptor
32360 * is invoked with one argument; (value). The purpose of this method is to
32361 * "tap into" a method chain sequence in order to modify intermediate results.
32362 *
32363 * @static
32364 * @memberOf _
32365 * @since 0.1.0
32366 * @category Seq
32367 * @param {*} value The value to provide to `interceptor`.
32368 * @param {Function} interceptor The function to invoke.
32369 * @returns {*} Returns `value`.
32370 * @example
32371 *
32372 * _([1, 2, 3])
32373 * .tap(function(array) {
32374 * // Mutate input array.
32375 * array.pop();
32376 * })
32377 * .reverse()
32378 * .value();
32379 * // => [2, 1]
32380 */
32381 function tap(value, interceptor) {
32382 interceptor(value);
32383 return value;
32384 }
32385
32386 /**
32387 * This method is like `_.tap` except that it returns the result of `interceptor`.
32388 * The purpose of this method is to "pass thru" values replacing intermediate
32389 * results in a method chain sequence.
32390 *
32391 * @static
32392 * @memberOf _
32393 * @since 3.0.0
32394 * @category Seq
32395 * @param {*} value The value to provide to `interceptor`.
32396 * @param {Function} interceptor The function to invoke.
32397 * @returns {*} Returns the result of `interceptor`.
32398 * @example
32399 *
32400 * _(' abc ')
32401 * .chain()
32402 * .trim()
32403 * .thru(function(value) {
32404 * return [value];
32405 * })
32406 * .value();
32407 * // => ['abc']
32408 */
32409 function thru(value, interceptor) {
32410 return interceptor(value);
32411 }
32412
32413 /**
32414 * This method is the wrapper version of `_.at`.
32415 *
32416 * @name at
32417 * @memberOf _
32418 * @since 1.0.0
32419 * @category Seq
32420 * @param {...(string|string[])} [paths] The property paths of elements to pick.
32421 * @returns {Object} Returns the new `lodash` wrapper instance.
32422 * @example
32423 *
32424 * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
32425 *
32426 * _(object).at(['a[0].b.c', 'a[1]']).value();
32427 * // => [3, 4]
32428 */
32429 var wrapperAt = flatRest(function(paths) {
32430 var length = paths.length,
32431 start = length ? paths[0] : 0,
32432 value = this.__wrapped__,
32433 interceptor = function(object) { return baseAt(object, paths); };
32434
32435 if (length > 1 || this.__actions__.length ||
32436 !(value instanceof LazyWrapper) || !isIndex(start)) {
32437 return this.thru(interceptor);
32438 }
32439 value = value.slice(start, +start + (length ? 1 : 0));
32440 value.__actions__.push({
32441 'func': thru,
32442 'args': [interceptor],
32443 'thisArg': undefined
32444 });
32445 return new LodashWrapper(value, this.__chain__).thru(function(array) {
32446 if (length && !array.length) {
32447 array.push(undefined);
32448 }
32449 return array;
32450 });
32451 });
32452
32453 /**
32454 * Creates a `lodash` wrapper instance with explicit method chain sequences enabled.
32455 *
32456 * @name chain
32457 * @memberOf _
32458 * @since 0.1.0
32459 * @category Seq
32460 * @returns {Object} Returns the new `lodash` wrapper instance.
32461 * @example
32462 *
32463 * var users = [
32464 * { 'user': 'barney', 'age': 36 },
32465 * { 'user': 'fred', 'age': 40 }
32466 * ];
32467 *
32468 * // A sequence without explicit chaining.
32469 * _(users).head();
32470 * // => { 'user': 'barney', 'age': 36 }
32471 *
32472 * // A sequence with explicit chaining.
32473 * _(users)
32474 * .chain()
32475 * .head()
32476 * .pick('user')
32477 * .value();
32478 * // => { 'user': 'barney' }
32479 */
32480 function wrapperChain() {
32481 return chain(this);
32482 }
32483
32484 /**
32485 * Executes the chain sequence and returns the wrapped result.
32486 *
32487 * @name commit
32488 * @memberOf _
32489 * @since 3.2.0
32490 * @category Seq
32491 * @returns {Object} Returns the new `lodash` wrapper instance.
32492 * @example
32493 *
32494 * var array = [1, 2];
32495 * var wrapped = _(array).push(3);
32496 *
32497 * console.log(array);
32498 * // => [1, 2]
32499 *
32500 * wrapped = wrapped.commit();
32501 * console.log(array);
32502 * // => [1, 2, 3]
32503 *
32504 * wrapped.last();
32505 * // => 3
32506 *
32507 * console.log(array);
32508 * // => [1, 2, 3]
32509 */
32510 function wrapperCommit() {
32511 return new LodashWrapper(this.value(), this.__chain__);
32512 }
32513
32514 /**
32515 * Gets the next value on a wrapped object following the
32516 * [iterator protocol](https://mdn.io/iteration_protocols#iterator).
32517 *
32518 * @name next
32519 * @memberOf _
32520 * @since 4.0.0
32521 * @category Seq
32522 * @returns {Object} Returns the next iterator value.
32523 * @example
32524 *
32525 * var wrapped = _([1, 2]);
32526 *
32527 * wrapped.next();
32528 * // => { 'done': false, 'value': 1 }
32529 *
32530 * wrapped.next();
32531 * // => { 'done': false, 'value': 2 }
32532 *
32533 * wrapped.next();
32534 * // => { 'done': true, 'value': undefined }
32535 */
32536 function wrapperNext() {
32537 if (this.__values__ === undefined) {
32538 this.__values__ = toArray(this.value());
32539 }
32540 var done = this.__index__ >= this.__values__.length,
32541 value = done ? undefined : this.__values__[this.__index__++];
32542
32543 return { 'done': done, 'value': value };
32544 }
32545
32546 /**
32547 * Enables the wrapper to be iterable.
32548 *
32549 * @name Symbol.iterator
32550 * @memberOf _
32551 * @since 4.0.0
32552 * @category Seq
32553 * @returns {Object} Returns the wrapper object.
32554 * @example
32555 *
32556 * var wrapped = _([1, 2]);
32557 *
32558 * wrapped[Symbol.iterator]() === wrapped;
32559 * // => true
32560 *
32561 * Array.from(wrapped);
32562 * // => [1, 2]
32563 */
32564 function wrapperToIterator() {
32565 return this;
32566 }
32567
32568 /**
32569 * Creates a clone of the chain sequence planting `value` as the wrapped value.
32570 *
32571 * @name plant
32572 * @memberOf _
32573 * @since 3.2.0
32574 * @category Seq
32575 * @param {*} value The value to plant.
32576 * @returns {Object} Returns the new `lodash` wrapper instance.
32577 * @example
32578 *
32579 * function square(n) {
32580 * return n * n;
32581 * }
32582 *
32583 * var wrapped = _([1, 2]).map(square);
32584 * var other = wrapped.plant([3, 4]);
32585 *
32586 * other.value();
32587 * // => [9, 16]
32588 *
32589 * wrapped.value();
32590 * // => [1, 4]
32591 */
32592 function wrapperPlant(value) {
32593 var result,
32594 parent = this;
32595
32596 while (parent instanceof baseLodash) {
32597 var clone = wrapperClone(parent);
32598 clone.__index__ = 0;
32599 clone.__values__ = undefined;
32600 if (result) {
32601 previous.__wrapped__ = clone;
32602 } else {
32603 result = clone;
32604 }
32605 var previous = clone;
32606 parent = parent.__wrapped__;
32607 }
32608 previous.__wrapped__ = value;
32609 return result;
32610 }
32611
32612 /**
32613 * This method is the wrapper version of `_.reverse`.
32614 *
32615 * **Note:** This method mutates the wrapped array.
32616 *
32617 * @name reverse
32618 * @memberOf _
32619 * @since 0.1.0
32620 * @category Seq
32621 * @returns {Object} Returns the new `lodash` wrapper instance.
32622 * @example
32623 *
32624 * var array = [1, 2, 3];
32625 *
32626 * _(array).reverse().value()
32627 * // => [3, 2, 1]
32628 *
32629 * console.log(array);
32630 * // => [3, 2, 1]
32631 */
32632 function wrapperReverse() {
32633 var value = this.__wrapped__;
32634 if (value instanceof LazyWrapper) {
32635 var wrapped = value;
32636 if (this.__actions__.length) {
32637 wrapped = new LazyWrapper(this);
32638 }
32639 wrapped = wrapped.reverse();
32640 wrapped.__actions__.push({
32641 'func': thru,
32642 'args': [reverse],
32643 'thisArg': undefined
32644 });
32645 return new LodashWrapper(wrapped, this.__chain__);
32646 }
32647 return this.thru(reverse);
32648 }
32649
32650 /**
32651 * Executes the chain sequence to resolve the unwrapped value.
32652 *
32653 * @name value
32654 * @memberOf _
32655 * @since 0.1.0
32656 * @alias toJSON, valueOf
32657 * @category Seq
32658 * @returns {*} Returns the resolved unwrapped value.
32659 * @example
32660 *
32661 * _([1, 2, 3]).value();
32662 * // => [1, 2, 3]
32663 */
32664 function wrapperValue() {
32665 return baseWrapperValue(this.__wrapped__, this.__actions__);
32666 }
32667
32668 /*------------------------------------------------------------------------*/
32669
32670 /**
32671 * Creates an object composed of keys generated from the results of running
32672 * each element of `collection` thru `iteratee`. The corresponding value of
32673 * each key is the number of times the key was returned by `iteratee`. The
32674 * iteratee is invoked with one argument: (value).
32675 *
32676 * @static
32677 * @memberOf _
32678 * @since 0.5.0
32679 * @category Collection
32680 * @param {Array|Object} collection The collection to iterate over.
32681 * @param {Function} [iteratee=_.identity]
32682 * The iteratee to transform keys.
32683 * @returns {Object} Returns the composed aggregate object.
32684 * @example
32685 *
32686 * _.countBy([6.1, 4.2, 6.3], Math.floor);
32687 * // => { '4': 1, '6': 2 }
32688 *
32689 * // The `_.property` iteratee shorthand.
32690 * _.countBy(['one', 'two', 'three'], 'length');
32691 * // => { '3': 2, '5': 1 }
32692 */
32693 var countBy = createAggregator(function(result, value, key) {
32694 if (hasOwnProperty.call(result, key)) {
32695 ++result[key];
32696 } else {
32697 baseAssignValue(result, key, 1);
32698 }
32699 });
32700
32701 /**
32702 * Checks if `predicate` returns truthy for **all** elements of `collection`.
32703 * Iteration is stopped once `predicate` returns falsey. The predicate is
32704 * invoked with three arguments: (value, index|key, collection).
32705 *
32706 * **Note:** This method returns `true` for
32707 * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because
32708 * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of
32709 * elements of empty collections.
32710 *
32711 * @static
32712 * @memberOf _
32713 * @since 0.1.0
32714 * @category Collection
32715 * @param {Array|Object} collection The collection to iterate over.
32716 * @param {Function} [predicate=_.identity]
32717 * The function invoked per iteration.
32718 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
32719 * @returns {boolean} Returns `true` if all elements pass the predicate check,
32720 * else `false`.
32721 * @example
32722 *
32723 * _.every([true, 1, null, 'yes'], Boolean);
32724 * // => false
32725 *
32726 * var users = [
32727 * { 'user': 'barney', 'age': 36, 'active': false },
32728 * { 'user': 'fred', 'age': 40, 'active': false }
32729 * ];
32730 *
32731 * // The `_.matches` iteratee shorthand.
32732 * _.every(users, { 'user': 'barney', 'active': false });
32733 * // => false
32734 *
32735 * // The `_.matchesProperty` iteratee shorthand.
32736 * _.every(users, ['active', false]);
32737 * // => true
32738 *
32739 * // The `_.property` iteratee shorthand.
32740 * _.every(users, 'active');
32741 * // => false
32742 */
32743 function every(collection, predicate, guard) {
32744 var func = isArray(collection) ? arrayEvery : baseEvery;
32745 if (guard && isIterateeCall(collection, predicate, guard)) {
32746 predicate = undefined;
32747 }
32748 return func(collection, getIteratee(predicate, 3));
32749 }
32750
32751 /**
32752 * Iterates over elements of `collection`, returning an array of all elements
32753 * `predicate` returns truthy for. The predicate is invoked with three
32754 * arguments: (value, index|key, collection).
32755 *
32756 * **Note:** Unlike `_.remove`, this method returns a new array.
32757 *
32758 * @static
32759 * @memberOf _
32760 * @since 0.1.0
32761 * @category Collection
32762 * @param {Array|Object} collection The collection to iterate over.
32763 * @param {Function} [predicate=_.identity]
32764 * The function invoked per iteration.
32765 * @returns {Array} Returns the new filtered array.
32766 * @see _.reject
32767 * @example
32768 *
32769 * var users = [
32770 * { 'user': 'barney', 'age': 36, 'active': true },
32771 * { 'user': 'fred', 'age': 40, 'active': false }
32772 * ];
32773 *
32774 * _.filter(users, function(o) { return !o.active; });
32775 * // => objects for ['fred']
32776 *
32777 * // The `_.matches` iteratee shorthand.
32778 * _.filter(users, { 'age': 36, 'active': true });
32779 * // => objects for ['barney']
32780 *
32781 * // The `_.matchesProperty` iteratee shorthand.
32782 * _.filter(users, ['active', false]);
32783 * // => objects for ['fred']
32784 *
32785 * // The `_.property` iteratee shorthand.
32786 * _.filter(users, 'active');
32787 * // => objects for ['barney']
32788 */
32789 function filter(collection, predicate) {
32790 var func = isArray(collection) ? arrayFilter : baseFilter;
32791 return func(collection, getIteratee(predicate, 3));
32792 }
32793
32794 /**
32795 * Iterates over elements of `collection`, returning the first element
32796 * `predicate` returns truthy for. The predicate is invoked with three
32797 * arguments: (value, index|key, collection).
32798 *
32799 * @static
32800 * @memberOf _
32801 * @since 0.1.0
32802 * @category Collection
32803 * @param {Array|Object} collection The collection to inspect.
32804 * @param {Function} [predicate=_.identity]
32805 * The function invoked per iteration.
32806 * @param {number} [fromIndex=0] The index to search from.
32807 * @returns {*} Returns the matched element, else `undefined`.
32808 * @example
32809 *
32810 * var users = [
32811 * { 'user': 'barney', 'age': 36, 'active': true },
32812 * { 'user': 'fred', 'age': 40, 'active': false },
32813 * { 'user': 'pebbles', 'age': 1, 'active': true }
32814 * ];
32815 *
32816 * _.find(users, function(o) { return o.age < 40; });
32817 * // => object for 'barney'
32818 *
32819 * // The `_.matches` iteratee shorthand.
32820 * _.find(users, { 'age': 1, 'active': true });
32821 * // => object for 'pebbles'
32822 *
32823 * // The `_.matchesProperty` iteratee shorthand.
32824 * _.find(users, ['active', false]);
32825 * // => object for 'fred'
32826 *
32827 * // The `_.property` iteratee shorthand.
32828 * _.find(users, 'active');
32829 * // => object for 'barney'
32830 */
32831 var find = createFind(findIndex);
32832
32833 /**
32834 * This method is like `_.find` except that it iterates over elements of
32835 * `collection` from right to left.
32836 *
32837 * @static
32838 * @memberOf _
32839 * @since 2.0.0
32840 * @category Collection
32841 * @param {Array|Object} collection The collection to inspect.
32842 * @param {Function} [predicate=_.identity]
32843 * The function invoked per iteration.
32844 * @param {number} [fromIndex=collection.length-1] The index to search from.
32845 * @returns {*} Returns the matched element, else `undefined`.
32846 * @example
32847 *
32848 * _.findLast([1, 2, 3, 4], function(n) {
32849 * return n % 2 == 1;
32850 * });
32851 * // => 3
32852 */
32853 var findLast = createFind(findLastIndex);
32854
32855 /**
32856 * Creates a flattened array of values by running each element in `collection`
32857 * thru `iteratee` and flattening the mapped results. The iteratee is invoked
32858 * with three arguments: (value, index|key, collection).
32859 *
32860 * @static
32861 * @memberOf _
32862 * @since 4.0.0
32863 * @category Collection
32864 * @param {Array|Object} collection The collection to iterate over.
32865 * @param {Function} [iteratee=_.identity]
32866 * The function invoked per iteration.
32867 * @returns {Array} Returns the new flattened array.
32868 * @example
32869 *
32870 * function duplicate(n) {
32871 * return [n, n];
32872 * }
32873 *
32874 * _.flatMap([1, 2], duplicate);
32875 * // => [1, 1, 2, 2]
32876 */
32877 function flatMap(collection, iteratee) {
32878 return baseFlatten(map(collection, iteratee), 1);
32879 }
32880
32881 /**
32882 * This method is like `_.flatMap` except that it recursively flattens the
32883 * mapped results.
32884 *
32885 * @static
32886 * @memberOf _
32887 * @since 4.7.0
32888 * @category Collection
32889 * @param {Array|Object} collection The collection to iterate over.
32890 * @param {Function} [iteratee=_.identity]
32891 * The function invoked per iteration.
32892 * @returns {Array} Returns the new flattened array.
32893 * @example
32894 *
32895 * function duplicate(n) {
32896 * return [[[n, n]]];
32897 * }
32898 *
32899 * _.flatMapDeep([1, 2], duplicate);
32900 * // => [1, 1, 2, 2]
32901 */
32902 function flatMapDeep(collection, iteratee) {
32903 return baseFlatten(map(collection, iteratee), INFINITY);
32904 }
32905
32906 /**
32907 * This method is like `_.flatMap` except that it recursively flattens the
32908 * mapped results up to `depth` times.
32909 *
32910 * @static
32911 * @memberOf _
32912 * @since 4.7.0
32913 * @category Collection
32914 * @param {Array|Object} collection The collection to iterate over.
32915 * @param {Function} [iteratee=_.identity]
32916 * The function invoked per iteration.
32917 * @param {number} [depth=1] The maximum recursion depth.
32918 * @returns {Array} Returns the new flattened array.
32919 * @example
32920 *
32921 * function duplicate(n) {
32922 * return [[[n, n]]];
32923 * }
32924 *
32925 * _.flatMapDepth([1, 2], duplicate, 2);
32926 * // => [[1, 1], [2, 2]]
32927 */
32928 function flatMapDepth(collection, iteratee, depth) {
32929 depth = depth === undefined ? 1 : toInteger(depth);
32930 return baseFlatten(map(collection, iteratee), depth);
32931 }
32932
32933 /**
32934 * Iterates over elements of `collection` and invokes `iteratee` for each element.
32935 * The iteratee is invoked with three arguments: (value, index|key, collection).
32936 * Iteratee functions may exit iteration early by explicitly returning `false`.
32937 *
32938 * **Note:** As with other "Collections" methods, objects with a "length"
32939 * property are iterated like arrays. To avoid this behavior use `_.forIn`
32940 * or `_.forOwn` for object iteration.
32941 *
32942 * @static
32943 * @memberOf _
32944 * @since 0.1.0
32945 * @alias each
32946 * @category Collection
32947 * @param {Array|Object} collection The collection to iterate over.
32948 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
32949 * @returns {Array|Object} Returns `collection`.
32950 * @see _.forEachRight
32951 * @example
32952 *
32953 * _.forEach([1, 2], function(value) {
32954 * console.log(value);
32955 * });
32956 * // => Logs `1` then `2`.
32957 *
32958 * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
32959 * console.log(key);
32960 * });
32961 * // => Logs 'a' then 'b' (iteration order is not guaranteed).
32962 */
32963 function forEach(collection, iteratee) {
32964 var func = isArray(collection) ? arrayEach : baseEach;
32965 return func(collection, getIteratee(iteratee, 3));
32966 }
32967
32968 /**
32969 * This method is like `_.forEach` except that it iterates over elements of
32970 * `collection` from right to left.
32971 *
32972 * @static
32973 * @memberOf _
32974 * @since 2.0.0
32975 * @alias eachRight
32976 * @category Collection
32977 * @param {Array|Object} collection The collection to iterate over.
32978 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
32979 * @returns {Array|Object} Returns `collection`.
32980 * @see _.forEach
32981 * @example
32982 *
32983 * _.forEachRight([1, 2], function(value) {
32984 * console.log(value);
32985 * });
32986 * // => Logs `2` then `1`.
32987 */
32988 function forEachRight(collection, iteratee) {
32989 var func = isArray(collection) ? arrayEachRight : baseEachRight;
32990 return func(collection, getIteratee(iteratee, 3));
32991 }
32992
32993 /**
32994 * Creates an object composed of keys generated from the results of running
32995 * each element of `collection` thru `iteratee`. The order of grouped values
32996 * is determined by the order they occur in `collection`. The corresponding
32997 * value of each key is an array of elements responsible for generating the
32998 * key. The iteratee is invoked with one argument: (value).
32999 *
33000 * @static
33001 * @memberOf _
33002 * @since 0.1.0
33003 * @category Collection
33004 * @param {Array|Object} collection The collection to iterate over.
33005 * @param {Function} [iteratee=_.identity]
33006 * The iteratee to transform keys.
33007 * @returns {Object} Returns the composed aggregate object.
33008 * @example
33009 *
33010 * _.groupBy([6.1, 4.2, 6.3], Math.floor);
33011 * // => { '4': [4.2], '6': [6.1, 6.3] }
33012 *
33013 * // The `_.property` iteratee shorthand.
33014 * _.groupBy(['one', 'two', 'three'], 'length');
33015 * // => { '3': ['one', 'two'], '5': ['three'] }
33016 */
33017 var groupBy = createAggregator(function(result, value, key) {
33018 if (hasOwnProperty.call(result, key)) {
33019 result[key].push(value);
33020 } else {
33021 baseAssignValue(result, key, [value]);
33022 }
33023 });
33024
33025 /**
33026 * Checks if `value` is in `collection`. If `collection` is a string, it's
33027 * checked for a substring of `value`, otherwise
33028 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
33029 * is used for equality comparisons. If `fromIndex` is negative, it's used as
33030 * the offset from the end of `collection`.
33031 *
33032 * @static
33033 * @memberOf _
33034 * @since 0.1.0
33035 * @category Collection
33036 * @param {Array|Object|string} collection The collection to inspect.
33037 * @param {*} value The value to search for.
33038 * @param {number} [fromIndex=0] The index to search from.
33039 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
33040 * @returns {boolean} Returns `true` if `value` is found, else `false`.
33041 * @example
33042 *
33043 * _.includes([1, 2, 3], 1);
33044 * // => true
33045 *
33046 * _.includes([1, 2, 3], 1, 2);
33047 * // => false
33048 *
33049 * _.includes({ 'a': 1, 'b': 2 }, 1);
33050 * // => true
33051 *
33052 * _.includes('abcd', 'bc');
33053 * // => true
33054 */
33055 function includes(collection, value, fromIndex, guard) {
33056 collection = isArrayLike(collection) ? collection : values(collection);
33057 fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;
33058
33059 var length = collection.length;
33060 if (fromIndex < 0) {
33061 fromIndex = nativeMax(length + fromIndex, 0);
33062 }
33063 return isString(collection)
33064 ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)
33065 : (!!length && baseIndexOf(collection, value, fromIndex) > -1);
33066 }
33067
33068 /**
33069 * Invokes the method at `path` of each element in `collection`, returning
33070 * an array of the results of each invoked method. Any additional arguments
33071 * are provided to each invoked method. If `path` is a function, it's invoked
33072 * for, and `this` bound to, each element in `collection`.
33073 *
33074 * @static
33075 * @memberOf _
33076 * @since 4.0.0
33077 * @category Collection
33078 * @param {Array|Object} collection The collection to iterate over.
33079 * @param {Array|Function|string} path The path of the method to invoke or
33080 * the function invoked per iteration.
33081 * @param {...*} [args] The arguments to invoke each method with.
33082 * @returns {Array} Returns the array of results.
33083 * @example
33084 *
33085 * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');
33086 * // => [[1, 5, 7], [1, 2, 3]]
33087 *
33088 * _.invokeMap([123, 456], String.prototype.split, '');
33089 * // => [['1', '2', '3'], ['4', '5', '6']]
33090 */
33091 var invokeMap = baseRest(function(collection, path, args) {
33092 var index = -1,
33093 isFunc = typeof path == 'function',
33094 isProp = isKey(path),
33095 result = isArrayLike(collection) ? Array(collection.length) : [];
33096
33097 baseEach(collection, function(value) {
33098 var func = isFunc ? path : ((isProp && value != null) ? value[path] : undefined);
33099 result[++index] = func ? apply(func, value, args) : baseInvoke(value, path, args);
33100 });
33101 return result;
33102 });
33103
33104 /**
33105 * Creates an object composed of keys generated from the results of running
33106 * each element of `collection` thru `iteratee`. The corresponding value of
33107 * each key is the last element responsible for generating the key. The
33108 * iteratee is invoked with one argument: (value).
33109 *
33110 * @static
33111 * @memberOf _
33112 * @since 4.0.0
33113 * @category Collection
33114 * @param {Array|Object} collection The collection to iterate over.
33115 * @param {Function} [iteratee=_.identity]
33116 * The iteratee to transform keys.
33117 * @returns {Object} Returns the composed aggregate object.
33118 * @example
33119 *
33120 * var array = [
33121 * { 'dir': 'left', 'code': 97 },
33122 * { 'dir': 'right', 'code': 100 }
33123 * ];
33124 *
33125 * _.keyBy(array, function(o) {
33126 * return String.fromCharCode(o.code);
33127 * });
33128 * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
33129 *
33130 * _.keyBy(array, 'dir');
33131 * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
33132 */
33133 var keyBy = createAggregator(function(result, value, key) {
33134 baseAssignValue(result, key, value);
33135 });
33136
33137 /**
33138 * Creates an array of values by running each element in `collection` thru
33139 * `iteratee`. The iteratee is invoked with three arguments:
33140 * (value, index|key, collection).
33141 *
33142 * Many lodash methods are guarded to work as iteratees for methods like
33143 * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
33144 *
33145 * The guarded methods are:
33146 * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
33147 * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
33148 * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
33149 * `template`, `trim`, `trimEnd`, `trimStart`, and `words`
33150 *
33151 * @static
33152 * @memberOf _
33153 * @since 0.1.0
33154 * @category Collection
33155 * @param {Array|Object} collection The collection to iterate over.
33156 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
33157 * @returns {Array} Returns the new mapped array.
33158 * @example
33159 *
33160 * function square(n) {
33161 * return n * n;
33162 * }
33163 *
33164 * _.map([4, 8], square);
33165 * // => [16, 64]
33166 *
33167 * _.map({ 'a': 4, 'b': 8 }, square);
33168 * // => [16, 64] (iteration order is not guaranteed)
33169 *
33170 * var users = [
33171 * { 'user': 'barney' },
33172 * { 'user': 'fred' }
33173 * ];
33174 *
33175 * // The `_.property` iteratee shorthand.
33176 * _.map(users, 'user');
33177 * // => ['barney', 'fred']
33178 */
33179 function map(collection, iteratee) {
33180 var func = isArray(collection) ? arrayMap : baseMap;
33181 return func(collection, getIteratee(iteratee, 3));
33182 }
33183
33184 /**
33185 * This method is like `_.sortBy` except that it allows specifying the sort
33186 * orders of the iteratees to sort by. If `orders` is unspecified, all values
33187 * are sorted in ascending order. Otherwise, specify an order of "desc" for
33188 * descending or "asc" for ascending sort order of corresponding values.
33189 *
33190 * @static
33191 * @memberOf _
33192 * @since 4.0.0
33193 * @category Collection
33194 * @param {Array|Object} collection The collection to iterate over.
33195 * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]
33196 * The iteratees to sort by.
33197 * @param {string[]} [orders] The sort orders of `iteratees`.
33198 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
33199 * @returns {Array} Returns the new sorted array.
33200 * @example
33201 *
33202 * var users = [
33203 * { 'user': 'fred', 'age': 48 },
33204 * { 'user': 'barney', 'age': 34 },
33205 * { 'user': 'fred', 'age': 40 },
33206 * { 'user': 'barney', 'age': 36 }
33207 * ];
33208 *
33209 * // Sort by `user` in ascending order and by `age` in descending order.
33210 * _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
33211 * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
33212 */
33213 function orderBy(collection, iteratees, orders, guard) {
33214 if (collection == null) {
33215 return [];
33216 }
33217 if (!isArray(iteratees)) {
33218 iteratees = iteratees == null ? [] : [iteratees];
33219 }
33220 orders = guard ? undefined : orders;
33221 if (!isArray(orders)) {
33222 orders = orders == null ? [] : [orders];
33223 }
33224 return baseOrderBy(collection, iteratees, orders);
33225 }
33226
33227 /**
33228 * Creates an array of elements split into two groups, the first of which
33229 * contains elements `predicate` returns truthy for, the second of which
33230 * contains elements `predicate` returns falsey for. The predicate is
33231 * invoked with one argument: (value).
33232 *
33233 * @static
33234 * @memberOf _
33235 * @since 3.0.0
33236 * @category Collection
33237 * @param {Array|Object} collection The collection to iterate over.
33238 * @param {Function} [predicate=_.identity] The function invoked per iteration.
33239 * @returns {Array} Returns the array of grouped elements.
33240 * @example
33241 *
33242 * var users = [
33243 * { 'user': 'barney', 'age': 36, 'active': false },
33244 * { 'user': 'fred', 'age': 40, 'active': true },
33245 * { 'user': 'pebbles', 'age': 1, 'active': false }
33246 * ];
33247 *
33248 * _.partition(users, function(o) { return o.active; });
33249 * // => objects for [['fred'], ['barney', 'pebbles']]
33250 *
33251 * // The `_.matches` iteratee shorthand.
33252 * _.partition(users, { 'age': 1, 'active': false });
33253 * // => objects for [['pebbles'], ['barney', 'fred']]
33254 *
33255 * // The `_.matchesProperty` iteratee shorthand.
33256 * _.partition(users, ['active', false]);
33257 * // => objects for [['barney', 'pebbles'], ['fred']]
33258 *
33259 * // The `_.property` iteratee shorthand.
33260 * _.partition(users, 'active');
33261 * // => objects for [['fred'], ['barney', 'pebbles']]
33262 */
33263 var partition = createAggregator(function(result, value, key) {
33264 result[key ? 0 : 1].push(value);
33265 }, function() { return [[], []]; });
33266
33267 /**
33268 * Reduces `collection` to a value which is the accumulated result of running
33269 * each element in `collection` thru `iteratee`, where each successive
33270 * invocation is supplied the return value of the previous. If `accumulator`
33271 * is not given, the first element of `collection` is used as the initial
33272 * value. The iteratee is invoked with four arguments:
33273 * (accumulator, value, index|key, collection).
33274 *
33275 * Many lodash methods are guarded to work as iteratees for methods like
33276 * `_.reduce`, `_.reduceRight`, and `_.transform`.
33277 *
33278 * The guarded methods are:
33279 * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
33280 * and `sortBy`
33281 *
33282 * @static
33283 * @memberOf _
33284 * @since 0.1.0
33285 * @category Collection
33286 * @param {Array|Object} collection The collection to iterate over.
33287 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
33288 * @param {*} [accumulator] The initial value.
33289 * @returns {*} Returns the accumulated value.
33290 * @see _.reduceRight
33291 * @example
33292 *
33293 * _.reduce([1, 2], function(sum, n) {
33294 * return sum + n;
33295 * }, 0);
33296 * // => 3
33297 *
33298 * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
33299 * (result[value] || (result[value] = [])).push(key);
33300 * return result;
33301 * }, {});
33302 * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
33303 */
33304 function reduce(collection, iteratee, accumulator) {
33305 var func = isArray(collection) ? arrayReduce : baseReduce,
33306 initAccum = arguments.length < 3;
33307
33308 return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach);
33309 }
33310
33311 /**
33312 * This method is like `_.reduce` except that it iterates over elements of
33313 * `collection` from right to left.
33314 *
33315 * @static
33316 * @memberOf _
33317 * @since 0.1.0
33318 * @category Collection
33319 * @param {Array|Object} collection The collection to iterate over.
33320 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
33321 * @param {*} [accumulator] The initial value.
33322 * @returns {*} Returns the accumulated value.
33323 * @see _.reduce
33324 * @example
33325 *
33326 * var array = [[0, 1], [2, 3], [4, 5]];
33327 *
33328 * _.reduceRight(array, function(flattened, other) {
33329 * return flattened.concat(other);
33330 * }, []);
33331 * // => [4, 5, 2, 3, 0, 1]
33332 */
33333 function reduceRight(collection, iteratee, accumulator) {
33334 var func = isArray(collection) ? arrayReduceRight : baseReduce,
33335 initAccum = arguments.length < 3;
33336
33337 return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight);
33338 }
33339
33340 /**
33341 * The opposite of `_.filter`; this method returns the elements of `collection`
33342 * that `predicate` does **not** return truthy for.
33343 *
33344 * @static
33345 * @memberOf _
33346 * @since 0.1.0
33347 * @category Collection
33348 * @param {Array|Object} collection The collection to iterate over.
33349 * @param {Function} [predicate=_.identity] The function invoked per iteration.
33350 * @returns {Array} Returns the new filtered array.
33351 * @see _.filter
33352 * @example
33353 *
33354 * var users = [
33355 * { 'user': 'barney', 'age': 36, 'active': false },
33356 * { 'user': 'fred', 'age': 40, 'active': true }
33357 * ];
33358 *
33359 * _.reject(users, function(o) { return !o.active; });
33360 * // => objects for ['fred']
33361 *
33362 * // The `_.matches` iteratee shorthand.
33363 * _.reject(users, { 'age': 40, 'active': true });
33364 * // => objects for ['barney']
33365 *
33366 * // The `_.matchesProperty` iteratee shorthand.
33367 * _.reject(users, ['active', false]);
33368 * // => objects for ['fred']
33369 *
33370 * // The `_.property` iteratee shorthand.
33371 * _.reject(users, 'active');
33372 * // => objects for ['barney']
33373 */
33374 function reject(collection, predicate) {
33375 var func = isArray(collection) ? arrayFilter : baseFilter;
33376 return func(collection, negate(getIteratee(predicate, 3)));
33377 }
33378
33379 /**
33380 * Gets a random element from `collection`.
33381 *
33382 * @static
33383 * @memberOf _
33384 * @since 2.0.0
33385 * @category Collection
33386 * @param {Array|Object} collection The collection to sample.
33387 * @returns {*} Returns the random element.
33388 * @example
33389 *
33390 * _.sample([1, 2, 3, 4]);
33391 * // => 2
33392 */
33393 function sample(collection) {
33394 var func = isArray(collection) ? arraySample : baseSample;
33395 return func(collection);
33396 }
33397
33398 /**
33399 * Gets `n` random elements at unique keys from `collection` up to the
33400 * size of `collection`.
33401 *
33402 * @static
33403 * @memberOf _
33404 * @since 4.0.0
33405 * @category Collection
33406 * @param {Array|Object} collection The collection to sample.
33407 * @param {number} [n=1] The number of elements to sample.
33408 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
33409 * @returns {Array} Returns the random elements.
33410 * @example
33411 *
33412 * _.sampleSize([1, 2, 3], 2);
33413 * // => [3, 1]
33414 *
33415 * _.sampleSize([1, 2, 3], 4);
33416 * // => [2, 3, 1]
33417 */
33418 function sampleSize(collection, n, guard) {
33419 if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) {
33420 n = 1;
33421 } else {
33422 n = toInteger(n);
33423 }
33424 var func = isArray(collection) ? arraySampleSize : baseSampleSize;
33425 return func(collection, n);
33426 }
33427
33428 /**
33429 * Creates an array of shuffled values, using a version of the
33430 * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
33431 *
33432 * @static
33433 * @memberOf _
33434 * @since 0.1.0
33435 * @category Collection
33436 * @param {Array|Object} collection The collection to shuffle.
33437 * @returns {Array} Returns the new shuffled array.
33438 * @example
33439 *
33440 * _.shuffle([1, 2, 3, 4]);
33441 * // => [4, 1, 3, 2]
33442 */
33443 function shuffle(collection) {
33444 var func = isArray(collection) ? arrayShuffle : baseShuffle;
33445 return func(collection);
33446 }
33447
33448 /**
33449 * Gets the size of `collection` by returning its length for array-like
33450 * values or the number of own enumerable string keyed properties for objects.
33451 *
33452 * @static
33453 * @memberOf _
33454 * @since 0.1.0
33455 * @category Collection
33456 * @param {Array|Object|string} collection The collection to inspect.
33457 * @returns {number} Returns the collection size.
33458 * @example
33459 *
33460 * _.size([1, 2, 3]);
33461 * // => 3
33462 *
33463 * _.size({ 'a': 1, 'b': 2 });
33464 * // => 2
33465 *
33466 * _.size('pebbles');
33467 * // => 7
33468 */
33469 function size(collection) {
33470 if (collection == null) {
33471 return 0;
33472 }
33473 if (isArrayLike(collection)) {
33474 return isString(collection) ? stringSize(collection) : collection.length;
33475 }
33476 var tag = getTag(collection);
33477 if (tag == mapTag || tag == setTag) {
33478 return collection.size;
33479 }
33480 return baseKeys(collection).length;
33481 }
33482
33483 /**
33484 * Checks if `predicate` returns truthy for **any** element of `collection`.
33485 * Iteration is stopped once `predicate` returns truthy. The predicate is
33486 * invoked with three arguments: (value, index|key, collection).
33487 *
33488 * @static
33489 * @memberOf _
33490 * @since 0.1.0
33491 * @category Collection
33492 * @param {Array|Object} collection The collection to iterate over.
33493 * @param {Function} [predicate=_.identity] The function invoked per iteration.
33494 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
33495 * @returns {boolean} Returns `true` if any element passes the predicate check,
33496 * else `false`.
33497 * @example
33498 *
33499 * _.some([null, 0, 'yes', false], Boolean);
33500 * // => true
33501 *
33502 * var users = [
33503 * { 'user': 'barney', 'active': true },
33504 * { 'user': 'fred', 'active': false }
33505 * ];
33506 *
33507 * // The `_.matches` iteratee shorthand.
33508 * _.some(users, { 'user': 'barney', 'active': false });
33509 * // => false
33510 *
33511 * // The `_.matchesProperty` iteratee shorthand.
33512 * _.some(users, ['active', false]);
33513 * // => true
33514 *
33515 * // The `_.property` iteratee shorthand.
33516 * _.some(users, 'active');
33517 * // => true
33518 */
33519 function some(collection, predicate, guard) {
33520 var func = isArray(collection) ? arraySome : baseSome;
33521 if (guard && isIterateeCall(collection, predicate, guard)) {
33522 predicate = undefined;
33523 }
33524 return func(collection, getIteratee(predicate, 3));
33525 }
33526
33527 /**
33528 * Creates an array of elements, sorted in ascending order by the results of
33529 * running each element in a collection thru each iteratee. This method
33530 * performs a stable sort, that is, it preserves the original sort order of
33531 * equal elements. The iteratees are invoked with one argument: (value).
33532 *
33533 * @static
33534 * @memberOf _
33535 * @since 0.1.0
33536 * @category Collection
33537 * @param {Array|Object} collection The collection to iterate over.
33538 * @param {...(Function|Function[])} [iteratees=[_.identity]]
33539 * The iteratees to sort by.
33540 * @returns {Array} Returns the new sorted array.
33541 * @example
33542 *
33543 * var users = [
33544 * { 'user': 'fred', 'age': 48 },
33545 * { 'user': 'barney', 'age': 36 },
33546 * { 'user': 'fred', 'age': 40 },
33547 * { 'user': 'barney', 'age': 34 }
33548 * ];
33549 *
33550 * _.sortBy(users, [function(o) { return o.user; }]);
33551 * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
33552 *
33553 * _.sortBy(users, ['user', 'age']);
33554 * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]]
33555 */
33556 var sortBy = baseRest(function(collection, iteratees) {
33557 if (collection == null) {
33558 return [];
33559 }
33560 var length = iteratees.length;
33561 if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {
33562 iteratees = [];
33563 } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
33564 iteratees = [iteratees[0]];
33565 }
33566 return baseOrderBy(collection, baseFlatten(iteratees, 1), []);
33567 });
33568
33569 /*------------------------------------------------------------------------*/
33570
33571 /**
33572 * Gets the timestamp of the number of milliseconds that have elapsed since
33573 * the Unix epoch (1 January 1970 00:00:00 UTC).
33574 *
33575 * @static
33576 * @memberOf _
33577 * @since 2.4.0
33578 * @category Date
33579 * @returns {number} Returns the timestamp.
33580 * @example
33581 *
33582 * _.defer(function(stamp) {
33583 * console.log(_.now() - stamp);
33584 * }, _.now());
33585 * // => Logs the number of milliseconds it took for the deferred invocation.
33586 */
33587 var now = ctxNow || function() {
33588 return root.Date.now();
33589 };
33590
33591 /*------------------------------------------------------------------------*/
33592
33593 /**
33594 * The opposite of `_.before`; this method creates a function that invokes
33595 * `func` once it's called `n` or more times.
33596 *
33597 * @static
33598 * @memberOf _
33599 * @since 0.1.0
33600 * @category Function
33601 * @param {number} n The number of calls before `func` is invoked.
33602 * @param {Function} func The function to restrict.
33603 * @returns {Function} Returns the new restricted function.
33604 * @example
33605 *
33606 * var saves = ['profile', 'settings'];
33607 *
33608 * var done = _.after(saves.length, function() {
33609 * console.log('done saving!');
33610 * });
33611 *
33612 * _.forEach(saves, function(type) {
33613 * asyncSave({ 'type': type, 'complete': done });
33614 * });
33615 * // => Logs 'done saving!' after the two async saves have completed.
33616 */
33617 function after(n, func) {
33618 if (typeof func != 'function') {
33619 throw new TypeError(FUNC_ERROR_TEXT);
33620 }
33621 n = toInteger(n);
33622 return function() {
33623 if (--n < 1) {
33624 return func.apply(this, arguments);
33625 }
33626 };
33627 }
33628
33629 /**
33630 * Creates a function that invokes `func`, with up to `n` arguments,
33631 * ignoring any additional arguments.
33632 *
33633 * @static
33634 * @memberOf _
33635 * @since 3.0.0
33636 * @category Function
33637 * @param {Function} func The function to cap arguments for.
33638 * @param {number} [n=func.length] The arity cap.
33639 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
33640 * @returns {Function} Returns the new capped function.
33641 * @example
33642 *
33643 * _.map(['6', '8', '10'], _.ary(parseInt, 1));
33644 * // => [6, 8, 10]
33645 */
33646 function ary(func, n, guard) {
33647 n = guard ? undefined : n;
33648 n = (func && n == null) ? func.length : n;
33649 return createWrap(func, ARY_FLAG, undefined, undefined, undefined, undefined, n);
33650 }
33651
33652 /**
33653 * Creates a function that invokes `func`, with the `this` binding and arguments
33654 * of the created function, while it's called less than `n` times. Subsequent
33655 * calls to the created function return the result of the last `func` invocation.
33656 *
33657 * @static
33658 * @memberOf _
33659 * @since 3.0.0
33660 * @category Function
33661 * @param {number} n The number of calls at which `func` is no longer invoked.
33662 * @param {Function} func The function to restrict.
33663 * @returns {Function} Returns the new restricted function.
33664 * @example
33665 *
33666 * jQuery(element).on('click', _.before(5, addContactToList));
33667 * // => Allows adding up to 4 contacts to the list.
33668 */
33669 function before(n, func) {
33670 var result;
33671 if (typeof func != 'function') {
33672 throw new TypeError(FUNC_ERROR_TEXT);
33673 }
33674 n = toInteger(n);
33675 return function() {
33676 if (--n > 0) {
33677 result = func.apply(this, arguments);
33678 }
33679 if (n <= 1) {
33680 func = undefined;
33681 }
33682 return result;
33683 };
33684 }
33685
33686 /**
33687 * Creates a function that invokes `func` with the `this` binding of `thisArg`
33688 * and `partials` prepended to the arguments it receives.
33689 *
33690 * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
33691 * may be used as a placeholder for partially applied arguments.
33692 *
33693 * **Note:** Unlike native `Function#bind`, this method doesn't set the "length"
33694 * property of bound functions.
33695 *
33696 * @static
33697 * @memberOf _
33698 * @since 0.1.0
33699 * @category Function
33700 * @param {Function} func The function to bind.
33701 * @param {*} thisArg The `this` binding of `func`.
33702 * @param {...*} [partials] The arguments to be partially applied.
33703 * @returns {Function} Returns the new bound function.
33704 * @example
33705 *
33706 * function greet(greeting, punctuation) {
33707 * return greeting + ' ' + this.user + punctuation;
33708 * }
33709 *
33710 * var object = { 'user': 'fred' };
33711 *
33712 * var bound = _.bind(greet, object, 'hi');
33713 * bound('!');
33714 * // => 'hi fred!'
33715 *
33716 * // Bound with placeholders.
33717 * var bound = _.bind(greet, object, _, '!');
33718 * bound('hi');
33719 * // => 'hi fred!'
33720 */
33721 var bind = baseRest(function(func, thisArg, partials) {
33722 var bitmask = BIND_FLAG;
33723 if (partials.length) {
33724 var holders = replaceHolders(partials, getHolder(bind));
33725 bitmask |= PARTIAL_FLAG;
33726 }
33727 return createWrap(func, bitmask, thisArg, partials, holders);
33728 });
33729
33730 /**
33731 * Creates a function that invokes the method at `object[key]` with `partials`
33732 * prepended to the arguments it receives.
33733 *
33734 * This method differs from `_.bind` by allowing bound functions to reference
33735 * methods that may be redefined or don't yet exist. See
33736 * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)
33737 * for more details.
33738 *
33739 * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic
33740 * builds, may be used as a placeholder for partially applied arguments.
33741 *
33742 * @static
33743 * @memberOf _
33744 * @since 0.10.0
33745 * @category Function
33746 * @param {Object} object The object to invoke the method on.
33747 * @param {string} key The key of the method.
33748 * @param {...*} [partials] The arguments to be partially applied.
33749 * @returns {Function} Returns the new bound function.
33750 * @example
33751 *
33752 * var object = {
33753 * 'user': 'fred',
33754 * 'greet': function(greeting, punctuation) {
33755 * return greeting + ' ' + this.user + punctuation;
33756 * }
33757 * };
33758 *
33759 * var bound = _.bindKey(object, 'greet', 'hi');
33760 * bound('!');
33761 * // => 'hi fred!'
33762 *
33763 * object.greet = function(greeting, punctuation) {
33764 * return greeting + 'ya ' + this.user + punctuation;
33765 * };
33766 *
33767 * bound('!');
33768 * // => 'hiya fred!'
33769 *
33770 * // Bound with placeholders.
33771 * var bound = _.bindKey(object, 'greet', _, '!');
33772 * bound('hi');
33773 * // => 'hiya fred!'
33774 */
33775 var bindKey = baseRest(function(object, key, partials) {
33776 var bitmask = BIND_FLAG | BIND_KEY_FLAG;
33777 if (partials.length) {
33778 var holders = replaceHolders(partials, getHolder(bindKey));
33779 bitmask |= PARTIAL_FLAG;
33780 }
33781 return createWrap(key, bitmask, object, partials, holders);
33782 });
33783
33784 /**
33785 * Creates a function that accepts arguments of `func` and either invokes
33786 * `func` returning its result, if at least `arity` number of arguments have
33787 * been provided, or returns a function that accepts the remaining `func`
33788 * arguments, and so on. The arity of `func` may be specified if `func.length`
33789 * is not sufficient.
33790 *
33791 * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
33792 * may be used as a placeholder for provided arguments.
33793 *
33794 * **Note:** This method doesn't set the "length" property of curried functions.
33795 *
33796 * @static
33797 * @memberOf _
33798 * @since 2.0.0
33799 * @category Function
33800 * @param {Function} func The function to curry.
33801 * @param {number} [arity=func.length] The arity of `func`.
33802 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
33803 * @returns {Function} Returns the new curried function.
33804 * @example
33805 *
33806 * var abc = function(a, b, c) {
33807 * return [a, b, c];
33808 * };
33809 *
33810 * var curried = _.curry(abc);
33811 *
33812 * curried(1)(2)(3);
33813 * // => [1, 2, 3]
33814 *
33815 * curried(1, 2)(3);
33816 * // => [1, 2, 3]
33817 *
33818 * curried(1, 2, 3);
33819 * // => [1, 2, 3]
33820 *
33821 * // Curried with placeholders.
33822 * curried(1)(_, 3)(2);
33823 * // => [1, 2, 3]
33824 */
33825 function curry(func, arity, guard) {
33826 arity = guard ? undefined : arity;
33827 var result = createWrap(func, CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
33828 result.placeholder = curry.placeholder;
33829 return result;
33830 }
33831
33832 /**
33833 * This method is like `_.curry` except that arguments are applied to `func`
33834 * in the manner of `_.partialRight` instead of `_.partial`.
33835 *
33836 * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
33837 * builds, may be used as a placeholder for provided arguments.
33838 *
33839 * **Note:** This method doesn't set the "length" property of curried functions.
33840 *
33841 * @static
33842 * @memberOf _
33843 * @since 3.0.0
33844 * @category Function
33845 * @param {Function} func The function to curry.
33846 * @param {number} [arity=func.length] The arity of `func`.
33847 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
33848 * @returns {Function} Returns the new curried function.
33849 * @example
33850 *
33851 * var abc = function(a, b, c) {
33852 * return [a, b, c];
33853 * };
33854 *
33855 * var curried = _.curryRight(abc);
33856 *
33857 * curried(3)(2)(1);
33858 * // => [1, 2, 3]
33859 *
33860 * curried(2, 3)(1);
33861 * // => [1, 2, 3]
33862 *
33863 * curried(1, 2, 3);
33864 * // => [1, 2, 3]
33865 *
33866 * // Curried with placeholders.
33867 * curried(3)(1, _)(2);
33868 * // => [1, 2, 3]
33869 */
33870 function curryRight(func, arity, guard) {
33871 arity = guard ? undefined : arity;
33872 var result = createWrap(func, CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
33873 result.placeholder = curryRight.placeholder;
33874 return result;
33875 }
33876
33877 /**
33878 * Creates a debounced function that delays invoking `func` until after `wait`
33879 * milliseconds have elapsed since the last time the debounced function was
33880 * invoked. The debounced function comes with a `cancel` method to cancel
33881 * delayed `func` invocations and a `flush` method to immediately invoke them.
33882 * Provide `options` to indicate whether `func` should be invoked on the
33883 * leading and/or trailing edge of the `wait` timeout. The `func` is invoked
33884 * with the last arguments provided to the debounced function. Subsequent
33885 * calls to the debounced function return the result of the last `func`
33886 * invocation.
33887 *
33888 * **Note:** If `leading` and `trailing` options are `true`, `func` is
33889 * invoked on the trailing edge of the timeout only if the debounced function
33890 * is invoked more than once during the `wait` timeout.
33891 *
33892 * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
33893 * until to the next tick, similar to `setTimeout` with a timeout of `0`.
33894 *
33895 * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
33896 * for details over the differences between `_.debounce` and `_.throttle`.
33897 *
33898 * @static
33899 * @memberOf _
33900 * @since 0.1.0
33901 * @category Function
33902 * @param {Function} func The function to debounce.
33903 * @param {number} [wait=0] The number of milliseconds to delay.
33904 * @param {Object} [options={}] The options object.
33905 * @param {boolean} [options.leading=false]
33906 * Specify invoking on the leading edge of the timeout.
33907 * @param {number} [options.maxWait]
33908 * The maximum time `func` is allowed to be delayed before it's invoked.
33909 * @param {boolean} [options.trailing=true]
33910 * Specify invoking on the trailing edge of the timeout.
33911 * @returns {Function} Returns the new debounced function.
33912 * @example
33913 *
33914 * // Avoid costly calculations while the window size is in flux.
33915 * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
33916 *
33917 * // Invoke `sendMail` when clicked, debouncing subsequent calls.
33918 * jQuery(element).on('click', _.debounce(sendMail, 300, {
33919 * 'leading': true,
33920 * 'trailing': false
33921 * }));
33922 *
33923 * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
33924 * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
33925 * var source = new EventSource('/stream');
33926 * jQuery(source).on('message', debounced);
33927 *
33928 * // Cancel the trailing debounced invocation.
33929 * jQuery(window).on('popstate', debounced.cancel);
33930 */
33931 function debounce(func, wait, options) {
33932 var lastArgs,
33933 lastThis,
33934 maxWait,
33935 result,
33936 timerId,
33937 lastCallTime,
33938 lastInvokeTime = 0,
33939 leading = false,
33940 maxing = false,
33941 trailing = true;
33942
33943 if (typeof func != 'function') {
33944 throw new TypeError(FUNC_ERROR_TEXT);
33945 }
33946 wait = toNumber(wait) || 0;
33947 if (isObject(options)) {
33948 leading = !!options.leading;
33949 maxing = 'maxWait' in options;
33950 maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
33951 trailing = 'trailing' in options ? !!options.trailing : trailing;
33952 }
33953
33954 function invokeFunc(time) {
33955 var args = lastArgs,
33956 thisArg = lastThis;
33957
33958 lastArgs = lastThis = undefined;
33959 lastInvokeTime = time;
33960 result = func.apply(thisArg, args);
33961 return result;
33962 }
33963
33964 function leadingEdge(time) {
33965 // Reset any `maxWait` timer.
33966 lastInvokeTime = time;
33967 // Start the timer for the trailing edge.
33968 timerId = setTimeout(timerExpired, wait);
33969 // Invoke the leading edge.
33970 return leading ? invokeFunc(time) : result;
33971 }
33972
33973 function remainingWait(time) {
33974 var timeSinceLastCall = time - lastCallTime,
33975 timeSinceLastInvoke = time - lastInvokeTime,
33976 result = wait - timeSinceLastCall;
33977
33978 return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;
33979 }
33980
33981 function shouldInvoke(time) {
33982 var timeSinceLastCall = time - lastCallTime,
33983 timeSinceLastInvoke = time - lastInvokeTime;
33984
33985 // Either this is the first call, activity has stopped and we're at the
33986 // trailing edge, the system time has gone backwards and we're treating
33987 // it as the trailing edge, or we've hit the `maxWait` limit.
33988 return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
33989 (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
33990 }
33991
33992 function timerExpired() {
33993 var time = now();
33994 if (shouldInvoke(time)) {
33995 return trailingEdge(time);
33996 }
33997 // Restart the timer.
33998 timerId = setTimeout(timerExpired, remainingWait(time));
33999 }
34000
34001 function trailingEdge(time) {
34002 timerId = undefined;
34003
34004 // Only invoke if we have `lastArgs` which means `func` has been
34005 // debounced at least once.
34006 if (trailing && lastArgs) {
34007 return invokeFunc(time);
34008 }
34009 lastArgs = lastThis = undefined;
34010 return result;
34011 }
34012
34013 function cancel() {
34014 if (timerId !== undefined) {
34015 clearTimeout(timerId);
34016 }
34017 lastInvokeTime = 0;
34018 lastArgs = lastCallTime = lastThis = timerId = undefined;
34019 }
34020
34021 function flush() {
34022 return timerId === undefined ? result : trailingEdge(now());
34023 }
34024
34025 function debounced() {
34026 var time = now(),
34027 isInvoking = shouldInvoke(time);
34028
34029 lastArgs = arguments;
34030 lastThis = this;
34031 lastCallTime = time;
34032
34033 if (isInvoking) {
34034 if (timerId === undefined) {
34035 return leadingEdge(lastCallTime);
34036 }
34037 if (maxing) {
34038 // Handle invocations in a tight loop.
34039 timerId = setTimeout(timerExpired, wait);
34040 return invokeFunc(lastCallTime);
34041 }
34042 }
34043 if (timerId === undefined) {
34044 timerId = setTimeout(timerExpired, wait);
34045 }
34046 return result;
34047 }
34048 debounced.cancel = cancel;
34049 debounced.flush = flush;
34050 return debounced;
34051 }
34052
34053 /**
34054 * Defers invoking the `func` until the current call stack has cleared. Any
34055 * additional arguments are provided to `func` when it's invoked.
34056 *
34057 * @static
34058 * @memberOf _
34059 * @since 0.1.0
34060 * @category Function
34061 * @param {Function} func The function to defer.
34062 * @param {...*} [args] The arguments to invoke `func` with.
34063 * @returns {number} Returns the timer id.
34064 * @example
34065 *
34066 * _.defer(function(text) {
34067 * console.log(text);
34068 * }, 'deferred');
34069 * // => Logs 'deferred' after one millisecond.
34070 */
34071 var defer = baseRest(function(func, args) {
34072 return baseDelay(func, 1, args);
34073 });
34074
34075 /**
34076 * Invokes `func` after `wait` milliseconds. Any additional arguments are
34077 * provided to `func` when it's invoked.
34078 *
34079 * @static
34080 * @memberOf _
34081 * @since 0.1.0
34082 * @category Function
34083 * @param {Function} func The function to delay.
34084 * @param {number} wait The number of milliseconds to delay invocation.
34085 * @param {...*} [args] The arguments to invoke `func` with.
34086 * @returns {number} Returns the timer id.
34087 * @example
34088 *
34089 * _.delay(function(text) {
34090 * console.log(text);
34091 * }, 1000, 'later');
34092 * // => Logs 'later' after one second.
34093 */
34094 var delay = baseRest(function(func, wait, args) {
34095 return baseDelay(func, toNumber(wait) || 0, args);
34096 });
34097
34098 /**
34099 * Creates a function that invokes `func` with arguments reversed.
34100 *
34101 * @static
34102 * @memberOf _
34103 * @since 4.0.0
34104 * @category Function
34105 * @param {Function} func The function to flip arguments for.
34106 * @returns {Function} Returns the new flipped function.
34107 * @example
34108 *
34109 * var flipped = _.flip(function() {
34110 * return _.toArray(arguments);
34111 * });
34112 *
34113 * flipped('a', 'b', 'c', 'd');
34114 * // => ['d', 'c', 'b', 'a']
34115 */
34116 function flip(func) {
34117 return createWrap(func, FLIP_FLAG);
34118 }
34119
34120 /**
34121 * Creates a function that memoizes the result of `func`. If `resolver` is
34122 * provided, it determines the cache key for storing the result based on the
34123 * arguments provided to the memoized function. By default, the first argument
34124 * provided to the memoized function is used as the map cache key. The `func`
34125 * is invoked with the `this` binding of the memoized function.
34126 *
34127 * **Note:** The cache is exposed as the `cache` property on the memoized
34128 * function. Its creation may be customized by replacing the `_.memoize.Cache`
34129 * constructor with one whose instances implement the
34130 * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
34131 * method interface of `delete`, `get`, `has`, and `set`.
34132 *
34133 * @static
34134 * @memberOf _
34135 * @since 0.1.0
34136 * @category Function
34137 * @param {Function} func The function to have its output memoized.
34138 * @param {Function} [resolver] The function to resolve the cache key.
34139 * @returns {Function} Returns the new memoized function.
34140 * @example
34141 *
34142 * var object = { 'a': 1, 'b': 2 };
34143 * var other = { 'c': 3, 'd': 4 };
34144 *
34145 * var values = _.memoize(_.values);
34146 * values(object);
34147 * // => [1, 2]
34148 *
34149 * values(other);
34150 * // => [3, 4]
34151 *
34152 * object.a = 2;
34153 * values(object);
34154 * // => [1, 2]
34155 *
34156 * // Modify the result cache.
34157 * values.cache.set(object, ['a', 'b']);
34158 * values(object);
34159 * // => ['a', 'b']
34160 *
34161 * // Replace `_.memoize.Cache`.
34162 * _.memoize.Cache = WeakMap;
34163 */
34164 function memoize(func, resolver) {
34165 if (typeof func != 'function' || (resolver && typeof resolver != 'function')) {
34166 throw new TypeError(FUNC_ERROR_TEXT);
34167 }
34168 var memoized = function() {
34169 var args = arguments,
34170 key = resolver ? resolver.apply(this, args) : args[0],
34171 cache = memoized.cache;
34172
34173 if (cache.has(key)) {
34174 return cache.get(key);
34175 }
34176 var result = func.apply(this, args);
34177 memoized.cache = cache.set(key, result) || cache;
34178 return result;
34179 };
34180 memoized.cache = new (memoize.Cache || MapCache);
34181 return memoized;
34182 }
34183
34184 // Expose `MapCache`.
34185 memoize.Cache = MapCache;
34186
34187 /**
34188 * Creates a function that negates the result of the predicate `func`. The
34189 * `func` predicate is invoked with the `this` binding and arguments of the
34190 * created function.
34191 *
34192 * @static
34193 * @memberOf _
34194 * @since 3.0.0
34195 * @category Function
34196 * @param {Function} predicate The predicate to negate.
34197 * @returns {Function} Returns the new negated function.
34198 * @example
34199 *
34200 * function isEven(n) {
34201 * return n % 2 == 0;
34202 * }
34203 *
34204 * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
34205 * // => [1, 3, 5]
34206 */
34207 function negate(predicate) {
34208 if (typeof predicate != 'function') {
34209 throw new TypeError(FUNC_ERROR_TEXT);
34210 }
34211 return function() {
34212 var args = arguments;
34213 switch (args.length) {
34214 case 0: return !predicate.call(this);
34215 case 1: return !predicate.call(this, args[0]);
34216 case 2: return !predicate.call(this, args[0], args[1]);
34217 case 3: return !predicate.call(this, args[0], args[1], args[2]);
34218 }
34219 return !predicate.apply(this, args);
34220 };
34221 }
34222
34223 /**
34224 * Creates a function that is restricted to invoking `func` once. Repeat calls
34225 * to the function return the value of the first invocation. The `func` is
34226 * invoked with the `this` binding and arguments of the created function.
34227 *
34228 * @static
34229 * @memberOf _
34230 * @since 0.1.0
34231 * @category Function
34232 * @param {Function} func The function to restrict.
34233 * @returns {Function} Returns the new restricted function.
34234 * @example
34235 *
34236 * var initialize = _.once(createApplication);
34237 * initialize();
34238 * initialize();
34239 * // => `createApplication` is invoked once
34240 */
34241 function once(func) {
34242 return before(2, func);
34243 }
34244
34245 /**
34246 * Creates a function that invokes `func` with its arguments transformed.
34247 *
34248 * @static
34249 * @since 4.0.0
34250 * @memberOf _
34251 * @category Function
34252 * @param {Function} func The function to wrap.
34253 * @param {...(Function|Function[])} [transforms=[_.identity]]
34254 * The argument transforms.
34255 * @returns {Function} Returns the new function.
34256 * @example
34257 *
34258 * function doubled(n) {
34259 * return n * 2;
34260 * }
34261 *
34262 * function square(n) {
34263 * return n * n;
34264 * }
34265 *
34266 * var func = _.overArgs(function(x, y) {
34267 * return [x, y];
34268 * }, [square, doubled]);
34269 *
34270 * func(9, 3);
34271 * // => [81, 6]
34272 *
34273 * func(10, 5);
34274 * // => [100, 10]
34275 */
34276 var overArgs = castRest(function(func, transforms) {
34277 transforms = (transforms.length == 1 && isArray(transforms[0]))
34278 ? arrayMap(transforms[0], baseUnary(getIteratee()))
34279 : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee()));
34280
34281 var funcsLength = transforms.length;
34282 return baseRest(function(args) {
34283 var index = -1,
34284 length = nativeMin(args.length, funcsLength);
34285
34286 while (++index < length) {
34287 args[index] = transforms[index].call(this, args[index]);
34288 }
34289 return apply(func, this, args);
34290 });
34291 });
34292
34293 /**
34294 * Creates a function that invokes `func` with `partials` prepended to the
34295 * arguments it receives. This method is like `_.bind` except it does **not**
34296 * alter the `this` binding.
34297 *
34298 * The `_.partial.placeholder` value, which defaults to `_` in monolithic
34299 * builds, may be used as a placeholder for partially applied arguments.
34300 *
34301 * **Note:** This method doesn't set the "length" property of partially
34302 * applied functions.
34303 *
34304 * @static
34305 * @memberOf _
34306 * @since 0.2.0
34307 * @category Function
34308 * @param {Function} func The function to partially apply arguments to.
34309 * @param {...*} [partials] The arguments to be partially applied.
34310 * @returns {Function} Returns the new partially applied function.
34311 * @example
34312 *
34313 * function greet(greeting, name) {
34314 * return greeting + ' ' + name;
34315 * }
34316 *
34317 * var sayHelloTo = _.partial(greet, 'hello');
34318 * sayHelloTo('fred');
34319 * // => 'hello fred'
34320 *
34321 * // Partially applied with placeholders.
34322 * var greetFred = _.partial(greet, _, 'fred');
34323 * greetFred('hi');
34324 * // => 'hi fred'
34325 */
34326 var partial = baseRest(function(func, partials) {
34327 var holders = replaceHolders(partials, getHolder(partial));
34328 return createWrap(func, PARTIAL_FLAG, undefined, partials, holders);
34329 });
34330
34331 /**
34332 * This method is like `_.partial` except that partially applied arguments
34333 * are appended to the arguments it receives.
34334 *
34335 * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
34336 * builds, may be used as a placeholder for partially applied arguments.
34337 *
34338 * **Note:** This method doesn't set the "length" property of partially
34339 * applied functions.
34340 *
34341 * @static
34342 * @memberOf _
34343 * @since 1.0.0
34344 * @category Function
34345 * @param {Function} func The function to partially apply arguments to.
34346 * @param {...*} [partials] The arguments to be partially applied.
34347 * @returns {Function} Returns the new partially applied function.
34348 * @example
34349 *
34350 * function greet(greeting, name) {
34351 * return greeting + ' ' + name;
34352 * }
34353 *
34354 * var greetFred = _.partialRight(greet, 'fred');
34355 * greetFred('hi');
34356 * // => 'hi fred'
34357 *
34358 * // Partially applied with placeholders.
34359 * var sayHelloTo = _.partialRight(greet, 'hello', _);
34360 * sayHelloTo('fred');
34361 * // => 'hello fred'
34362 */
34363 var partialRight = baseRest(function(func, partials) {
34364 var holders = replaceHolders(partials, getHolder(partialRight));
34365 return createWrap(func, PARTIAL_RIGHT_FLAG, undefined, partials, holders);
34366 });
34367
34368 /**
34369 * Creates a function that invokes `func` with arguments arranged according
34370 * to the specified `indexes` where the argument value at the first index is
34371 * provided as the first argument, the argument value at the second index is
34372 * provided as the second argument, and so on.
34373 *
34374 * @static
34375 * @memberOf _
34376 * @since 3.0.0
34377 * @category Function
34378 * @param {Function} func The function to rearrange arguments for.
34379 * @param {...(number|number[])} indexes The arranged argument indexes.
34380 * @returns {Function} Returns the new function.
34381 * @example
34382 *
34383 * var rearged = _.rearg(function(a, b, c) {
34384 * return [a, b, c];
34385 * }, [2, 0, 1]);
34386 *
34387 * rearged('b', 'c', 'a')
34388 * // => ['a', 'b', 'c']
34389 */
34390 var rearg = flatRest(function(func, indexes) {
34391 return createWrap(func, REARG_FLAG, undefined, undefined, undefined, indexes);
34392 });
34393
34394 /**
34395 * Creates a function that invokes `func` with the `this` binding of the
34396 * created function and arguments from `start` and beyond provided as
34397 * an array.
34398 *
34399 * **Note:** This method is based on the
34400 * [rest parameter](https://mdn.io/rest_parameters).
34401 *
34402 * @static
34403 * @memberOf _
34404 * @since 4.0.0
34405 * @category Function
34406 * @param {Function} func The function to apply a rest parameter to.
34407 * @param {number} [start=func.length-1] The start position of the rest parameter.
34408 * @returns {Function} Returns the new function.
34409 * @example
34410 *
34411 * var say = _.rest(function(what, names) {
34412 * return what + ' ' + _.initial(names).join(', ') +
34413 * (_.size(names) > 1 ? ', & ' : '') + _.last(names);
34414 * });
34415 *
34416 * say('hello', 'fred', 'barney', 'pebbles');
34417 * // => 'hello fred, barney, & pebbles'
34418 */
34419 function rest(func, start) {
34420 if (typeof func != 'function') {
34421 throw new TypeError(FUNC_ERROR_TEXT);
34422 }
34423 start = start === undefined ? start : toInteger(start);
34424 return baseRest(func, start);
34425 }
34426
34427 /**
34428 * Creates a function that invokes `func` with the `this` binding of the
34429 * create function and an array of arguments much like
34430 * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply).
34431 *
34432 * **Note:** This method is based on the
34433 * [spread operator](https://mdn.io/spread_operator).
34434 *
34435 * @static
34436 * @memberOf _
34437 * @since 3.2.0
34438 * @category Function
34439 * @param {Function} func The function to spread arguments over.
34440 * @param {number} [start=0] The start position of the spread.
34441 * @returns {Function} Returns the new function.
34442 * @example
34443 *
34444 * var say = _.spread(function(who, what) {
34445 * return who + ' says ' + what;
34446 * });
34447 *
34448 * say(['fred', 'hello']);
34449 * // => 'fred says hello'
34450 *
34451 * var numbers = Promise.all([
34452 * Promise.resolve(40),
34453 * Promise.resolve(36)
34454 * ]);
34455 *
34456 * numbers.then(_.spread(function(x, y) {
34457 * return x + y;
34458 * }));
34459 * // => a Promise of 76
34460 */
34461 function spread(func, start) {
34462 if (typeof func != 'function') {
34463 throw new TypeError(FUNC_ERROR_TEXT);
34464 }
34465 start = start === undefined ? 0 : nativeMax(toInteger(start), 0);
34466 return baseRest(function(args) {
34467 var array = args[start],
34468 otherArgs = castSlice(args, 0, start);
34469
34470 if (array) {
34471 arrayPush(otherArgs, array);
34472 }
34473 return apply(func, this, otherArgs);
34474 });
34475 }
34476
34477 /**
34478 * Creates a throttled function that only invokes `func` at most once per
34479 * every `wait` milliseconds. The throttled function comes with a `cancel`
34480 * method to cancel delayed `func` invocations and a `flush` method to
34481 * immediately invoke them. Provide `options` to indicate whether `func`
34482 * should be invoked on the leading and/or trailing edge of the `wait`
34483 * timeout. The `func` is invoked with the last arguments provided to the
34484 * throttled function. Subsequent calls to the throttled function return the
34485 * result of the last `func` invocation.
34486 *
34487 * **Note:** If `leading` and `trailing` options are `true`, `func` is
34488 * invoked on the trailing edge of the timeout only if the throttled function
34489 * is invoked more than once during the `wait` timeout.
34490 *
34491 * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
34492 * until to the next tick, similar to `setTimeout` with a timeout of `0`.
34493 *
34494 * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
34495 * for details over the differences between `_.throttle` and `_.debounce`.
34496 *
34497 * @static
34498 * @memberOf _
34499 * @since 0.1.0
34500 * @category Function
34501 * @param {Function} func The function to throttle.
34502 * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
34503 * @param {Object} [options={}] The options object.
34504 * @param {boolean} [options.leading=true]
34505 * Specify invoking on the leading edge of the timeout.
34506 * @param {boolean} [options.trailing=true]
34507 * Specify invoking on the trailing edge of the timeout.
34508 * @returns {Function} Returns the new throttled function.
34509 * @example
34510 *
34511 * // Avoid excessively updating the position while scrolling.
34512 * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
34513 *
34514 * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
34515 * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
34516 * jQuery(element).on('click', throttled);
34517 *
34518 * // Cancel the trailing throttled invocation.
34519 * jQuery(window).on('popstate', throttled.cancel);
34520 */
34521 function throttle(func, wait, options) {
34522 var leading = true,
34523 trailing = true;
34524
34525 if (typeof func != 'function') {
34526 throw new TypeError(FUNC_ERROR_TEXT);
34527 }
34528 if (isObject(options)) {
34529 leading = 'leading' in options ? !!options.leading : leading;
34530 trailing = 'trailing' in options ? !!options.trailing : trailing;
34531 }
34532 return debounce(func, wait, {
34533 'leading': leading,
34534 'maxWait': wait,
34535 'trailing': trailing
34536 });
34537 }
34538
34539 /**
34540 * Creates a function that accepts up to one argument, ignoring any
34541 * additional arguments.
34542 *
34543 * @static
34544 * @memberOf _
34545 * @since 4.0.0
34546 * @category Function
34547 * @param {Function} func The function to cap arguments for.
34548 * @returns {Function} Returns the new capped function.
34549 * @example
34550 *
34551 * _.map(['6', '8', '10'], _.unary(parseInt));
34552 * // => [6, 8, 10]
34553 */
34554 function unary(func) {
34555 return ary(func, 1);
34556 }
34557
34558 /**
34559 * Creates a function that provides `value` to `wrapper` as its first
34560 * argument. Any additional arguments provided to the function are appended
34561 * to those provided to the `wrapper`. The wrapper is invoked with the `this`
34562 * binding of the created function.
34563 *
34564 * @static
34565 * @memberOf _
34566 * @since 0.1.0
34567 * @category Function
34568 * @param {*} value The value to wrap.
34569 * @param {Function} [wrapper=identity] The wrapper function.
34570 * @returns {Function} Returns the new function.
34571 * @example
34572 *
34573 * var p = _.wrap(_.escape, function(func, text) {
34574 * return '<p>' + func(text) + '</p>';
34575 * });
34576 *
34577 * p('fred, barney, & pebbles');
34578 * // => '<p>fred, barney, &amp; pebbles</p>'
34579 */
34580 function wrap(value, wrapper) {
34581 wrapper = wrapper == null ? identity : wrapper;
34582 return partial(wrapper, value);
34583 }
34584
34585 /*------------------------------------------------------------------------*/
34586
34587 /**
34588 * Casts `value` as an array if it's not one.
34589 *
34590 * @static
34591 * @memberOf _
34592 * @since 4.4.0
34593 * @category Lang
34594 * @param {*} value The value to inspect.
34595 * @returns {Array} Returns the cast array.
34596 * @example
34597 *
34598 * _.castArray(1);
34599 * // => [1]
34600 *
34601 * _.castArray({ 'a': 1 });
34602 * // => [{ 'a': 1 }]
34603 *
34604 * _.castArray('abc');
34605 * // => ['abc']
34606 *
34607 * _.castArray(null);
34608 * // => [null]
34609 *
34610 * _.castArray(undefined);
34611 * // => [undefined]
34612 *
34613 * _.castArray();
34614 * // => []
34615 *
34616 * var array = [1, 2, 3];
34617 * console.log(_.castArray(array) === array);
34618 * // => true
34619 */
34620 function castArray() {
34621 if (!arguments.length) {
34622 return [];
34623 }
34624 var value = arguments[0];
34625 return isArray(value) ? value : [value];
34626 }
34627
34628 /**
34629 * Creates a shallow clone of `value`.
34630 *
34631 * **Note:** This method is loosely based on the
34632 * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
34633 * and supports cloning arrays, array buffers, booleans, date objects, maps,
34634 * numbers, `Object` objects, regexes, sets, strings, symbols, and typed
34635 * arrays. The own enumerable properties of `arguments` objects are cloned
34636 * as plain objects. An empty object is returned for uncloneable values such
34637 * as error objects, functions, DOM nodes, and WeakMaps.
34638 *
34639 * @static
34640 * @memberOf _
34641 * @since 0.1.0
34642 * @category Lang
34643 * @param {*} value The value to clone.
34644 * @returns {*} Returns the cloned value.
34645 * @see _.cloneDeep
34646 * @example
34647 *
34648 * var objects = [{ 'a': 1 }, { 'b': 2 }];
34649 *
34650 * var shallow = _.clone(objects);
34651 * console.log(shallow[0] === objects[0]);
34652 * // => true
34653 */
34654 function clone(value) {
34655 return baseClone(value, false, true);
34656 }
34657
34658 /**
34659 * This method is like `_.clone` except that it accepts `customizer` which
34660 * is invoked to produce the cloned value. If `customizer` returns `undefined`,
34661 * cloning is handled by the method instead. The `customizer` is invoked with
34662 * up to four arguments; (value [, index|key, object, stack]).
34663 *
34664 * @static
34665 * @memberOf _
34666 * @since 4.0.0
34667 * @category Lang
34668 * @param {*} value The value to clone.
34669 * @param {Function} [customizer] The function to customize cloning.
34670 * @returns {*} Returns the cloned value.
34671 * @see _.cloneDeepWith
34672 * @example
34673 *
34674 * function customizer(value) {
34675 * if (_.isElement(value)) {
34676 * return value.cloneNode(false);
34677 * }
34678 * }
34679 *
34680 * var el = _.cloneWith(document.body, customizer);
34681 *
34682 * console.log(el === document.body);
34683 * // => false
34684 * console.log(el.nodeName);
34685 * // => 'BODY'
34686 * console.log(el.childNodes.length);
34687 * // => 0
34688 */
34689 function cloneWith(value, customizer) {
34690 return baseClone(value, false, true, customizer);
34691 }
34692
34693 /**
34694 * This method is like `_.clone` except that it recursively clones `value`.
34695 *
34696 * @static
34697 * @memberOf _
34698 * @since 1.0.0
34699 * @category Lang
34700 * @param {*} value The value to recursively clone.
34701 * @returns {*} Returns the deep cloned value.
34702 * @see _.clone
34703 * @example
34704 *
34705 * var objects = [{ 'a': 1 }, { 'b': 2 }];
34706 *
34707 * var deep = _.cloneDeep(objects);
34708 * console.log(deep[0] === objects[0]);
34709 * // => false
34710 */
34711 function cloneDeep(value) {
34712 return baseClone(value, true, true);
34713 }
34714
34715 /**
34716 * This method is like `_.cloneWith` except that it recursively clones `value`.
34717 *
34718 * @static
34719 * @memberOf _
34720 * @since 4.0.0
34721 * @category Lang
34722 * @param {*} value The value to recursively clone.
34723 * @param {Function} [customizer] The function to customize cloning.
34724 * @returns {*} Returns the deep cloned value.
34725 * @see _.cloneWith
34726 * @example
34727 *
34728 * function customizer(value) {
34729 * if (_.isElement(value)) {
34730 * return value.cloneNode(true);
34731 * }
34732 * }
34733 *
34734 * var el = _.cloneDeepWith(document.body, customizer);
34735 *
34736 * console.log(el === document.body);
34737 * // => false
34738 * console.log(el.nodeName);
34739 * // => 'BODY'
34740 * console.log(el.childNodes.length);
34741 * // => 20
34742 */
34743 function cloneDeepWith(value, customizer) {
34744 return baseClone(value, true, true, customizer);
34745 }
34746
34747 /**
34748 * Checks if `object` conforms to `source` by invoking the predicate
34749 * properties of `source` with the corresponding property values of `object`.
34750 *
34751 * **Note:** This method is equivalent to `_.conforms` when `source` is
34752 * partially applied.
34753 *
34754 * @static
34755 * @memberOf _
34756 * @since 4.14.0
34757 * @category Lang
34758 * @param {Object} object The object to inspect.
34759 * @param {Object} source The object of property predicates to conform to.
34760 * @returns {boolean} Returns `true` if `object` conforms, else `false`.
34761 * @example
34762 *
34763 * var object = { 'a': 1, 'b': 2 };
34764 *
34765 * _.conformsTo(object, { 'b': function(n) { return n > 1; } });
34766 * // => true
34767 *
34768 * _.conformsTo(object, { 'b': function(n) { return n > 2; } });
34769 * // => false
34770 */
34771 function conformsTo(object, source) {
34772 return source == null || baseConformsTo(object, source, keys(source));
34773 }
34774
34775 /**
34776 * Performs a
34777 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
34778 * comparison between two values to determine if they are equivalent.
34779 *
34780 * @static
34781 * @memberOf _
34782 * @since 4.0.0
34783 * @category Lang
34784 * @param {*} value The value to compare.
34785 * @param {*} other The other value to compare.
34786 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
34787 * @example
34788 *
34789 * var object = { 'a': 1 };
34790 * var other = { 'a': 1 };
34791 *
34792 * _.eq(object, object);
34793 * // => true
34794 *
34795 * _.eq(object, other);
34796 * // => false
34797 *
34798 * _.eq('a', 'a');
34799 * // => true
34800 *
34801 * _.eq('a', Object('a'));
34802 * // => false
34803 *
34804 * _.eq(NaN, NaN);
34805 * // => true
34806 */
34807 function eq(value, other) {
34808 return value === other || (value !== value && other !== other);
34809 }
34810
34811 /**
34812 * Checks if `value` is greater than `other`.
34813 *
34814 * @static
34815 * @memberOf _
34816 * @since 3.9.0
34817 * @category Lang
34818 * @param {*} value The value to compare.
34819 * @param {*} other The other value to compare.
34820 * @returns {boolean} Returns `true` if `value` is greater than `other`,
34821 * else `false`.
34822 * @see _.lt
34823 * @example
34824 *
34825 * _.gt(3, 1);
34826 * // => true
34827 *
34828 * _.gt(3, 3);
34829 * // => false
34830 *
34831 * _.gt(1, 3);
34832 * // => false
34833 */
34834 var gt = createRelationalOperation(baseGt);
34835
34836 /**
34837 * Checks if `value` is greater than or equal to `other`.
34838 *
34839 * @static
34840 * @memberOf _
34841 * @since 3.9.0
34842 * @category Lang
34843 * @param {*} value The value to compare.
34844 * @param {*} other The other value to compare.
34845 * @returns {boolean} Returns `true` if `value` is greater than or equal to
34846 * `other`, else `false`.
34847 * @see _.lte
34848 * @example
34849 *
34850 * _.gte(3, 1);
34851 * // => true
34852 *
34853 * _.gte(3, 3);
34854 * // => true
34855 *
34856 * _.gte(1, 3);
34857 * // => false
34858 */
34859 var gte = createRelationalOperation(function(value, other) {
34860 return value >= other;
34861 });
34862
34863 /**
34864 * Checks if `value` is likely an `arguments` object.
34865 *
34866 * @static
34867 * @memberOf _
34868 * @since 0.1.0
34869 * @category Lang
34870 * @param {*} value The value to check.
34871 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
34872 * else `false`.
34873 * @example
34874 *
34875 * _.isArguments(function() { return arguments; }());
34876 * // => true
34877 *
34878 * _.isArguments([1, 2, 3]);
34879 * // => false
34880 */
34881 var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
34882 return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
34883 !propertyIsEnumerable.call(value, 'callee');
34884 };
34885
34886 /**
34887 * Checks if `value` is classified as an `Array` object.
34888 *
34889 * @static
34890 * @memberOf _
34891 * @since 0.1.0
34892 * @category Lang
34893 * @param {*} value The value to check.
34894 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
34895 * @example
34896 *
34897 * _.isArray([1, 2, 3]);
34898 * // => true
34899 *
34900 * _.isArray(document.body.children);
34901 * // => false
34902 *
34903 * _.isArray('abc');
34904 * // => false
34905 *
34906 * _.isArray(_.noop);
34907 * // => false
34908 */
34909 var isArray = Array.isArray;
34910
34911 /**
34912 * Checks if `value` is classified as an `ArrayBuffer` object.
34913 *
34914 * @static
34915 * @memberOf _
34916 * @since 4.3.0
34917 * @category Lang
34918 * @param {*} value The value to check.
34919 * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.
34920 * @example
34921 *
34922 * _.isArrayBuffer(new ArrayBuffer(2));
34923 * // => true
34924 *
34925 * _.isArrayBuffer(new Array(2));
34926 * // => false
34927 */
34928 var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer;
34929
34930 /**
34931 * Checks if `value` is array-like. A value is considered array-like if it's
34932 * not a function and has a `value.length` that's an integer greater than or
34933 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
34934 *
34935 * @static
34936 * @memberOf _
34937 * @since 4.0.0
34938 * @category Lang
34939 * @param {*} value The value to check.
34940 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
34941 * @example
34942 *
34943 * _.isArrayLike([1, 2, 3]);
34944 * // => true
34945 *
34946 * _.isArrayLike(document.body.children);
34947 * // => true
34948 *
34949 * _.isArrayLike('abc');
34950 * // => true
34951 *
34952 * _.isArrayLike(_.noop);
34953 * // => false
34954 */
34955 function isArrayLike(value) {
34956 return value != null && isLength(value.length) && !isFunction(value);
34957 }
34958
34959 /**
34960 * This method is like `_.isArrayLike` except that it also checks if `value`
34961 * is an object.
34962 *
34963 * @static
34964 * @memberOf _
34965 * @since 4.0.0
34966 * @category Lang
34967 * @param {*} value The value to check.
34968 * @returns {boolean} Returns `true` if `value` is an array-like object,
34969 * else `false`.
34970 * @example
34971 *
34972 * _.isArrayLikeObject([1, 2, 3]);
34973 * // => true
34974 *
34975 * _.isArrayLikeObject(document.body.children);
34976 * // => true
34977 *
34978 * _.isArrayLikeObject('abc');
34979 * // => false
34980 *
34981 * _.isArrayLikeObject(_.noop);
34982 * // => false
34983 */
34984 function isArrayLikeObject(value) {
34985 return isObjectLike(value) && isArrayLike(value);
34986 }
34987
34988 /**
34989 * Checks if `value` is classified as a boolean primitive or object.
34990 *
34991 * @static
34992 * @memberOf _
34993 * @since 0.1.0
34994 * @category Lang
34995 * @param {*} value The value to check.
34996 * @returns {boolean} Returns `true` if `value` is a boolean, else `false`.
34997 * @example
34998 *
34999 * _.isBoolean(false);
35000 * // => true
35001 *
35002 * _.isBoolean(null);
35003 * // => false
35004 */
35005 function isBoolean(value) {
35006 return value === true || value === false ||
35007 (isObjectLike(value) && objectToString.call(value) == boolTag);
35008 }
35009
35010 /**
35011 * Checks if `value` is a buffer.
35012 *
35013 * @static
35014 * @memberOf _
35015 * @since 4.3.0
35016 * @category Lang
35017 * @param {*} value The value to check.
35018 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
35019 * @example
35020 *
35021 * _.isBuffer(new Buffer(2));
35022 * // => true
35023 *
35024 * _.isBuffer(new Uint8Array(2));
35025 * // => false
35026 */
35027 var isBuffer = nativeIsBuffer || stubFalse;
35028
35029 /**
35030 * Checks if `value` is classified as a `Date` object.
35031 *
35032 * @static
35033 * @memberOf _
35034 * @since 0.1.0
35035 * @category Lang
35036 * @param {*} value The value to check.
35037 * @returns {boolean} Returns `true` if `value` is a date object, else `false`.
35038 * @example
35039 *
35040 * _.isDate(new Date);
35041 * // => true
35042 *
35043 * _.isDate('Mon April 23 2012');
35044 * // => false
35045 */
35046 var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate;
35047
35048 /**
35049 * Checks if `value` is likely a DOM element.
35050 *
35051 * @static
35052 * @memberOf _
35053 * @since 0.1.0
35054 * @category Lang
35055 * @param {*} value The value to check.
35056 * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
35057 * @example
35058 *
35059 * _.isElement(document.body);
35060 * // => true
35061 *
35062 * _.isElement('<body>');
35063 * // => false
35064 */
35065 function isElement(value) {
35066 return value != null && value.nodeType === 1 && isObjectLike(value) && !isPlainObject(value);
35067 }
35068
35069 /**
35070 * Checks if `value` is an empty object, collection, map, or set.
35071 *
35072 * Objects are considered empty if they have no own enumerable string keyed
35073 * properties.
35074 *
35075 * Array-like values such as `arguments` objects, arrays, buffers, strings, or
35076 * jQuery-like collections are considered empty if they have a `length` of `0`.
35077 * Similarly, maps and sets are considered empty if they have a `size` of `0`.
35078 *
35079 * @static
35080 * @memberOf _
35081 * @since 0.1.0
35082 * @category Lang
35083 * @param {*} value The value to check.
35084 * @returns {boolean} Returns `true` if `value` is empty, else `false`.
35085 * @example
35086 *
35087 * _.isEmpty(null);
35088 * // => true
35089 *
35090 * _.isEmpty(true);
35091 * // => true
35092 *
35093 * _.isEmpty(1);
35094 * // => true
35095 *
35096 * _.isEmpty([1, 2, 3]);
35097 * // => false
35098 *
35099 * _.isEmpty({ 'a': 1 });
35100 * // => false
35101 */
35102 function isEmpty(value) {
35103 if (isArrayLike(value) &&
35104 (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||
35105 isBuffer(value) || isTypedArray(value) || isArguments(value))) {
35106 return !value.length;
35107 }
35108 var tag = getTag(value);
35109 if (tag == mapTag || tag == setTag) {
35110 return !value.size;
35111 }
35112 if (isPrototype(value)) {
35113 return !baseKeys(value).length;
35114 }
35115 for (var key in value) {
35116 if (hasOwnProperty.call(value, key)) {
35117 return false;
35118 }
35119 }
35120 return true;
35121 }
35122
35123 /**
35124 * Performs a deep comparison between two values to determine if they are
35125 * equivalent.
35126 *
35127 * **Note:** This method supports comparing arrays, array buffers, booleans,
35128 * date objects, error objects, maps, numbers, `Object` objects, regexes,
35129 * sets, strings, symbols, and typed arrays. `Object` objects are compared
35130 * by their own, not inherited, enumerable properties. Functions and DOM
35131 * nodes are **not** supported.
35132 *
35133 * @static
35134 * @memberOf _
35135 * @since 0.1.0
35136 * @category Lang
35137 * @param {*} value The value to compare.
35138 * @param {*} other The other value to compare.
35139 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
35140 * @example
35141 *
35142 * var object = { 'a': 1 };
35143 * var other = { 'a': 1 };
35144 *
35145 * _.isEqual(object, other);
35146 * // => true
35147 *
35148 * object === other;
35149 * // => false
35150 */
35151 function isEqual(value, other) {
35152 return baseIsEqual(value, other);
35153 }
35154
35155 /**
35156 * This method is like `_.isEqual` except that it accepts `customizer` which
35157 * is invoked to compare values. If `customizer` returns `undefined`, comparisons
35158 * are handled by the method instead. The `customizer` is invoked with up to
35159 * six arguments: (objValue, othValue [, index|key, object, other, stack]).
35160 *
35161 * @static
35162 * @memberOf _
35163 * @since 4.0.0
35164 * @category Lang
35165 * @param {*} value The value to compare.
35166 * @param {*} other The other value to compare.
35167 * @param {Function} [customizer] The function to customize comparisons.
35168 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
35169 * @example
35170 *
35171 * function isGreeting(value) {
35172 * return /^h(?:i|ello)$/.test(value);
35173 * }
35174 *
35175 * function customizer(objValue, othValue) {
35176 * if (isGreeting(objValue) && isGreeting(othValue)) {
35177 * return true;
35178 * }
35179 * }
35180 *
35181 * var array = ['hello', 'goodbye'];
35182 * var other = ['hi', 'goodbye'];
35183 *
35184 * _.isEqualWith(array, other, customizer);
35185 * // => true
35186 */
35187 function isEqualWith(value, other, customizer) {
35188 customizer = typeof customizer == 'function' ? customizer : undefined;
35189 var result = customizer ? customizer(value, other) : undefined;
35190 return result === undefined ? baseIsEqual(value, other, customizer) : !!result;
35191 }
35192
35193 /**
35194 * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
35195 * `SyntaxError`, `TypeError`, or `URIError` object.
35196 *
35197 * @static
35198 * @memberOf _
35199 * @since 3.0.0
35200 * @category Lang
35201 * @param {*} value The value to check.
35202 * @returns {boolean} Returns `true` if `value` is an error object, else `false`.
35203 * @example
35204 *
35205 * _.isError(new Error);
35206 * // => true
35207 *
35208 * _.isError(Error);
35209 * // => false
35210 */
35211 function isError(value) {
35212 if (!isObjectLike(value)) {
35213 return false;
35214 }
35215 return (objectToString.call(value) == errorTag) ||
35216 (typeof value.message == 'string' && typeof value.name == 'string');
35217 }
35218
35219 /**
35220 * Checks if `value` is a finite primitive number.
35221 *
35222 * **Note:** This method is based on
35223 * [`Number.isFinite`](https://mdn.io/Number/isFinite).
35224 *
35225 * @static
35226 * @memberOf _
35227 * @since 0.1.0
35228 * @category Lang
35229 * @param {*} value The value to check.
35230 * @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
35231 * @example
35232 *
35233 * _.isFinite(3);
35234 * // => true
35235 *
35236 * _.isFinite(Number.MIN_VALUE);
35237 * // => true
35238 *
35239 * _.isFinite(Infinity);
35240 * // => false
35241 *
35242 * _.isFinite('3');
35243 * // => false
35244 */
35245 function isFinite(value) {
35246 return typeof value == 'number' && nativeIsFinite(value);
35247 }
35248
35249 /**
35250 * Checks if `value` is classified as a `Function` object.
35251 *
35252 * @static
35253 * @memberOf _
35254 * @since 0.1.0
35255 * @category Lang
35256 * @param {*} value The value to check.
35257 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
35258 * @example
35259 *
35260 * _.isFunction(_);
35261 * // => true
35262 *
35263 * _.isFunction(/abc/);
35264 * // => false
35265 */
35266 function isFunction(value) {
35267 // The use of `Object#toString` avoids issues with the `typeof` operator
35268 // in Safari 9 which returns 'object' for typed array and other constructors.
35269 var tag = isObject(value) ? objectToString.call(value) : '';
35270 return tag == funcTag || tag == genTag || tag == proxyTag;
35271 }
35272
35273 /**
35274 * Checks if `value` is an integer.
35275 *
35276 * **Note:** This method is based on
35277 * [`Number.isInteger`](https://mdn.io/Number/isInteger).
35278 *
35279 * @static
35280 * @memberOf _
35281 * @since 4.0.0
35282 * @category Lang
35283 * @param {*} value The value to check.
35284 * @returns {boolean} Returns `true` if `value` is an integer, else `false`.
35285 * @example
35286 *
35287 * _.isInteger(3);
35288 * // => true
35289 *
35290 * _.isInteger(Number.MIN_VALUE);
35291 * // => false
35292 *
35293 * _.isInteger(Infinity);
35294 * // => false
35295 *
35296 * _.isInteger('3');
35297 * // => false
35298 */
35299 function isInteger(value) {
35300 return typeof value == 'number' && value == toInteger(value);
35301 }
35302
35303 /**
35304 * Checks if `value` is a valid array-like length.
35305 *
35306 * **Note:** This method is loosely based on
35307 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
35308 *
35309 * @static
35310 * @memberOf _
35311 * @since 4.0.0
35312 * @category Lang
35313 * @param {*} value The value to check.
35314 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
35315 * @example
35316 *
35317 * _.isLength(3);
35318 * // => true
35319 *
35320 * _.isLength(Number.MIN_VALUE);
35321 * // => false
35322 *
35323 * _.isLength(Infinity);
35324 * // => false
35325 *
35326 * _.isLength('3');
35327 * // => false
35328 */
35329 function isLength(value) {
35330 return typeof value == 'number' &&
35331 value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
35332 }
35333
35334 /**
35335 * Checks if `value` is the
35336 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
35337 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
35338 *
35339 * @static
35340 * @memberOf _
35341 * @since 0.1.0
35342 * @category Lang
35343 * @param {*} value The value to check.
35344 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
35345 * @example
35346 *
35347 * _.isObject({});
35348 * // => true
35349 *
35350 * _.isObject([1, 2, 3]);
35351 * // => true
35352 *
35353 * _.isObject(_.noop);
35354 * // => true
35355 *
35356 * _.isObject(null);
35357 * // => false
35358 */
35359 function isObject(value) {
35360 var type = typeof value;
35361 return value != null && (type == 'object' || type == 'function');
35362 }
35363
35364 /**
35365 * Checks if `value` is object-like. A value is object-like if it's not `null`
35366 * and has a `typeof` result of "object".
35367 *
35368 * @static
35369 * @memberOf _
35370 * @since 4.0.0
35371 * @category Lang
35372 * @param {*} value The value to check.
35373 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
35374 * @example
35375 *
35376 * _.isObjectLike({});
35377 * // => true
35378 *
35379 * _.isObjectLike([1, 2, 3]);
35380 * // => true
35381 *
35382 * _.isObjectLike(_.noop);
35383 * // => false
35384 *
35385 * _.isObjectLike(null);
35386 * // => false
35387 */
35388 function isObjectLike(value) {
35389 return value != null && typeof value == 'object';
35390 }
35391
35392 /**
35393 * Checks if `value` is classified as a `Map` object.
35394 *
35395 * @static
35396 * @memberOf _
35397 * @since 4.3.0
35398 * @category Lang
35399 * @param {*} value The value to check.
35400 * @returns {boolean} Returns `true` if `value` is a map, else `false`.
35401 * @example
35402 *
35403 * _.isMap(new Map);
35404 * // => true
35405 *
35406 * _.isMap(new WeakMap);
35407 * // => false
35408 */
35409 var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;
35410
35411 /**
35412 * Performs a partial deep comparison between `object` and `source` to
35413 * determine if `object` contains equivalent property values.
35414 *
35415 * **Note:** This method is equivalent to `_.matches` when `source` is
35416 * partially applied.
35417 *
35418 * Partial comparisons will match empty array and empty object `source`
35419 * values against any array or object value, respectively. See `_.isEqual`
35420 * for a list of supported value comparisons.
35421 *
35422 * @static
35423 * @memberOf _
35424 * @since 3.0.0
35425 * @category Lang
35426 * @param {Object} object The object to inspect.
35427 * @param {Object} source The object of property values to match.
35428 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
35429 * @example
35430 *
35431 * var object = { 'a': 1, 'b': 2 };
35432 *
35433 * _.isMatch(object, { 'b': 2 });
35434 * // => true
35435 *
35436 * _.isMatch(object, { 'b': 1 });
35437 * // => false
35438 */
35439 function isMatch(object, source) {
35440 return object === source || baseIsMatch(object, source, getMatchData(source));
35441 }
35442
35443 /**
35444 * This method is like `_.isMatch` except that it accepts `customizer` which
35445 * is invoked to compare values. If `customizer` returns `undefined`, comparisons
35446 * are handled by the method instead. The `customizer` is invoked with five
35447 * arguments: (objValue, srcValue, index|key, object, source).
35448 *
35449 * @static
35450 * @memberOf _
35451 * @since 4.0.0
35452 * @category Lang
35453 * @param {Object} object The object to inspect.
35454 * @param {Object} source The object of property values to match.
35455 * @param {Function} [customizer] The function to customize comparisons.
35456 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
35457 * @example
35458 *
35459 * function isGreeting(value) {
35460 * return /^h(?:i|ello)$/.test(value);
35461 * }
35462 *
35463 * function customizer(objValue, srcValue) {
35464 * if (isGreeting(objValue) && isGreeting(srcValue)) {
35465 * return true;
35466 * }
35467 * }
35468 *
35469 * var object = { 'greeting': 'hello' };
35470 * var source = { 'greeting': 'hi' };
35471 *
35472 * _.isMatchWith(object, source, customizer);
35473 * // => true
35474 */
35475 function isMatchWith(object, source, customizer) {
35476 customizer = typeof customizer == 'function' ? customizer : undefined;
35477 return baseIsMatch(object, source, getMatchData(source), customizer);
35478 }
35479
35480 /**
35481 * Checks if `value` is `NaN`.
35482 *
35483 * **Note:** This method is based on
35484 * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as
35485 * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for
35486 * `undefined` and other non-number values.
35487 *
35488 * @static
35489 * @memberOf _
35490 * @since 0.1.0
35491 * @category Lang
35492 * @param {*} value The value to check.
35493 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
35494 * @example
35495 *
35496 * _.isNaN(NaN);
35497 * // => true
35498 *
35499 * _.isNaN(new Number(NaN));
35500 * // => true
35501 *
35502 * isNaN(undefined);
35503 * // => true
35504 *
35505 * _.isNaN(undefined);
35506 * // => false
35507 */
35508 function isNaN(value) {
35509 // An `NaN` primitive is the only value that is not equal to itself.
35510 // Perform the `toStringTag` check first to avoid errors with some
35511 // ActiveX objects in IE.
35512 return isNumber(value) && value != +value;
35513 }
35514
35515 /**
35516 * Checks if `value` is a pristine native function.
35517 *
35518 * **Note:** This method can't reliably detect native functions in the presence
35519 * of the core-js package because core-js circumvents this kind of detection.
35520 * Despite multiple requests, the core-js maintainer has made it clear: any
35521 * attempt to fix the detection will be obstructed. As a result, we're left
35522 * with little choice but to throw an error. Unfortunately, this also affects
35523 * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill),
35524 * which rely on core-js.
35525 *
35526 * @static
35527 * @memberOf _
35528 * @since 3.0.0
35529 * @category Lang
35530 * @param {*} value The value to check.
35531 * @returns {boolean} Returns `true` if `value` is a native function,
35532 * else `false`.
35533 * @example
35534 *
35535 * _.isNative(Array.prototype.push);
35536 * // => true
35537 *
35538 * _.isNative(_);
35539 * // => false
35540 */
35541 function isNative(value) {
35542 if (isMaskable(value)) {
35543 throw new Error(CORE_ERROR_TEXT);
35544 }
35545 return baseIsNative(value);
35546 }
35547
35548 /**
35549 * Checks if `value` is `null`.
35550 *
35551 * @static
35552 * @memberOf _
35553 * @since 0.1.0
35554 * @category Lang
35555 * @param {*} value The value to check.
35556 * @returns {boolean} Returns `true` if `value` is `null`, else `false`.
35557 * @example
35558 *
35559 * _.isNull(null);
35560 * // => true
35561 *
35562 * _.isNull(void 0);
35563 * // => false
35564 */
35565 function isNull(value) {
35566 return value === null;
35567 }
35568
35569 /**
35570 * Checks if `value` is `null` or `undefined`.
35571 *
35572 * @static
35573 * @memberOf _
35574 * @since 4.0.0
35575 * @category Lang
35576 * @param {*} value The value to check.
35577 * @returns {boolean} Returns `true` if `value` is nullish, else `false`.
35578 * @example
35579 *
35580 * _.isNil(null);
35581 * // => true
35582 *
35583 * _.isNil(void 0);
35584 * // => true
35585 *
35586 * _.isNil(NaN);
35587 * // => false
35588 */
35589 function isNil(value) {
35590 return value == null;
35591 }
35592
35593 /**
35594 * Checks if `value` is classified as a `Number` primitive or object.
35595 *
35596 * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
35597 * classified as numbers, use the `_.isFinite` method.
35598 *
35599 * @static
35600 * @memberOf _
35601 * @since 0.1.0
35602 * @category Lang
35603 * @param {*} value The value to check.
35604 * @returns {boolean} Returns `true` if `value` is a number, else `false`.
35605 * @example
35606 *
35607 * _.isNumber(3);
35608 * // => true
35609 *
35610 * _.isNumber(Number.MIN_VALUE);
35611 * // => true
35612 *
35613 * _.isNumber(Infinity);
35614 * // => true
35615 *
35616 * _.isNumber('3');
35617 * // => false
35618 */
35619 function isNumber(value) {
35620 return typeof value == 'number' ||
35621 (isObjectLike(value) && objectToString.call(value) == numberTag);
35622 }
35623
35624 /**
35625 * Checks if `value` is a plain object, that is, an object created by the
35626 * `Object` constructor or one with a `[[Prototype]]` of `null`.
35627 *
35628 * @static
35629 * @memberOf _
35630 * @since 0.8.0
35631 * @category Lang
35632 * @param {*} value The value to check.
35633 * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
35634 * @example
35635 *
35636 * function Foo() {
35637 * this.a = 1;
35638 * }
35639 *
35640 * _.isPlainObject(new Foo);
35641 * // => false
35642 *
35643 * _.isPlainObject([1, 2, 3]);
35644 * // => false
35645 *
35646 * _.isPlainObject({ 'x': 0, 'y': 0 });
35647 * // => true
35648 *
35649 * _.isPlainObject(Object.create(null));
35650 * // => true
35651 */
35652 function isPlainObject(value) {
35653 if (!isObjectLike(value) || objectToString.call(value) != objectTag) {
35654 return false;
35655 }
35656 var proto = getPrototype(value);
35657 if (proto === null) {
35658 return true;
35659 }
35660 var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
35661 return (typeof Ctor == 'function' &&
35662 Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
35663 }
35664
35665 /**
35666 * Checks if `value` is classified as a `RegExp` object.
35667 *
35668 * @static
35669 * @memberOf _
35670 * @since 0.1.0
35671 * @category Lang
35672 * @param {*} value The value to check.
35673 * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
35674 * @example
35675 *
35676 * _.isRegExp(/abc/);
35677 * // => true
35678 *
35679 * _.isRegExp('/abc/');
35680 * // => false
35681 */
35682 var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp;
35683
35684 /**
35685 * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754
35686 * double precision number which isn't the result of a rounded unsafe integer.
35687 *
35688 * **Note:** This method is based on
35689 * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger).
35690 *
35691 * @static
35692 * @memberOf _
35693 * @since 4.0.0
35694 * @category Lang
35695 * @param {*} value The value to check.
35696 * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`.
35697 * @example
35698 *
35699 * _.isSafeInteger(3);
35700 * // => true
35701 *
35702 * _.isSafeInteger(Number.MIN_VALUE);
35703 * // => false
35704 *
35705 * _.isSafeInteger(Infinity);
35706 * // => false
35707 *
35708 * _.isSafeInteger('3');
35709 * // => false
35710 */
35711 function isSafeInteger(value) {
35712 return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER;
35713 }
35714
35715 /**
35716 * Checks if `value` is classified as a `Set` object.
35717 *
35718 * @static
35719 * @memberOf _
35720 * @since 4.3.0
35721 * @category Lang
35722 * @param {*} value The value to check.
35723 * @returns {boolean} Returns `true` if `value` is a set, else `false`.
35724 * @example
35725 *
35726 * _.isSet(new Set);
35727 * // => true
35728 *
35729 * _.isSet(new WeakSet);
35730 * // => false
35731 */
35732 var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;
35733
35734 /**
35735 * Checks if `value` is classified as a `String` primitive or object.
35736 *
35737 * @static
35738 * @since 0.1.0
35739 * @memberOf _
35740 * @category Lang
35741 * @param {*} value The value to check.
35742 * @returns {boolean} Returns `true` if `value` is a string, else `false`.
35743 * @example
35744 *
35745 * _.isString('abc');
35746 * // => true
35747 *
35748 * _.isString(1);
35749 * // => false
35750 */
35751 function isString(value) {
35752 return typeof value == 'string' ||
35753 (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag);
35754 }
35755
35756 /**
35757 * Checks if `value` is classified as a `Symbol` primitive or object.
35758 *
35759 * @static
35760 * @memberOf _
35761 * @since 4.0.0
35762 * @category Lang
35763 * @param {*} value The value to check.
35764 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
35765 * @example
35766 *
35767 * _.isSymbol(Symbol.iterator);
35768 * // => true
35769 *
35770 * _.isSymbol('abc');
35771 * // => false
35772 */
35773 function isSymbol(value) {
35774 return typeof value == 'symbol' ||
35775 (isObjectLike(value) && objectToString.call(value) == symbolTag);
35776 }
35777
35778 /**
35779 * Checks if `value` is classified as a typed array.
35780 *
35781 * @static
35782 * @memberOf _
35783 * @since 3.0.0
35784 * @category Lang
35785 * @param {*} value The value to check.
35786 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
35787 * @example
35788 *
35789 * _.isTypedArray(new Uint8Array);
35790 * // => true
35791 *
35792 * _.isTypedArray([]);
35793 * // => false
35794 */
35795 var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
35796
35797 /**
35798 * Checks if `value` is `undefined`.
35799 *
35800 * @static
35801 * @since 0.1.0
35802 * @memberOf _
35803 * @category Lang
35804 * @param {*} value The value to check.
35805 * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
35806 * @example
35807 *
35808 * _.isUndefined(void 0);
35809 * // => true
35810 *
35811 * _.isUndefined(null);
35812 * // => false
35813 */
35814 function isUndefined(value) {
35815 return value === undefined;
35816 }
35817
35818 /**
35819 * Checks if `value` is classified as a `WeakMap` object.
35820 *
35821 * @static
35822 * @memberOf _
35823 * @since 4.3.0
35824 * @category Lang
35825 * @param {*} value The value to check.
35826 * @returns {boolean} Returns `true` if `value` is a weak map, else `false`.
35827 * @example
35828 *
35829 * _.isWeakMap(new WeakMap);
35830 * // => true
35831 *
35832 * _.isWeakMap(new Map);
35833 * // => false
35834 */
35835 function isWeakMap(value) {
35836 return isObjectLike(value) && getTag(value) == weakMapTag;
35837 }
35838
35839 /**
35840 * Checks if `value` is classified as a `WeakSet` object.
35841 *
35842 * @static
35843 * @memberOf _
35844 * @since 4.3.0
35845 * @category Lang
35846 * @param {*} value The value to check.
35847 * @returns {boolean} Returns `true` if `value` is a weak set, else `false`.
35848 * @example
35849 *
35850 * _.isWeakSet(new WeakSet);
35851 * // => true
35852 *
35853 * _.isWeakSet(new Set);
35854 * // => false
35855 */
35856 function isWeakSet(value) {
35857 return isObjectLike(value) && objectToString.call(value) == weakSetTag;
35858 }
35859
35860 /**
35861 * Checks if `value` is less than `other`.
35862 *
35863 * @static
35864 * @memberOf _
35865 * @since 3.9.0
35866 * @category Lang
35867 * @param {*} value The value to compare.
35868 * @param {*} other The other value to compare.
35869 * @returns {boolean} Returns `true` if `value` is less than `other`,
35870 * else `false`.
35871 * @see _.gt
35872 * @example
35873 *
35874 * _.lt(1, 3);
35875 * // => true
35876 *
35877 * _.lt(3, 3);
35878 * // => false
35879 *
35880 * _.lt(3, 1);
35881 * // => false
35882 */
35883 var lt = createRelationalOperation(baseLt);
35884
35885 /**
35886 * Checks if `value` is less than or equal to `other`.
35887 *
35888 * @static
35889 * @memberOf _
35890 * @since 3.9.0
35891 * @category Lang
35892 * @param {*} value The value to compare.
35893 * @param {*} other The other value to compare.
35894 * @returns {boolean} Returns `true` if `value` is less than or equal to
35895 * `other`, else `false`.
35896 * @see _.gte
35897 * @example
35898 *
35899 * _.lte(1, 3);
35900 * // => true
35901 *
35902 * _.lte(3, 3);
35903 * // => true
35904 *
35905 * _.lte(3, 1);
35906 * // => false
35907 */
35908 var lte = createRelationalOperation(function(value, other) {
35909 return value <= other;
35910 });
35911
35912 /**
35913 * Converts `value` to an array.
35914 *
35915 * @static
35916 * @since 0.1.0
35917 * @memberOf _
35918 * @category Lang
35919 * @param {*} value The value to convert.
35920 * @returns {Array} Returns the converted array.
35921 * @example
35922 *
35923 * _.toArray({ 'a': 1, 'b': 2 });
35924 * // => [1, 2]
35925 *
35926 * _.toArray('abc');
35927 * // => ['a', 'b', 'c']
35928 *
35929 * _.toArray(1);
35930 * // => []
35931 *
35932 * _.toArray(null);
35933 * // => []
35934 */
35935 function toArray(value) {
35936 if (!value) {
35937 return [];
35938 }
35939 if (isArrayLike(value)) {
35940 return isString(value) ? stringToArray(value) : copyArray(value);
35941 }
35942 if (iteratorSymbol && value[iteratorSymbol]) {
35943 return iteratorToArray(value[iteratorSymbol]());
35944 }
35945 var tag = getTag(value),
35946 func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values);
35947
35948 return func(value);
35949 }
35950
35951 /**
35952 * Converts `value` to a finite number.
35953 *
35954 * @static
35955 * @memberOf _
35956 * @since 4.12.0
35957 * @category Lang
35958 * @param {*} value The value to convert.
35959 * @returns {number} Returns the converted number.
35960 * @example
35961 *
35962 * _.toFinite(3.2);
35963 * // => 3.2
35964 *
35965 * _.toFinite(Number.MIN_VALUE);
35966 * // => 5e-324
35967 *
35968 * _.toFinite(Infinity);
35969 * // => 1.7976931348623157e+308
35970 *
35971 * _.toFinite('3.2');
35972 * // => 3.2
35973 */
35974 function toFinite(value) {
35975 if (!value) {
35976 return value === 0 ? value : 0;
35977 }
35978 value = toNumber(value);
35979 if (value === INFINITY || value === -INFINITY) {
35980 var sign = (value < 0 ? -1 : 1);
35981 return sign * MAX_INTEGER;
35982 }
35983 return value === value ? value : 0;
35984 }
35985
35986 /**
35987 * Converts `value` to an integer.
35988 *
35989 * **Note:** This method is loosely based on
35990 * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
35991 *
35992 * @static
35993 * @memberOf _
35994 * @since 4.0.0
35995 * @category Lang
35996 * @param {*} value The value to convert.
35997 * @returns {number} Returns the converted integer.
35998 * @example
35999 *
36000 * _.toInteger(3.2);
36001 * // => 3
36002 *
36003 * _.toInteger(Number.MIN_VALUE);
36004 * // => 0
36005 *
36006 * _.toInteger(Infinity);
36007 * // => 1.7976931348623157e+308
36008 *
36009 * _.toInteger('3.2');
36010 * // => 3
36011 */
36012 function toInteger(value) {
36013 var result = toFinite(value),
36014 remainder = result % 1;
36015
36016 return result === result ? (remainder ? result - remainder : result) : 0;
36017 }
36018
36019 /**
36020 * Converts `value` to an integer suitable for use as the length of an
36021 * array-like object.
36022 *
36023 * **Note:** This method is based on
36024 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
36025 *
36026 * @static
36027 * @memberOf _
36028 * @since 4.0.0
36029 * @category Lang
36030 * @param {*} value The value to convert.
36031 * @returns {number} Returns the converted integer.
36032 * @example
36033 *
36034 * _.toLength(3.2);
36035 * // => 3
36036 *
36037 * _.toLength(Number.MIN_VALUE);
36038 * // => 0
36039 *
36040 * _.toLength(Infinity);
36041 * // => 4294967295
36042 *
36043 * _.toLength('3.2');
36044 * // => 3
36045 */
36046 function toLength(value) {
36047 return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0;
36048 }
36049
36050 /**
36051 * Converts `value` to a number.
36052 *
36053 * @static
36054 * @memberOf _
36055 * @since 4.0.0
36056 * @category Lang
36057 * @param {*} value The value to process.
36058 * @returns {number} Returns the number.
36059 * @example
36060 *
36061 * _.toNumber(3.2);
36062 * // => 3.2
36063 *
36064 * _.toNumber(Number.MIN_VALUE);
36065 * // => 5e-324
36066 *
36067 * _.toNumber(Infinity);
36068 * // => Infinity
36069 *
36070 * _.toNumber('3.2');
36071 * // => 3.2
36072 */
36073 function toNumber(value) {
36074 if (typeof value == 'number') {
36075 return value;
36076 }
36077 if (isSymbol(value)) {
36078 return NAN;
36079 }
36080 if (isObject(value)) {
36081 var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
36082 value = isObject(other) ? (other + '') : other;
36083 }
36084 if (typeof value != 'string') {
36085 return value === 0 ? value : +value;
36086 }
36087 value = value.replace(reTrim, '');
36088 var isBinary = reIsBinary.test(value);
36089 return (isBinary || reIsOctal.test(value))
36090 ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
36091 : (reIsBadHex.test(value) ? NAN : +value);
36092 }
36093
36094 /**
36095 * Converts `value` to a plain object flattening inherited enumerable string
36096 * keyed properties of `value` to own properties of the plain object.
36097 *
36098 * @static
36099 * @memberOf _
36100 * @since 3.0.0
36101 * @category Lang
36102 * @param {*} value The value to convert.
36103 * @returns {Object} Returns the converted plain object.
36104 * @example
36105 *
36106 * function Foo() {
36107 * this.b = 2;
36108 * }
36109 *
36110 * Foo.prototype.c = 3;
36111 *
36112 * _.assign({ 'a': 1 }, new Foo);
36113 * // => { 'a': 1, 'b': 2 }
36114 *
36115 * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
36116 * // => { 'a': 1, 'b': 2, 'c': 3 }
36117 */
36118 function toPlainObject(value) {
36119 return copyObject(value, keysIn(value));
36120 }
36121
36122 /**
36123 * Converts `value` to a safe integer. A safe integer can be compared and
36124 * represented correctly.
36125 *
36126 * @static
36127 * @memberOf _
36128 * @since 4.0.0
36129 * @category Lang
36130 * @param {*} value The value to convert.
36131 * @returns {number} Returns the converted integer.
36132 * @example
36133 *
36134 * _.toSafeInteger(3.2);
36135 * // => 3
36136 *
36137 * _.toSafeInteger(Number.MIN_VALUE);
36138 * // => 0
36139 *
36140 * _.toSafeInteger(Infinity);
36141 * // => 9007199254740991
36142 *
36143 * _.toSafeInteger('3.2');
36144 * // => 3
36145 */
36146 function toSafeInteger(value) {
36147 return baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER);
36148 }
36149
36150 /**
36151 * Converts `value` to a string. An empty string is returned for `null`
36152 * and `undefined` values. The sign of `-0` is preserved.
36153 *
36154 * @static
36155 * @memberOf _
36156 * @since 4.0.0
36157 * @category Lang
36158 * @param {*} value The value to convert.
36159 * @returns {string} Returns the converted string.
36160 * @example
36161 *
36162 * _.toString(null);
36163 * // => ''
36164 *
36165 * _.toString(-0);
36166 * // => '-0'
36167 *
36168 * _.toString([1, 2, 3]);
36169 * // => '1,2,3'
36170 */
36171 function toString(value) {
36172 return value == null ? '' : baseToString(value);
36173 }
36174
36175 /*------------------------------------------------------------------------*/
36176
36177 /**
36178 * Assigns own enumerable string keyed properties of source objects to the
36179 * destination object. Source objects are applied from left to right.
36180 * Subsequent sources overwrite property assignments of previous sources.
36181 *
36182 * **Note:** This method mutates `object` and is loosely based on
36183 * [`Object.assign`](https://mdn.io/Object/assign).
36184 *
36185 * @static
36186 * @memberOf _
36187 * @since 0.10.0
36188 * @category Object
36189 * @param {Object} object The destination object.
36190 * @param {...Object} [sources] The source objects.
36191 * @returns {Object} Returns `object`.
36192 * @see _.assignIn
36193 * @example
36194 *
36195 * function Foo() {
36196 * this.a = 1;
36197 * }
36198 *
36199 * function Bar() {
36200 * this.c = 3;
36201 * }
36202 *
36203 * Foo.prototype.b = 2;
36204 * Bar.prototype.d = 4;
36205 *
36206 * _.assign({ 'a': 0 }, new Foo, new Bar);
36207 * // => { 'a': 1, 'c': 3 }
36208 */
36209 var assign = createAssigner(function(object, source) {
36210 if (isPrototype(source) || isArrayLike(source)) {
36211 copyObject(source, keys(source), object);
36212 return;
36213 }
36214 for (var key in source) {
36215 if (hasOwnProperty.call(source, key)) {
36216 assignValue(object, key, source[key]);
36217 }
36218 }
36219 });
36220
36221 /**
36222 * This method is like `_.assign` except that it iterates over own and
36223 * inherited source properties.
36224 *
36225 * **Note:** This method mutates `object`.
36226 *
36227 * @static
36228 * @memberOf _
36229 * @since 4.0.0
36230 * @alias extend
36231 * @category Object
36232 * @param {Object} object The destination object.
36233 * @param {...Object} [sources] The source objects.
36234 * @returns {Object} Returns `object`.
36235 * @see _.assign
36236 * @example
36237 *
36238 * function Foo() {
36239 * this.a = 1;
36240 * }
36241 *
36242 * function Bar() {
36243 * this.c = 3;
36244 * }
36245 *
36246 * Foo.prototype.b = 2;
36247 * Bar.prototype.d = 4;
36248 *
36249 * _.assignIn({ 'a': 0 }, new Foo, new Bar);
36250 * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
36251 */
36252 var assignIn = createAssigner(function(object, source) {
36253 copyObject(source, keysIn(source), object);
36254 });
36255
36256 /**
36257 * This method is like `_.assignIn` except that it accepts `customizer`
36258 * which is invoked to produce the assigned values. If `customizer` returns
36259 * `undefined`, assignment is handled by the method instead. The `customizer`
36260 * is invoked with five arguments: (objValue, srcValue, key, object, source).
36261 *
36262 * **Note:** This method mutates `object`.
36263 *
36264 * @static
36265 * @memberOf _
36266 * @since 4.0.0
36267 * @alias extendWith
36268 * @category Object
36269 * @param {Object} object The destination object.
36270 * @param {...Object} sources The source objects.
36271 * @param {Function} [customizer] The function to customize assigned values.
36272 * @returns {Object} Returns `object`.
36273 * @see _.assignWith
36274 * @example
36275 *
36276 * function customizer(objValue, srcValue) {
36277 * return _.isUndefined(objValue) ? srcValue : objValue;
36278 * }
36279 *
36280 * var defaults = _.partialRight(_.assignInWith, customizer);
36281 *
36282 * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
36283 * // => { 'a': 1, 'b': 2 }
36284 */
36285 var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {
36286 copyObject(source, keysIn(source), object, customizer);
36287 });
36288
36289 /**
36290 * This method is like `_.assign` except that it accepts `customizer`
36291 * which is invoked to produce the assigned values. If `customizer` returns
36292 * `undefined`, assignment is handled by the method instead. The `customizer`
36293 * is invoked with five arguments: (objValue, srcValue, key, object, source).
36294 *
36295 * **Note:** This method mutates `object`.
36296 *
36297 * @static
36298 * @memberOf _
36299 * @since 4.0.0
36300 * @category Object
36301 * @param {Object} object The destination object.
36302 * @param {...Object} sources The source objects.
36303 * @param {Function} [customizer] The function to customize assigned values.
36304 * @returns {Object} Returns `object`.
36305 * @see _.assignInWith
36306 * @example
36307 *
36308 * function customizer(objValue, srcValue) {
36309 * return _.isUndefined(objValue) ? srcValue : objValue;
36310 * }
36311 *
36312 * var defaults = _.partialRight(_.assignWith, customizer);
36313 *
36314 * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
36315 * // => { 'a': 1, 'b': 2 }
36316 */
36317 var assignWith = createAssigner(function(object, source, srcIndex, customizer) {
36318 copyObject(source, keys(source), object, customizer);
36319 });
36320
36321 /**
36322 * Creates an array of values corresponding to `paths` of `object`.
36323 *
36324 * @static
36325 * @memberOf _
36326 * @since 1.0.0
36327 * @category Object
36328 * @param {Object} object The object to iterate over.
36329 * @param {...(string|string[])} [paths] The property paths of elements to pick.
36330 * @returns {Array} Returns the picked values.
36331 * @example
36332 *
36333 * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
36334 *
36335 * _.at(object, ['a[0].b.c', 'a[1]']);
36336 * // => [3, 4]
36337 */
36338 var at = flatRest(baseAt);
36339
36340 /**
36341 * Creates an object that inherits from the `prototype` object. If a
36342 * `properties` object is given, its own enumerable string keyed properties
36343 * are assigned to the created object.
36344 *
36345 * @static
36346 * @memberOf _
36347 * @since 2.3.0
36348 * @category Object
36349 * @param {Object} prototype The object to inherit from.
36350 * @param {Object} [properties] The properties to assign to the object.
36351 * @returns {Object} Returns the new object.
36352 * @example
36353 *
36354 * function Shape() {
36355 * this.x = 0;
36356 * this.y = 0;
36357 * }
36358 *
36359 * function Circle() {
36360 * Shape.call(this);
36361 * }
36362 *
36363 * Circle.prototype = _.create(Shape.prototype, {
36364 * 'constructor': Circle
36365 * });
36366 *
36367 * var circle = new Circle;
36368 * circle instanceof Circle;
36369 * // => true
36370 *
36371 * circle instanceof Shape;
36372 * // => true
36373 */
36374 function create(prototype, properties) {
36375 var result = baseCreate(prototype);
36376 return properties ? baseAssign(result, properties) : result;
36377 }
36378
36379 /**
36380 * Assigns own and inherited enumerable string keyed properties of source
36381 * objects to the destination object for all destination properties that
36382 * resolve to `undefined`. Source objects are applied from left to right.
36383 * Once a property is set, additional values of the same property are ignored.
36384 *
36385 * **Note:** This method mutates `object`.
36386 *
36387 * @static
36388 * @since 0.1.0
36389 * @memberOf _
36390 * @category Object
36391 * @param {Object} object The destination object.
36392 * @param {...Object} [sources] The source objects.
36393 * @returns {Object} Returns `object`.
36394 * @see _.defaultsDeep
36395 * @example
36396 *
36397 * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
36398 * // => { 'a': 1, 'b': 2 }
36399 */
36400 var defaults = baseRest(function(args) {
36401 args.push(undefined, assignInDefaults);
36402 return apply(assignInWith, undefined, args);
36403 });
36404
36405 /**
36406 * This method is like `_.defaults` except that it recursively assigns
36407 * default properties.
36408 *
36409 * **Note:** This method mutates `object`.
36410 *
36411 * @static
36412 * @memberOf _
36413 * @since 3.10.0
36414 * @category Object
36415 * @param {Object} object The destination object.
36416 * @param {...Object} [sources] The source objects.
36417 * @returns {Object} Returns `object`.
36418 * @see _.defaults
36419 * @example
36420 *
36421 * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });
36422 * // => { 'a': { 'b': 2, 'c': 3 } }
36423 */
36424 var defaultsDeep = baseRest(function(args) {
36425 args.push(undefined, mergeDefaults);
36426 return apply(mergeWith, undefined, args);
36427 });
36428
36429 /**
36430 * This method is like `_.find` except that it returns the key of the first
36431 * element `predicate` returns truthy for instead of the element itself.
36432 *
36433 * @static
36434 * @memberOf _
36435 * @since 1.1.0
36436 * @category Object
36437 * @param {Object} object The object to inspect.
36438 * @param {Function} [predicate=_.identity] The function invoked per iteration.
36439 * @returns {string|undefined} Returns the key of the matched element,
36440 * else `undefined`.
36441 * @example
36442 *
36443 * var users = {
36444 * 'barney': { 'age': 36, 'active': true },
36445 * 'fred': { 'age': 40, 'active': false },
36446 * 'pebbles': { 'age': 1, 'active': true }
36447 * };
36448 *
36449 * _.findKey(users, function(o) { return o.age < 40; });
36450 * // => 'barney' (iteration order is not guaranteed)
36451 *
36452 * // The `_.matches` iteratee shorthand.
36453 * _.findKey(users, { 'age': 1, 'active': true });
36454 * // => 'pebbles'
36455 *
36456 * // The `_.matchesProperty` iteratee shorthand.
36457 * _.findKey(users, ['active', false]);
36458 * // => 'fred'
36459 *
36460 * // The `_.property` iteratee shorthand.
36461 * _.findKey(users, 'active');
36462 * // => 'barney'
36463 */
36464 function findKey(object, predicate) {
36465 return baseFindKey(object, getIteratee(predicate, 3), baseForOwn);
36466 }
36467
36468 /**
36469 * This method is like `_.findKey` except that it iterates over elements of
36470 * a collection in the opposite order.
36471 *
36472 * @static
36473 * @memberOf _
36474 * @since 2.0.0
36475 * @category Object
36476 * @param {Object} object The object to inspect.
36477 * @param {Function} [predicate=_.identity] The function invoked per iteration.
36478 * @returns {string|undefined} Returns the key of the matched element,
36479 * else `undefined`.
36480 * @example
36481 *
36482 * var users = {
36483 * 'barney': { 'age': 36, 'active': true },
36484 * 'fred': { 'age': 40, 'active': false },
36485 * 'pebbles': { 'age': 1, 'active': true }
36486 * };
36487 *
36488 * _.findLastKey(users, function(o) { return o.age < 40; });
36489 * // => returns 'pebbles' assuming `_.findKey` returns 'barney'
36490 *
36491 * // The `_.matches` iteratee shorthand.
36492 * _.findLastKey(users, { 'age': 36, 'active': true });
36493 * // => 'barney'
36494 *
36495 * // The `_.matchesProperty` iteratee shorthand.
36496 * _.findLastKey(users, ['active', false]);
36497 * // => 'fred'
36498 *
36499 * // The `_.property` iteratee shorthand.
36500 * _.findLastKey(users, 'active');
36501 * // => 'pebbles'
36502 */
36503 function findLastKey(object, predicate) {
36504 return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight);
36505 }
36506
36507 /**
36508 * Iterates over own and inherited enumerable string keyed properties of an
36509 * object and invokes `iteratee` for each property. The iteratee is invoked
36510 * with three arguments: (value, key, object). Iteratee functions may exit
36511 * iteration early by explicitly returning `false`.
36512 *
36513 * @static
36514 * @memberOf _
36515 * @since 0.3.0
36516 * @category Object
36517 * @param {Object} object The object to iterate over.
36518 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
36519 * @returns {Object} Returns `object`.
36520 * @see _.forInRight
36521 * @example
36522 *
36523 * function Foo() {
36524 * this.a = 1;
36525 * this.b = 2;
36526 * }
36527 *
36528 * Foo.prototype.c = 3;
36529 *
36530 * _.forIn(new Foo, function(value, key) {
36531 * console.log(key);
36532 * });
36533 * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).
36534 */
36535 function forIn(object, iteratee) {
36536 return object == null
36537 ? object
36538 : baseFor(object, getIteratee(iteratee, 3), keysIn);
36539 }
36540
36541 /**
36542 * This method is like `_.forIn` except that it iterates over properties of
36543 * `object` in the opposite order.
36544 *
36545 * @static
36546 * @memberOf _
36547 * @since 2.0.0
36548 * @category Object
36549 * @param {Object} object The object to iterate over.
36550 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
36551 * @returns {Object} Returns `object`.
36552 * @see _.forIn
36553 * @example
36554 *
36555 * function Foo() {
36556 * this.a = 1;
36557 * this.b = 2;
36558 * }
36559 *
36560 * Foo.prototype.c = 3;
36561 *
36562 * _.forInRight(new Foo, function(value, key) {
36563 * console.log(key);
36564 * });
36565 * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.
36566 */
36567 function forInRight(object, iteratee) {
36568 return object == null
36569 ? object
36570 : baseForRight(object, getIteratee(iteratee, 3), keysIn);
36571 }
36572
36573 /**
36574 * Iterates over own enumerable string keyed properties of an object and
36575 * invokes `iteratee` for each property. The iteratee is invoked with three
36576 * arguments: (value, key, object). Iteratee functions may exit iteration
36577 * early by explicitly returning `false`.
36578 *
36579 * @static
36580 * @memberOf _
36581 * @since 0.3.0
36582 * @category Object
36583 * @param {Object} object The object to iterate over.
36584 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
36585 * @returns {Object} Returns `object`.
36586 * @see _.forOwnRight
36587 * @example
36588 *
36589 * function Foo() {
36590 * this.a = 1;
36591 * this.b = 2;
36592 * }
36593 *
36594 * Foo.prototype.c = 3;
36595 *
36596 * _.forOwn(new Foo, function(value, key) {
36597 * console.log(key);
36598 * });
36599 * // => Logs 'a' then 'b' (iteration order is not guaranteed).
36600 */
36601 function forOwn(object, iteratee) {
36602 return object && baseForOwn(object, getIteratee(iteratee, 3));
36603 }
36604
36605 /**
36606 * This method is like `_.forOwn` except that it iterates over properties of
36607 * `object` in the opposite order.
36608 *
36609 * @static
36610 * @memberOf _
36611 * @since 2.0.0
36612 * @category Object
36613 * @param {Object} object The object to iterate over.
36614 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
36615 * @returns {Object} Returns `object`.
36616 * @see _.forOwn
36617 * @example
36618 *
36619 * function Foo() {
36620 * this.a = 1;
36621 * this.b = 2;
36622 * }
36623 *
36624 * Foo.prototype.c = 3;
36625 *
36626 * _.forOwnRight(new Foo, function(value, key) {
36627 * console.log(key);
36628 * });
36629 * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'.
36630 */
36631 function forOwnRight(object, iteratee) {
36632 return object && baseForOwnRight(object, getIteratee(iteratee, 3));
36633 }
36634
36635 /**
36636 * Creates an array of function property names from own enumerable properties
36637 * of `object`.
36638 *
36639 * @static
36640 * @since 0.1.0
36641 * @memberOf _
36642 * @category Object
36643 * @param {Object} object The object to inspect.
36644 * @returns {Array} Returns the function names.
36645 * @see _.functionsIn
36646 * @example
36647 *
36648 * function Foo() {
36649 * this.a = _.constant('a');
36650 * this.b = _.constant('b');
36651 * }
36652 *
36653 * Foo.prototype.c = _.constant('c');
36654 *
36655 * _.functions(new Foo);
36656 * // => ['a', 'b']
36657 */
36658 function functions(object) {
36659 return object == null ? [] : baseFunctions(object, keys(object));
36660 }
36661
36662 /**
36663 * Creates an array of function property names from own and inherited
36664 * enumerable properties of `object`.
36665 *
36666 * @static
36667 * @memberOf _
36668 * @since 4.0.0
36669 * @category Object
36670 * @param {Object} object The object to inspect.
36671 * @returns {Array} Returns the function names.
36672 * @see _.functions
36673 * @example
36674 *
36675 * function Foo() {
36676 * this.a = _.constant('a');
36677 * this.b = _.constant('b');
36678 * }
36679 *
36680 * Foo.prototype.c = _.constant('c');
36681 *
36682 * _.functionsIn(new Foo);
36683 * // => ['a', 'b', 'c']
36684 */
36685 function functionsIn(object) {
36686 return object == null ? [] : baseFunctions(object, keysIn(object));
36687 }
36688
36689 /**
36690 * Gets the value at `path` of `object`. If the resolved value is
36691 * `undefined`, the `defaultValue` is returned in its place.
36692 *
36693 * @static
36694 * @memberOf _
36695 * @since 3.7.0
36696 * @category Object
36697 * @param {Object} object The object to query.
36698 * @param {Array|string} path The path of the property to get.
36699 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
36700 * @returns {*} Returns the resolved value.
36701 * @example
36702 *
36703 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
36704 *
36705 * _.get(object, 'a[0].b.c');
36706 * // => 3
36707 *
36708 * _.get(object, ['a', '0', 'b', 'c']);
36709 * // => 3
36710 *
36711 * _.get(object, 'a.b.c', 'default');
36712 * // => 'default'
36713 */
36714 function get(object, path, defaultValue) {
36715 var result = object == null ? undefined : baseGet(object, path);
36716 return result === undefined ? defaultValue : result;
36717 }
36718
36719 /**
36720 * Checks if `path` is a direct property of `object`.
36721 *
36722 * @static
36723 * @since 0.1.0
36724 * @memberOf _
36725 * @category Object
36726 * @param {Object} object The object to query.
36727 * @param {Array|string} path The path to check.
36728 * @returns {boolean} Returns `true` if `path` exists, else `false`.
36729 * @example
36730 *
36731 * var object = { 'a': { 'b': 2 } };
36732 * var other = _.create({ 'a': _.create({ 'b': 2 }) });
36733 *
36734 * _.has(object, 'a');
36735 * // => true
36736 *
36737 * _.has(object, 'a.b');
36738 * // => true
36739 *
36740 * _.has(object, ['a', 'b']);
36741 * // => true
36742 *
36743 * _.has(other, 'a');
36744 * // => false
36745 */
36746 function has(object, path) {
36747 return object != null && hasPath(object, path, baseHas);
36748 }
36749
36750 /**
36751 * Checks if `path` is a direct or inherited property of `object`.
36752 *
36753 * @static
36754 * @memberOf _
36755 * @since 4.0.0
36756 * @category Object
36757 * @param {Object} object The object to query.
36758 * @param {Array|string} path The path to check.
36759 * @returns {boolean} Returns `true` if `path` exists, else `false`.
36760 * @example
36761 *
36762 * var object = _.create({ 'a': _.create({ 'b': 2 }) });
36763 *
36764 * _.hasIn(object, 'a');
36765 * // => true
36766 *
36767 * _.hasIn(object, 'a.b');
36768 * // => true
36769 *
36770 * _.hasIn(object, ['a', 'b']);
36771 * // => true
36772 *
36773 * _.hasIn(object, 'b');
36774 * // => false
36775 */
36776 function hasIn(object, path) {
36777 return object != null && hasPath(object, path, baseHasIn);
36778 }
36779
36780 /**
36781 * Creates an object composed of the inverted keys and values of `object`.
36782 * If `object` contains duplicate values, subsequent values overwrite
36783 * property assignments of previous values.
36784 *
36785 * @static
36786 * @memberOf _
36787 * @since 0.7.0
36788 * @category Object
36789 * @param {Object} object The object to invert.
36790 * @returns {Object} Returns the new inverted object.
36791 * @example
36792 *
36793 * var object = { 'a': 1, 'b': 2, 'c': 1 };
36794 *
36795 * _.invert(object);
36796 * // => { '1': 'c', '2': 'b' }
36797 */
36798 var invert = createInverter(function(result, value, key) {
36799 result[value] = key;
36800 }, constant(identity));
36801
36802 /**
36803 * This method is like `_.invert` except that the inverted object is generated
36804 * from the results of running each element of `object` thru `iteratee`. The
36805 * corresponding inverted value of each inverted key is an array of keys
36806 * responsible for generating the inverted value. The iteratee is invoked
36807 * with one argument: (value).
36808 *
36809 * @static
36810 * @memberOf _
36811 * @since 4.1.0
36812 * @category Object
36813 * @param {Object} object The object to invert.
36814 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
36815 * @returns {Object} Returns the new inverted object.
36816 * @example
36817 *
36818 * var object = { 'a': 1, 'b': 2, 'c': 1 };
36819 *
36820 * _.invertBy(object);
36821 * // => { '1': ['a', 'c'], '2': ['b'] }
36822 *
36823 * _.invertBy(object, function(value) {
36824 * return 'group' + value;
36825 * });
36826 * // => { 'group1': ['a', 'c'], 'group2': ['b'] }
36827 */
36828 var invertBy = createInverter(function(result, value, key) {
36829 if (hasOwnProperty.call(result, value)) {
36830 result[value].push(key);
36831 } else {
36832 result[value] = [key];
36833 }
36834 }, getIteratee);
36835
36836 /**
36837 * Invokes the method at `path` of `object`.
36838 *
36839 * @static
36840 * @memberOf _
36841 * @since 4.0.0
36842 * @category Object
36843 * @param {Object} object The object to query.
36844 * @param {Array|string} path The path of the method to invoke.
36845 * @param {...*} [args] The arguments to invoke the method with.
36846 * @returns {*} Returns the result of the invoked method.
36847 * @example
36848 *
36849 * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };
36850 *
36851 * _.invoke(object, 'a[0].b.c.slice', 1, 3);
36852 * // => [2, 3]
36853 */
36854 var invoke = baseRest(baseInvoke);
36855
36856 /**
36857 * Creates an array of the own enumerable property names of `object`.
36858 *
36859 * **Note:** Non-object values are coerced to objects. See the
36860 * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
36861 * for more details.
36862 *
36863 * @static
36864 * @since 0.1.0
36865 * @memberOf _
36866 * @category Object
36867 * @param {Object} object The object to query.
36868 * @returns {Array} Returns the array of property names.
36869 * @example
36870 *
36871 * function Foo() {
36872 * this.a = 1;
36873 * this.b = 2;
36874 * }
36875 *
36876 * Foo.prototype.c = 3;
36877 *
36878 * _.keys(new Foo);
36879 * // => ['a', 'b'] (iteration order is not guaranteed)
36880 *
36881 * _.keys('hi');
36882 * // => ['0', '1']
36883 */
36884 function keys(object) {
36885 return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
36886 }
36887
36888 /**
36889 * Creates an array of the own and inherited enumerable property names of `object`.
36890 *
36891 * **Note:** Non-object values are coerced to objects.
36892 *
36893 * @static
36894 * @memberOf _
36895 * @since 3.0.0
36896 * @category Object
36897 * @param {Object} object The object to query.
36898 * @returns {Array} Returns the array of property names.
36899 * @example
36900 *
36901 * function Foo() {
36902 * this.a = 1;
36903 * this.b = 2;
36904 * }
36905 *
36906 * Foo.prototype.c = 3;
36907 *
36908 * _.keysIn(new Foo);
36909 * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
36910 */
36911 function keysIn(object) {
36912 return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
36913 }
36914
36915 /**
36916 * The opposite of `_.mapValues`; this method creates an object with the
36917 * same values as `object` and keys generated by running each own enumerable
36918 * string keyed property of `object` thru `iteratee`. The iteratee is invoked
36919 * with three arguments: (value, key, object).
36920 *
36921 * @static
36922 * @memberOf _
36923 * @since 3.8.0
36924 * @category Object
36925 * @param {Object} object The object to iterate over.
36926 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
36927 * @returns {Object} Returns the new mapped object.
36928 * @see _.mapValues
36929 * @example
36930 *
36931 * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
36932 * return key + value;
36933 * });
36934 * // => { 'a1': 1, 'b2': 2 }
36935 */
36936 function mapKeys(object, iteratee) {
36937 var result = {};
36938 iteratee = getIteratee(iteratee, 3);
36939
36940 baseForOwn(object, function(value, key, object) {
36941 baseAssignValue(result, iteratee(value, key, object), value);
36942 });
36943 return result;
36944 }
36945
36946 /**
36947 * Creates an object with the same keys as `object` and values generated
36948 * by running each own enumerable string keyed property of `object` thru
36949 * `iteratee`. The iteratee is invoked with three arguments:
36950 * (value, key, object).
36951 *
36952 * @static
36953 * @memberOf _
36954 * @since 2.4.0
36955 * @category Object
36956 * @param {Object} object The object to iterate over.
36957 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
36958 * @returns {Object} Returns the new mapped object.
36959 * @see _.mapKeys
36960 * @example
36961 *
36962 * var users = {
36963 * 'fred': { 'user': 'fred', 'age': 40 },
36964 * 'pebbles': { 'user': 'pebbles', 'age': 1 }
36965 * };
36966 *
36967 * _.mapValues(users, function(o) { return o.age; });
36968 * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
36969 *
36970 * // The `_.property` iteratee shorthand.
36971 * _.mapValues(users, 'age');
36972 * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
36973 */
36974 function mapValues(object, iteratee) {
36975 var result = {};
36976 iteratee = getIteratee(iteratee, 3);
36977
36978 baseForOwn(object, function(value, key, object) {
36979 baseAssignValue(result, key, iteratee(value, key, object));
36980 });
36981 return result;
36982 }
36983
36984 /**
36985 * This method is like `_.assign` except that it recursively merges own and
36986 * inherited enumerable string keyed properties of source objects into the
36987 * destination object. Source properties that resolve to `undefined` are
36988 * skipped if a destination value exists. Array and plain object properties
36989 * are merged recursively. Other objects and value types are overridden by
36990 * assignment. Source objects are applied from left to right. Subsequent
36991 * sources overwrite property assignments of previous sources.
36992 *
36993 * **Note:** This method mutates `object`.
36994 *
36995 * @static
36996 * @memberOf _
36997 * @since 0.5.0
36998 * @category Object
36999 * @param {Object} object The destination object.
37000 * @param {...Object} [sources] The source objects.
37001 * @returns {Object} Returns `object`.
37002 * @example
37003 *
37004 * var object = {
37005 * 'a': [{ 'b': 2 }, { 'd': 4 }]
37006 * };
37007 *
37008 * var other = {
37009 * 'a': [{ 'c': 3 }, { 'e': 5 }]
37010 * };
37011 *
37012 * _.merge(object, other);
37013 * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
37014 */
37015 var merge = createAssigner(function(object, source, srcIndex) {
37016 baseMerge(object, source, srcIndex);
37017 });
37018
37019 /**
37020 * This method is like `_.merge` except that it accepts `customizer` which
37021 * is invoked to produce the merged values of the destination and source
37022 * properties. If `customizer` returns `undefined`, merging is handled by the
37023 * method instead. The `customizer` is invoked with six arguments:
37024 * (objValue, srcValue, key, object, source, stack).
37025 *
37026 * **Note:** This method mutates `object`.
37027 *
37028 * @static
37029 * @memberOf _
37030 * @since 4.0.0
37031 * @category Object
37032 * @param {Object} object The destination object.
37033 * @param {...Object} sources The source objects.
37034 * @param {Function} customizer The function to customize assigned values.
37035 * @returns {Object} Returns `object`.
37036 * @example
37037 *
37038 * function customizer(objValue, srcValue) {
37039 * if (_.isArray(objValue)) {
37040 * return objValue.concat(srcValue);
37041 * }
37042 * }
37043 *
37044 * var object = { 'a': [1], 'b': [2] };
37045 * var other = { 'a': [3], 'b': [4] };
37046 *
37047 * _.mergeWith(object, other, customizer);
37048 * // => { 'a': [1, 3], 'b': [2, 4] }
37049 */
37050 var mergeWith = createAssigner(function(object, source, srcIndex, customizer) {
37051 baseMerge(object, source, srcIndex, customizer);
37052 });
37053
37054 /**
37055 * The opposite of `_.pick`; this method creates an object composed of the
37056 * own and inherited enumerable string keyed properties of `object` that are
37057 * not omitted.
37058 *
37059 * @static
37060 * @since 0.1.0
37061 * @memberOf _
37062 * @category Object
37063 * @param {Object} object The source object.
37064 * @param {...(string|string[])} [props] The property identifiers to omit.
37065 * @returns {Object} Returns the new object.
37066 * @example
37067 *
37068 * var object = { 'a': 1, 'b': '2', 'c': 3 };
37069 *
37070 * _.omit(object, ['a', 'c']);
37071 * // => { 'b': '2' }
37072 */
37073 var omit = flatRest(function(object, props) {
37074 if (object == null) {
37075 return {};
37076 }
37077 props = arrayMap(props, toKey);
37078 return basePick(object, baseDifference(getAllKeysIn(object), props));
37079 });
37080
37081 /**
37082 * The opposite of `_.pickBy`; this method creates an object composed of
37083 * the own and inherited enumerable string keyed properties of `object` that
37084 * `predicate` doesn't return truthy for. The predicate is invoked with two
37085 * arguments: (value, key).
37086 *
37087 * @static
37088 * @memberOf _
37089 * @since 4.0.0
37090 * @category Object
37091 * @param {Object} object The source object.
37092 * @param {Function} [predicate=_.identity] The function invoked per property.
37093 * @returns {Object} Returns the new object.
37094 * @example
37095 *
37096 * var object = { 'a': 1, 'b': '2', 'c': 3 };
37097 *
37098 * _.omitBy(object, _.isNumber);
37099 * // => { 'b': '2' }
37100 */
37101 function omitBy(object, predicate) {
37102 return pickBy(object, negate(getIteratee(predicate)));
37103 }
37104
37105 /**
37106 * Creates an object composed of the picked `object` properties.
37107 *
37108 * @static
37109 * @since 0.1.0
37110 * @memberOf _
37111 * @category Object
37112 * @param {Object} object The source object.
37113 * @param {...(string|string[])} [props] The property identifiers to pick.
37114 * @returns {Object} Returns the new object.
37115 * @example
37116 *
37117 * var object = { 'a': 1, 'b': '2', 'c': 3 };
37118 *
37119 * _.pick(object, ['a', 'c']);
37120 * // => { 'a': 1, 'c': 3 }
37121 */
37122 var pick = flatRest(function(object, props) {
37123 return object == null ? {} : basePick(object, arrayMap(props, toKey));
37124 });
37125
37126 /**
37127 * Creates an object composed of the `object` properties `predicate` returns
37128 * truthy for. The predicate is invoked with two arguments: (value, key).
37129 *
37130 * @static
37131 * @memberOf _
37132 * @since 4.0.0
37133 * @category Object
37134 * @param {Object} object The source object.
37135 * @param {Function} [predicate=_.identity] The function invoked per property.
37136 * @returns {Object} Returns the new object.
37137 * @example
37138 *
37139 * var object = { 'a': 1, 'b': '2', 'c': 3 };
37140 *
37141 * _.pickBy(object, _.isNumber);
37142 * // => { 'a': 1, 'c': 3 }
37143 */
37144 function pickBy(object, predicate) {
37145 return object == null ? {} : basePickBy(object, getAllKeysIn(object), getIteratee(predicate));
37146 }
37147
37148 /**
37149 * This method is like `_.get` except that if the resolved value is a
37150 * function it's invoked with the `this` binding of its parent object and
37151 * its result is returned.
37152 *
37153 * @static
37154 * @since 0.1.0
37155 * @memberOf _
37156 * @category Object
37157 * @param {Object} object The object to query.
37158 * @param {Array|string} path The path of the property to resolve.
37159 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
37160 * @returns {*} Returns the resolved value.
37161 * @example
37162 *
37163 * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
37164 *
37165 * _.result(object, 'a[0].b.c1');
37166 * // => 3
37167 *
37168 * _.result(object, 'a[0].b.c2');
37169 * // => 4
37170 *
37171 * _.result(object, 'a[0].b.c3', 'default');
37172 * // => 'default'
37173 *
37174 * _.result(object, 'a[0].b.c3', _.constant('default'));
37175 * // => 'default'
37176 */
37177 function result(object, path, defaultValue) {
37178 path = isKey(path, object) ? [path] : castPath(path);
37179
37180 var index = -1,
37181 length = path.length;
37182
37183 // Ensure the loop is entered when path is empty.
37184 if (!length) {
37185 object = undefined;
37186 length = 1;
37187 }
37188 while (++index < length) {
37189 var value = object == null ? undefined : object[toKey(path[index])];
37190 if (value === undefined) {
37191 index = length;
37192 value = defaultValue;
37193 }
37194 object = isFunction(value) ? value.call(object) : value;
37195 }
37196 return object;
37197 }
37198
37199 /**
37200 * Sets the value at `path` of `object`. If a portion of `path` doesn't exist,
37201 * it's created. Arrays are created for missing index properties while objects
37202 * are created for all other missing properties. Use `_.setWith` to customize
37203 * `path` creation.
37204 *
37205 * **Note:** This method mutates `object`.
37206 *
37207 * @static
37208 * @memberOf _
37209 * @since 3.7.0
37210 * @category Object
37211 * @param {Object} object The object to modify.
37212 * @param {Array|string} path The path of the property to set.
37213 * @param {*} value The value to set.
37214 * @returns {Object} Returns `object`.
37215 * @example
37216 *
37217 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
37218 *
37219 * _.set(object, 'a[0].b.c', 4);
37220 * console.log(object.a[0].b.c);
37221 * // => 4
37222 *
37223 * _.set(object, ['x', '0', 'y', 'z'], 5);
37224 * console.log(object.x[0].y.z);
37225 * // => 5
37226 */
37227 function set(object, path, value) {
37228 return object == null ? object : baseSet(object, path, value);
37229 }
37230
37231 /**
37232 * This method is like `_.set` except that it accepts `customizer` which is
37233 * invoked to produce the objects of `path`. If `customizer` returns `undefined`
37234 * path creation is handled by the method instead. The `customizer` is invoked
37235 * with three arguments: (nsValue, key, nsObject).
37236 *
37237 * **Note:** This method mutates `object`.
37238 *
37239 * @static
37240 * @memberOf _
37241 * @since 4.0.0
37242 * @category Object
37243 * @param {Object} object The object to modify.
37244 * @param {Array|string} path The path of the property to set.
37245 * @param {*} value The value to set.
37246 * @param {Function} [customizer] The function to customize assigned values.
37247 * @returns {Object} Returns `object`.
37248 * @example
37249 *
37250 * var object = {};
37251 *
37252 * _.setWith(object, '[0][1]', 'a', Object);
37253 * // => { '0': { '1': 'a' } }
37254 */
37255 function setWith(object, path, value, customizer) {
37256 customizer = typeof customizer == 'function' ? customizer : undefined;
37257 return object == null ? object : baseSet(object, path, value, customizer);
37258 }
37259
37260 /**
37261 * Creates an array of own enumerable string keyed-value pairs for `object`
37262 * which can be consumed by `_.fromPairs`. If `object` is a map or set, its
37263 * entries are returned.
37264 *
37265 * @static
37266 * @memberOf _
37267 * @since 4.0.0
37268 * @alias entries
37269 * @category Object
37270 * @param {Object} object The object to query.
37271 * @returns {Array} Returns the key-value pairs.
37272 * @example
37273 *
37274 * function Foo() {
37275 * this.a = 1;
37276 * this.b = 2;
37277 * }
37278 *
37279 * Foo.prototype.c = 3;
37280 *
37281 * _.toPairs(new Foo);
37282 * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)
37283 */
37284 var toPairs = createToPairs(keys);
37285
37286 /**
37287 * Creates an array of own and inherited enumerable string keyed-value pairs
37288 * for `object` which can be consumed by `_.fromPairs`. If `object` is a map
37289 * or set, its entries are returned.
37290 *
37291 * @static
37292 * @memberOf _
37293 * @since 4.0.0
37294 * @alias entriesIn
37295 * @category Object
37296 * @param {Object} object The object to query.
37297 * @returns {Array} Returns the key-value pairs.
37298 * @example
37299 *
37300 * function Foo() {
37301 * this.a = 1;
37302 * this.b = 2;
37303 * }
37304 *
37305 * Foo.prototype.c = 3;
37306 *
37307 * _.toPairsIn(new Foo);
37308 * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed)
37309 */
37310 var toPairsIn = createToPairs(keysIn);
37311
37312 /**
37313 * An alternative to `_.reduce`; this method transforms `object` to a new
37314 * `accumulator` object which is the result of running each of its own
37315 * enumerable string keyed properties thru `iteratee`, with each invocation
37316 * potentially mutating the `accumulator` object. If `accumulator` is not
37317 * provided, a new object with the same `[[Prototype]]` will be used. The
37318 * iteratee is invoked with four arguments: (accumulator, value, key, object).
37319 * Iteratee functions may exit iteration early by explicitly returning `false`.
37320 *
37321 * @static
37322 * @memberOf _
37323 * @since 1.3.0
37324 * @category Object
37325 * @param {Object} object The object to iterate over.
37326 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
37327 * @param {*} [accumulator] The custom accumulator value.
37328 * @returns {*} Returns the accumulated value.
37329 * @example
37330 *
37331 * _.transform([2, 3, 4], function(result, n) {
37332 * result.push(n *= n);
37333 * return n % 2 == 0;
37334 * }, []);
37335 * // => [4, 9]
37336 *
37337 * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
37338 * (result[value] || (result[value] = [])).push(key);
37339 * }, {});
37340 * // => { '1': ['a', 'c'], '2': ['b'] }
37341 */
37342 function transform(object, iteratee, accumulator) {
37343 var isArr = isArray(object),
37344 isArrLike = isArr || isBuffer(object) || isTypedArray(object);
37345
37346 iteratee = getIteratee(iteratee, 4);
37347 if (accumulator == null) {
37348 var Ctor = object && object.constructor;
37349 if (isArrLike) {
37350 accumulator = isArr ? new Ctor : [];
37351 }
37352 else if (isObject(object)) {
37353 accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};
37354 }
37355 else {
37356 accumulator = {};
37357 }
37358 }
37359 (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) {
37360 return iteratee(accumulator, value, index, object);
37361 });
37362 return accumulator;
37363 }
37364
37365 /**
37366 * Removes the property at `path` of `object`.
37367 *
37368 * **Note:** This method mutates `object`.
37369 *
37370 * @static
37371 * @memberOf _
37372 * @since 4.0.0
37373 * @category Object
37374 * @param {Object} object The object to modify.
37375 * @param {Array|string} path The path of the property to unset.
37376 * @returns {boolean} Returns `true` if the property is deleted, else `false`.
37377 * @example
37378 *
37379 * var object = { 'a': [{ 'b': { 'c': 7 } }] };
37380 * _.unset(object, 'a[0].b.c');
37381 * // => true
37382 *
37383 * console.log(object);
37384 * // => { 'a': [{ 'b': {} }] };
37385 *
37386 * _.unset(object, ['a', '0', 'b', 'c']);
37387 * // => true
37388 *
37389 * console.log(object);
37390 * // => { 'a': [{ 'b': {} }] };
37391 */
37392 function unset(object, path) {
37393 return object == null ? true : baseUnset(object, path);
37394 }
37395
37396 /**
37397 * This method is like `_.set` except that accepts `updater` to produce the
37398 * value to set. Use `_.updateWith` to customize `path` creation. The `updater`
37399 * is invoked with one argument: (value).
37400 *
37401 * **Note:** This method mutates `object`.
37402 *
37403 * @static
37404 * @memberOf _
37405 * @since 4.6.0
37406 * @category Object
37407 * @param {Object} object The object to modify.
37408 * @param {Array|string} path The path of the property to set.
37409 * @param {Function} updater The function to produce the updated value.
37410 * @returns {Object} Returns `object`.
37411 * @example
37412 *
37413 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
37414 *
37415 * _.update(object, 'a[0].b.c', function(n) { return n * n; });
37416 * console.log(object.a[0].b.c);
37417 * // => 9
37418 *
37419 * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });
37420 * console.log(object.x[0].y.z);
37421 * // => 0
37422 */
37423 function update(object, path, updater) {
37424 return object == null ? object : baseUpdate(object, path, castFunction(updater));
37425 }
37426
37427 /**
37428 * This method is like `_.update` except that it accepts `customizer` which is
37429 * invoked to produce the objects of `path`. If `customizer` returns `undefined`
37430 * path creation is handled by the method instead. The `customizer` is invoked
37431 * with three arguments: (nsValue, key, nsObject).
37432 *
37433 * **Note:** This method mutates `object`.
37434 *
37435 * @static
37436 * @memberOf _
37437 * @since 4.6.0
37438 * @category Object
37439 * @param {Object} object The object to modify.
37440 * @param {Array|string} path The path of the property to set.
37441 * @param {Function} updater The function to produce the updated value.
37442 * @param {Function} [customizer] The function to customize assigned values.
37443 * @returns {Object} Returns `object`.
37444 * @example
37445 *
37446 * var object = {};
37447 *
37448 * _.updateWith(object, '[0][1]', _.constant('a'), Object);
37449 * // => { '0': { '1': 'a' } }
37450 */
37451 function updateWith(object, path, updater, customizer) {
37452 customizer = typeof customizer == 'function' ? customizer : undefined;
37453 return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer);
37454 }
37455
37456 /**
37457 * Creates an array of the own enumerable string keyed property values of `object`.
37458 *
37459 * **Note:** Non-object values are coerced to objects.
37460 *
37461 * @static
37462 * @since 0.1.0
37463 * @memberOf _
37464 * @category Object
37465 * @param {Object} object The object to query.
37466 * @returns {Array} Returns the array of property values.
37467 * @example
37468 *
37469 * function Foo() {
37470 * this.a = 1;
37471 * this.b = 2;
37472 * }
37473 *
37474 * Foo.prototype.c = 3;
37475 *
37476 * _.values(new Foo);
37477 * // => [1, 2] (iteration order is not guaranteed)
37478 *
37479 * _.values('hi');
37480 * // => ['h', 'i']
37481 */
37482 function values(object) {
37483 return object ? baseValues(object, keys(object)) : [];
37484 }
37485
37486 /**
37487 * Creates an array of the own and inherited enumerable string keyed property
37488 * values of `object`.
37489 *
37490 * **Note:** Non-object values are coerced to objects.
37491 *
37492 * @static
37493 * @memberOf _
37494 * @since 3.0.0
37495 * @category Object
37496 * @param {Object} object The object to query.
37497 * @returns {Array} Returns the array of property values.
37498 * @example
37499 *
37500 * function Foo() {
37501 * this.a = 1;
37502 * this.b = 2;
37503 * }
37504 *
37505 * Foo.prototype.c = 3;
37506 *
37507 * _.valuesIn(new Foo);
37508 * // => [1, 2, 3] (iteration order is not guaranteed)
37509 */
37510 function valuesIn(object) {
37511 return object == null ? [] : baseValues(object, keysIn(object));
37512 }
37513
37514 /*------------------------------------------------------------------------*/
37515
37516 /**
37517 * Clamps `number` within the inclusive `lower` and `upper` bounds.
37518 *
37519 * @static
37520 * @memberOf _
37521 * @since 4.0.0
37522 * @category Number
37523 * @param {number} number The number to clamp.
37524 * @param {number} [lower] The lower bound.
37525 * @param {number} upper The upper bound.
37526 * @returns {number} Returns the clamped number.
37527 * @example
37528 *
37529 * _.clamp(-10, -5, 5);
37530 * // => -5
37531 *
37532 * _.clamp(10, -5, 5);
37533 * // => 5
37534 */
37535 function clamp(number, lower, upper) {
37536 if (upper === undefined) {
37537 upper = lower;
37538 lower = undefined;
37539 }
37540 if (upper !== undefined) {
37541 upper = toNumber(upper);
37542 upper = upper === upper ? upper : 0;
37543 }
37544 if (lower !== undefined) {
37545 lower = toNumber(lower);
37546 lower = lower === lower ? lower : 0;
37547 }
37548 return baseClamp(toNumber(number), lower, upper);
37549 }
37550
37551 /**
37552 * Checks if `n` is between `start` and up to, but not including, `end`. If
37553 * `end` is not specified, it's set to `start` with `start` then set to `0`.
37554 * If `start` is greater than `end` the params are swapped to support
37555 * negative ranges.
37556 *
37557 * @static
37558 * @memberOf _
37559 * @since 3.3.0
37560 * @category Number
37561 * @param {number} number The number to check.
37562 * @param {number} [start=0] The start of the range.
37563 * @param {number} end The end of the range.
37564 * @returns {boolean} Returns `true` if `number` is in the range, else `false`.
37565 * @see _.range, _.rangeRight
37566 * @example
37567 *
37568 * _.inRange(3, 2, 4);
37569 * // => true
37570 *
37571 * _.inRange(4, 8);
37572 * // => true
37573 *
37574 * _.inRange(4, 2);
37575 * // => false
37576 *
37577 * _.inRange(2, 2);
37578 * // => false
37579 *
37580 * _.inRange(1.2, 2);
37581 * // => true
37582 *
37583 * _.inRange(5.2, 4);
37584 * // => false
37585 *
37586 * _.inRange(-3, -2, -6);
37587 * // => true
37588 */
37589 function inRange(number, start, end) {
37590 start = toFinite(start);
37591 if (end === undefined) {
37592 end = start;
37593 start = 0;
37594 } else {
37595 end = toFinite(end);
37596 }
37597 number = toNumber(number);
37598 return baseInRange(number, start, end);
37599 }
37600
37601 /**
37602 * Produces a random number between the inclusive `lower` and `upper` bounds.
37603 * If only one argument is provided a number between `0` and the given number
37604 * is returned. If `floating` is `true`, or either `lower` or `upper` are
37605 * floats, a floating-point number is returned instead of an integer.
37606 *
37607 * **Note:** JavaScript follows the IEEE-754 standard for resolving
37608 * floating-point values which can produce unexpected results.
37609 *
37610 * @static
37611 * @memberOf _
37612 * @since 0.7.0
37613 * @category Number
37614 * @param {number} [lower=0] The lower bound.
37615 * @param {number} [upper=1] The upper bound.
37616 * @param {boolean} [floating] Specify returning a floating-point number.
37617 * @returns {number} Returns the random number.
37618 * @example
37619 *
37620 * _.random(0, 5);
37621 * // => an integer between 0 and 5
37622 *
37623 * _.random(5);
37624 * // => also an integer between 0 and 5
37625 *
37626 * _.random(5, true);
37627 * // => a floating-point number between 0 and 5
37628 *
37629 * _.random(1.2, 5.2);
37630 * // => a floating-point number between 1.2 and 5.2
37631 */
37632 function random(lower, upper, floating) {
37633 if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) {
37634 upper = floating = undefined;
37635 }
37636 if (floating === undefined) {
37637 if (typeof upper == 'boolean') {
37638 floating = upper;
37639 upper = undefined;
37640 }
37641 else if (typeof lower == 'boolean') {
37642 floating = lower;
37643 lower = undefined;
37644 }
37645 }
37646 if (lower === undefined && upper === undefined) {
37647 lower = 0;
37648 upper = 1;
37649 }
37650 else {
37651 lower = toFinite(lower);
37652 if (upper === undefined) {
37653 upper = lower;
37654 lower = 0;
37655 } else {
37656 upper = toFinite(upper);
37657 }
37658 }
37659 if (lower > upper) {
37660 var temp = lower;
37661 lower = upper;
37662 upper = temp;
37663 }
37664 if (floating || lower % 1 || upper % 1) {
37665 var rand = nativeRandom();
37666 return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper);
37667 }
37668 return baseRandom(lower, upper);
37669 }
37670
37671 /*------------------------------------------------------------------------*/
37672
37673 /**
37674 * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
37675 *
37676 * @static
37677 * @memberOf _
37678 * @since 3.0.0
37679 * @category String
37680 * @param {string} [string=''] The string to convert.
37681 * @returns {string} Returns the camel cased string.
37682 * @example
37683 *
37684 * _.camelCase('Foo Bar');
37685 * // => 'fooBar'
37686 *
37687 * _.camelCase('--foo-bar--');
37688 * // => 'fooBar'
37689 *
37690 * _.camelCase('__FOO_BAR__');
37691 * // => 'fooBar'
37692 */
37693 var camelCase = createCompounder(function(result, word, index) {
37694 word = word.toLowerCase();
37695 return result + (index ? capitalize(word) : word);
37696 });
37697
37698 /**
37699 * Converts the first character of `string` to upper case and the remaining
37700 * to lower case.
37701 *
37702 * @static
37703 * @memberOf _
37704 * @since 3.0.0
37705 * @category String
37706 * @param {string} [string=''] The string to capitalize.
37707 * @returns {string} Returns the capitalized string.
37708 * @example
37709 *
37710 * _.capitalize('FRED');
37711 * // => 'Fred'
37712 */
37713 function capitalize(string) {
37714 return upperFirst(toString(string).toLowerCase());
37715 }
37716
37717 /**
37718 * Deburrs `string` by converting
37719 * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
37720 * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
37721 * letters to basic Latin letters and removing
37722 * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
37723 *
37724 * @static
37725 * @memberOf _
37726 * @since 3.0.0
37727 * @category String
37728 * @param {string} [string=''] The string to deburr.
37729 * @returns {string} Returns the deburred string.
37730 * @example
37731 *
37732 * _.deburr('déjà vu');
37733 * // => 'deja vu'
37734 */
37735 function deburr(string) {
37736 string = toString(string);
37737 return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
37738 }
37739
37740 /**
37741 * Checks if `string` ends with the given target string.
37742 *
37743 * @static
37744 * @memberOf _
37745 * @since 3.0.0
37746 * @category String
37747 * @param {string} [string=''] The string to inspect.
37748 * @param {string} [target] The string to search for.
37749 * @param {number} [position=string.length] The position to search up to.
37750 * @returns {boolean} Returns `true` if `string` ends with `target`,
37751 * else `false`.
37752 * @example
37753 *
37754 * _.endsWith('abc', 'c');
37755 * // => true
37756 *
37757 * _.endsWith('abc', 'b');
37758 * // => false
37759 *
37760 * _.endsWith('abc', 'b', 2);
37761 * // => true
37762 */
37763 function endsWith(string, target, position) {
37764 string = toString(string);
37765 target = baseToString(target);
37766
37767 var length = string.length;
37768 position = position === undefined
37769 ? length
37770 : baseClamp(toInteger(position), 0, length);
37771
37772 var end = position;
37773 position -= target.length;
37774 return position >= 0 && string.slice(position, end) == target;
37775 }
37776
37777 /**
37778 * Converts the characters "&", "<", ">", '"', and "'" in `string` to their
37779 * corresponding HTML entities.
37780 *
37781 * **Note:** No other characters are escaped. To escape additional
37782 * characters use a third-party library like [_he_](https://mths.be/he).
37783 *
37784 * Though the ">" character is escaped for symmetry, characters like
37785 * ">" and "/" don't need escaping in HTML and have no special meaning
37786 * unless they're part of a tag or unquoted attribute value. See
37787 * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
37788 * (under "semi-related fun fact") for more details.
37789 *
37790 * When working with HTML you should always
37791 * [quote attribute values](http://wonko.com/post/html-escaping) to reduce
37792 * XSS vectors.
37793 *
37794 * @static
37795 * @since 0.1.0
37796 * @memberOf _
37797 * @category String
37798 * @param {string} [string=''] The string to escape.
37799 * @returns {string} Returns the escaped string.
37800 * @example
37801 *
37802 * _.escape('fred, barney, & pebbles');
37803 * // => 'fred, barney, &amp; pebbles'
37804 */
37805 function escape(string) {
37806 string = toString(string);
37807 return (string && reHasUnescapedHtml.test(string))
37808 ? string.replace(reUnescapedHtml, escapeHtmlChar)
37809 : string;
37810 }
37811
37812 /**
37813 * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+",
37814 * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`.
37815 *
37816 * @static
37817 * @memberOf _
37818 * @since 3.0.0
37819 * @category String
37820 * @param {string} [string=''] The string to escape.
37821 * @returns {string} Returns the escaped string.
37822 * @example
37823 *
37824 * _.escapeRegExp('[lodash](https://lodash.com/)');
37825 * // => '\[lodash\]\(https://lodash\.com/\)'
37826 */
37827 function escapeRegExp(string) {
37828 string = toString(string);
37829 return (string && reHasRegExpChar.test(string))
37830 ? string.replace(reRegExpChar, '\\$&')
37831 : string;
37832 }
37833
37834 /**
37835 * Converts `string` to
37836 * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
37837 *
37838 * @static
37839 * @memberOf _
37840 * @since 3.0.0
37841 * @category String
37842 * @param {string} [string=''] The string to convert.
37843 * @returns {string} Returns the kebab cased string.
37844 * @example
37845 *
37846 * _.kebabCase('Foo Bar');
37847 * // => 'foo-bar'
37848 *
37849 * _.kebabCase('fooBar');
37850 * // => 'foo-bar'
37851 *
37852 * _.kebabCase('__FOO_BAR__');
37853 * // => 'foo-bar'
37854 */
37855 var kebabCase = createCompounder(function(result, word, index) {
37856 return result + (index ? '-' : '') + word.toLowerCase();
37857 });
37858
37859 /**
37860 * Converts `string`, as space separated words, to lower case.
37861 *
37862 * @static
37863 * @memberOf _
37864 * @since 4.0.0
37865 * @category String
37866 * @param {string} [string=''] The string to convert.
37867 * @returns {string} Returns the lower cased string.
37868 * @example
37869 *
37870 * _.lowerCase('--Foo-Bar--');
37871 * // => 'foo bar'
37872 *
37873 * _.lowerCase('fooBar');
37874 * // => 'foo bar'
37875 *
37876 * _.lowerCase('__FOO_BAR__');
37877 * // => 'foo bar'
37878 */
37879 var lowerCase = createCompounder(function(result, word, index) {
37880 return result + (index ? ' ' : '') + word.toLowerCase();
37881 });
37882
37883 /**
37884 * Converts the first character of `string` to lower case.
37885 *
37886 * @static
37887 * @memberOf _
37888 * @since 4.0.0
37889 * @category String
37890 * @param {string} [string=''] The string to convert.
37891 * @returns {string} Returns the converted string.
37892 * @example
37893 *
37894 * _.lowerFirst('Fred');
37895 * // => 'fred'
37896 *
37897 * _.lowerFirst('FRED');
37898 * // => 'fRED'
37899 */
37900 var lowerFirst = createCaseFirst('toLowerCase');
37901
37902 /**
37903 * Pads `string` on the left and right sides if it's shorter than `length`.
37904 * Padding characters are truncated if they can't be evenly divided by `length`.
37905 *
37906 * @static
37907 * @memberOf _
37908 * @since 3.0.0
37909 * @category String
37910 * @param {string} [string=''] The string to pad.
37911 * @param {number} [length=0] The padding length.
37912 * @param {string} [chars=' '] The string used as padding.
37913 * @returns {string} Returns the padded string.
37914 * @example
37915 *
37916 * _.pad('abc', 8);
37917 * // => ' abc '
37918 *
37919 * _.pad('abc', 8, '_-');
37920 * // => '_-abc_-_'
37921 *
37922 * _.pad('abc', 3);
37923 * // => 'abc'
37924 */
37925 function pad(string, length, chars) {
37926 string = toString(string);
37927 length = toInteger(length);
37928
37929 var strLength = length ? stringSize(string) : 0;
37930 if (!length || strLength >= length) {
37931 return string;
37932 }
37933 var mid = (length - strLength) / 2;
37934 return (
37935 createPadding(nativeFloor(mid), chars) +
37936 string +
37937 createPadding(nativeCeil(mid), chars)
37938 );
37939 }
37940
37941 /**
37942 * Pads `string` on the right side if it's shorter than `length`. Padding
37943 * characters are truncated if they exceed `length`.
37944 *
37945 * @static
37946 * @memberOf _
37947 * @since 4.0.0
37948 * @category String
37949 * @param {string} [string=''] The string to pad.
37950 * @param {number} [length=0] The padding length.
37951 * @param {string} [chars=' '] The string used as padding.
37952 * @returns {string} Returns the padded string.
37953 * @example
37954 *
37955 * _.padEnd('abc', 6);
37956 * // => 'abc '
37957 *
37958 * _.padEnd('abc', 6, '_-');
37959 * // => 'abc_-_'
37960 *
37961 * _.padEnd('abc', 3);
37962 * // => 'abc'
37963 */
37964 function padEnd(string, length, chars) {
37965 string = toString(string);
37966 length = toInteger(length);
37967
37968 var strLength = length ? stringSize(string) : 0;
37969 return (length && strLength < length)
37970 ? (string + createPadding(length - strLength, chars))
37971 : string;
37972 }
37973
37974 /**
37975 * Pads `string` on the left side if it's shorter than `length`. Padding
37976 * characters are truncated if they exceed `length`.
37977 *
37978 * @static
37979 * @memberOf _
37980 * @since 4.0.0
37981 * @category String
37982 * @param {string} [string=''] The string to pad.
37983 * @param {number} [length=0] The padding length.
37984 * @param {string} [chars=' '] The string used as padding.
37985 * @returns {string} Returns the padded string.
37986 * @example
37987 *
37988 * _.padStart('abc', 6);
37989 * // => ' abc'
37990 *
37991 * _.padStart('abc', 6, '_-');
37992 * // => '_-_abc'
37993 *
37994 * _.padStart('abc', 3);
37995 * // => 'abc'
37996 */
37997 function padStart(string, length, chars) {
37998 string = toString(string);
37999 length = toInteger(length);
38000
38001 var strLength = length ? stringSize(string) : 0;
38002 return (length && strLength < length)
38003 ? (createPadding(length - strLength, chars) + string)
38004 : string;
38005 }
38006
38007 /**
38008 * Converts `string` to an integer of the specified radix. If `radix` is
38009 * `undefined` or `0`, a `radix` of `10` is used unless `value` is a
38010 * hexadecimal, in which case a `radix` of `16` is used.
38011 *
38012 * **Note:** This method aligns with the
38013 * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.
38014 *
38015 * @static
38016 * @memberOf _
38017 * @since 1.1.0
38018 * @category String
38019 * @param {string} string The string to convert.
38020 * @param {number} [radix=10] The radix to interpret `value` by.
38021 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
38022 * @returns {number} Returns the converted integer.
38023 * @example
38024 *
38025 * _.parseInt('08');
38026 * // => 8
38027 *
38028 * _.map(['6', '08', '10'], _.parseInt);
38029 * // => [6, 8, 10]
38030 */
38031 function parseInt(string, radix, guard) {
38032 if (guard || radix == null) {
38033 radix = 0;
38034 } else if (radix) {
38035 radix = +radix;
38036 }
38037 return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0);
38038 }
38039
38040 /**
38041 * Repeats the given string `n` times.
38042 *
38043 * @static
38044 * @memberOf _
38045 * @since 3.0.0
38046 * @category String
38047 * @param {string} [string=''] The string to repeat.
38048 * @param {number} [n=1] The number of times to repeat the string.
38049 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
38050 * @returns {string} Returns the repeated string.
38051 * @example
38052 *
38053 * _.repeat('*', 3);
38054 * // => '***'
38055 *
38056 * _.repeat('abc', 2);
38057 * // => 'abcabc'
38058 *
38059 * _.repeat('abc', 0);
38060 * // => ''
38061 */
38062 function repeat(string, n, guard) {
38063 if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) {
38064 n = 1;
38065 } else {
38066 n = toInteger(n);
38067 }
38068 return baseRepeat(toString(string), n);
38069 }
38070
38071 /**
38072 * Replaces matches for `pattern` in `string` with `replacement`.
38073 *
38074 * **Note:** This method is based on
38075 * [`String#replace`](https://mdn.io/String/replace).
38076 *
38077 * @static
38078 * @memberOf _
38079 * @since 4.0.0
38080 * @category String
38081 * @param {string} [string=''] The string to modify.
38082 * @param {RegExp|string} pattern The pattern to replace.
38083 * @param {Function|string} replacement The match replacement.
38084 * @returns {string} Returns the modified string.
38085 * @example
38086 *
38087 * _.replace('Hi Fred', 'Fred', 'Barney');
38088 * // => 'Hi Barney'
38089 */
38090 function replace() {
38091 var args = arguments,
38092 string = toString(args[0]);
38093
38094 return args.length < 3 ? string : string.replace(args[1], args[2]);
38095 }
38096
38097 /**
38098 * Converts `string` to
38099 * [snake case](https://en.wikipedia.org/wiki/Snake_case).
38100 *
38101 * @static
38102 * @memberOf _
38103 * @since 3.0.0
38104 * @category String
38105 * @param {string} [string=''] The string to convert.
38106 * @returns {string} Returns the snake cased string.
38107 * @example
38108 *
38109 * _.snakeCase('Foo Bar');
38110 * // => 'foo_bar'
38111 *
38112 * _.snakeCase('fooBar');
38113 * // => 'foo_bar'
38114 *
38115 * _.snakeCase('--FOO-BAR--');
38116 * // => 'foo_bar'
38117 */
38118 var snakeCase = createCompounder(function(result, word, index) {
38119 return result + (index ? '_' : '') + word.toLowerCase();
38120 });
38121
38122 /**
38123 * Splits `string` by `separator`.
38124 *
38125 * **Note:** This method is based on
38126 * [`String#split`](https://mdn.io/String/split).
38127 *
38128 * @static
38129 * @memberOf _
38130 * @since 4.0.0
38131 * @category String
38132 * @param {string} [string=''] The string to split.
38133 * @param {RegExp|string} separator The separator pattern to split by.
38134 * @param {number} [limit] The length to truncate results to.
38135 * @returns {Array} Returns the string segments.
38136 * @example
38137 *
38138 * _.split('a-b-c', '-', 2);
38139 * // => ['a', 'b']
38140 */
38141 function split(string, separator, limit) {
38142 if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) {
38143 separator = limit = undefined;
38144 }
38145 limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0;
38146 if (!limit) {
38147 return [];
38148 }
38149 string = toString(string);
38150 if (string && (
38151 typeof separator == 'string' ||
38152 (separator != null && !isRegExp(separator))
38153 )) {
38154 separator = baseToString(separator);
38155 if (!separator && hasUnicode(string)) {
38156 return castSlice(stringToArray(string), 0, limit);
38157 }
38158 }
38159 return string.split(separator, limit);
38160 }
38161
38162 /**
38163 * Converts `string` to
38164 * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
38165 *
38166 * @static
38167 * @memberOf _
38168 * @since 3.1.0
38169 * @category String
38170 * @param {string} [string=''] The string to convert.
38171 * @returns {string} Returns the start cased string.
38172 * @example
38173 *
38174 * _.startCase('--foo-bar--');
38175 * // => 'Foo Bar'
38176 *
38177 * _.startCase('fooBar');
38178 * // => 'Foo Bar'
38179 *
38180 * _.startCase('__FOO_BAR__');
38181 * // => 'FOO BAR'
38182 */
38183 var startCase = createCompounder(function(result, word, index) {
38184 return result + (index ? ' ' : '') + upperFirst(word);
38185 });
38186
38187 /**
38188 * Checks if `string` starts with the given target string.
38189 *
38190 * @static
38191 * @memberOf _
38192 * @since 3.0.0
38193 * @category String
38194 * @param {string} [string=''] The string to inspect.
38195 * @param {string} [target] The string to search for.
38196 * @param {number} [position=0] The position to search from.
38197 * @returns {boolean} Returns `true` if `string` starts with `target`,
38198 * else `false`.
38199 * @example
38200 *
38201 * _.startsWith('abc', 'a');
38202 * // => true
38203 *
38204 * _.startsWith('abc', 'b');
38205 * // => false
38206 *
38207 * _.startsWith('abc', 'b', 1);
38208 * // => true
38209 */
38210 function startsWith(string, target, position) {
38211 string = toString(string);
38212 position = baseClamp(toInteger(position), 0, string.length);
38213 target = baseToString(target);
38214 return string.slice(position, position + target.length) == target;
38215 }
38216
38217 /**
38218 * Creates a compiled template function that can interpolate data properties
38219 * in "interpolate" delimiters, HTML-escape interpolated data properties in
38220 * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
38221 * properties may be accessed as free variables in the template. If a setting
38222 * object is given, it takes precedence over `_.templateSettings` values.
38223 *
38224 * **Note:** In the development build `_.template` utilizes
38225 * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
38226 * for easier debugging.
38227 *
38228 * For more information on precompiling templates see
38229 * [lodash's custom builds documentation](https://lodash.com/custom-builds).
38230 *
38231 * For more information on Chrome extension sandboxes see
38232 * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
38233 *
38234 * @static
38235 * @since 0.1.0
38236 * @memberOf _
38237 * @category String
38238 * @param {string} [string=''] The template string.
38239 * @param {Object} [options={}] The options object.
38240 * @param {RegExp} [options.escape=_.templateSettings.escape]
38241 * The HTML "escape" delimiter.
38242 * @param {RegExp} [options.evaluate=_.templateSettings.evaluate]
38243 * The "evaluate" delimiter.
38244 * @param {Object} [options.imports=_.templateSettings.imports]
38245 * An object to import into the template as free variables.
38246 * @param {RegExp} [options.interpolate=_.templateSettings.interpolate]
38247 * The "interpolate" delimiter.
38248 * @param {string} [options.sourceURL='lodash.templateSources[n]']
38249 * The sourceURL of the compiled template.
38250 * @param {string} [options.variable='obj']
38251 * The data object variable name.
38252 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
38253 * @returns {Function} Returns the compiled template function.
38254 * @example
38255 *
38256 * // Use the "interpolate" delimiter to create a compiled template.
38257 * var compiled = _.template('hello <%= user %>!');
38258 * compiled({ 'user': 'fred' });
38259 * // => 'hello fred!'
38260 *
38261 * // Use the HTML "escape" delimiter to escape data property values.
38262 * var compiled = _.template('<b><%- value %></b>');
38263 * compiled({ 'value': '<script>' });
38264 * // => '<b>&lt;script&gt;</b>'
38265 *
38266 * // Use the "evaluate" delimiter to execute JavaScript and generate HTML.
38267 * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
38268 * compiled({ 'users': ['fred', 'barney'] });
38269 * // => '<li>fred</li><li>barney</li>'
38270 *
38271 * // Use the internal `print` function in "evaluate" delimiters.
38272 * var compiled = _.template('<% print("hello " + user); %>!');
38273 * compiled({ 'user': 'barney' });
38274 * // => 'hello barney!'
38275 *
38276 * // Use the ES template literal delimiter as an "interpolate" delimiter.
38277 * // Disable support by replacing the "interpolate" delimiter.
38278 * var compiled = _.template('hello ${ user }!');
38279 * compiled({ 'user': 'pebbles' });
38280 * // => 'hello pebbles!'
38281 *
38282 * // Use backslashes to treat delimiters as plain text.
38283 * var compiled = _.template('<%= "\\<%- value %\\>" %>');
38284 * compiled({ 'value': 'ignored' });
38285 * // => '<%- value %>'
38286 *
38287 * // Use the `imports` option to import `jQuery` as `jq`.
38288 * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
38289 * var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
38290 * compiled({ 'users': ['fred', 'barney'] });
38291 * // => '<li>fred</li><li>barney</li>'
38292 *
38293 * // Use the `sourceURL` option to specify a custom sourceURL for the template.
38294 * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
38295 * compiled(data);
38296 * // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector.
38297 *
38298 * // Use the `variable` option to ensure a with-statement isn't used in the compiled template.
38299 * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
38300 * compiled.source;
38301 * // => function(data) {
38302 * // var __t, __p = '';
38303 * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
38304 * // return __p;
38305 * // }
38306 *
38307 * // Use custom template delimiters.
38308 * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
38309 * var compiled = _.template('hello {{ user }}!');
38310 * compiled({ 'user': 'mustache' });
38311 * // => 'hello mustache!'
38312 *
38313 * // Use the `source` property to inline compiled templates for meaningful
38314 * // line numbers in error messages and stack traces.
38315 * fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\
38316 * var JST = {\
38317 * "main": ' + _.template(mainText).source + '\
38318 * };\
38319 * ');
38320 */
38321 function template(string, options, guard) {
38322 // Based on John Resig's `tmpl` implementation
38323 // (http://ejohn.org/blog/javascript-micro-templating/)
38324 // and Laura Doktorova's doT.js (https://github.com/olado/doT).
38325 var settings = lodash.templateSettings;
38326
38327 if (guard && isIterateeCall(string, options, guard)) {
38328 options = undefined;
38329 }
38330 string = toString(string);
38331 options = assignInWith({}, options, settings, assignInDefaults);
38332
38333 var imports = assignInWith({}, options.imports, settings.imports, assignInDefaults),
38334 importsKeys = keys(imports),
38335 importsValues = baseValues(imports, importsKeys);
38336
38337 var isEscaping,
38338 isEvaluating,
38339 index = 0,
38340 interpolate = options.interpolate || reNoMatch,
38341 source = "__p += '";
38342
38343 // Compile the regexp to match each delimiter.
38344 var reDelimiters = RegExp(
38345 (options.escape || reNoMatch).source + '|' +
38346 interpolate.source + '|' +
38347 (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
38348 (options.evaluate || reNoMatch).source + '|$'
38349 , 'g');
38350
38351 // Use a sourceURL for easier debugging.
38352 var sourceURL = '//# sourceURL=' +
38353 ('sourceURL' in options
38354 ? options.sourceURL
38355 : ('lodash.templateSources[' + (++templateCounter) + ']')
38356 ) + '\n';
38357
38358 string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
38359 interpolateValue || (interpolateValue = esTemplateValue);
38360
38361 // Escape characters that can't be included in string literals.
38362 source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
38363
38364 // Replace delimiters with snippets.
38365 if (escapeValue) {
38366 isEscaping = true;
38367 source += "' +\n__e(" + escapeValue + ") +\n'";
38368 }
38369 if (evaluateValue) {
38370 isEvaluating = true;
38371 source += "';\n" + evaluateValue + ";\n__p += '";
38372 }
38373 if (interpolateValue) {
38374 source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
38375 }
38376 index = offset + match.length;
38377
38378 // The JS engine embedded in Adobe products needs `match` returned in
38379 // order to produce the correct `offset` value.
38380 return match;
38381 });
38382
38383 source += "';\n";
38384
38385 // If `variable` is not specified wrap a with-statement around the generated
38386 // code to add the data object to the top of the scope chain.
38387 var variable = options.variable;
38388 if (!variable) {
38389 source = 'with (obj) {\n' + source + '\n}\n';
38390 }
38391 // Cleanup code by stripping empty strings.
38392 source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
38393 .replace(reEmptyStringMiddle, '$1')
38394 .replace(reEmptyStringTrailing, '$1;');
38395
38396 // Frame code as the function body.
38397 source = 'function(' + (variable || 'obj') + ') {\n' +
38398 (variable
38399 ? ''
38400 : 'obj || (obj = {});\n'
38401 ) +
38402 "var __t, __p = ''" +
38403 (isEscaping
38404 ? ', __e = _.escape'
38405 : ''
38406 ) +
38407 (isEvaluating
38408 ? ', __j = Array.prototype.join;\n' +
38409 "function print() { __p += __j.call(arguments, '') }\n"
38410 : ';\n'
38411 ) +
38412 source +
38413 'return __p\n}';
38414
38415 var result = attempt(function() {
38416 return Function(importsKeys, sourceURL + 'return ' + source)
38417 .apply(undefined, importsValues);
38418 });
38419
38420 // Provide the compiled function's source by its `toString` method or
38421 // the `source` property as a convenience for inlining compiled templates.
38422 result.source = source;
38423 if (isError(result)) {
38424 throw result;
38425 }
38426 return result;
38427 }
38428
38429 /**
38430 * Converts `string`, as a whole, to lower case just like
38431 * [String#toLowerCase](https://mdn.io/toLowerCase).
38432 *
38433 * @static
38434 * @memberOf _
38435 * @since 4.0.0
38436 * @category String
38437 * @param {string} [string=''] The string to convert.
38438 * @returns {string} Returns the lower cased string.
38439 * @example
38440 *
38441 * _.toLower('--Foo-Bar--');
38442 * // => '--foo-bar--'
38443 *
38444 * _.toLower('fooBar');
38445 * // => 'foobar'
38446 *
38447 * _.toLower('__FOO_BAR__');
38448 * // => '__foo_bar__'
38449 */
38450 function toLower(value) {
38451 return toString(value).toLowerCase();
38452 }
38453
38454 /**
38455 * Converts `string`, as a whole, to upper case just like
38456 * [String#toUpperCase](https://mdn.io/toUpperCase).
38457 *
38458 * @static
38459 * @memberOf _
38460 * @since 4.0.0
38461 * @category String
38462 * @param {string} [string=''] The string to convert.
38463 * @returns {string} Returns the upper cased string.
38464 * @example
38465 *
38466 * _.toUpper('--foo-bar--');
38467 * // => '--FOO-BAR--'
38468 *
38469 * _.toUpper('fooBar');
38470 * // => 'FOOBAR'
38471 *
38472 * _.toUpper('__foo_bar__');
38473 * // => '__FOO_BAR__'
38474 */
38475 function toUpper(value) {
38476 return toString(value).toUpperCase();
38477 }
38478
38479 /**
38480 * Removes leading and trailing whitespace or specified characters from `string`.
38481 *
38482 * @static
38483 * @memberOf _
38484 * @since 3.0.0
38485 * @category String
38486 * @param {string} [string=''] The string to trim.
38487 * @param {string} [chars=whitespace] The characters to trim.
38488 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
38489 * @returns {string} Returns the trimmed string.
38490 * @example
38491 *
38492 * _.trim(' abc ');
38493 * // => 'abc'
38494 *
38495 * _.trim('-_-abc-_-', '_-');
38496 * // => 'abc'
38497 *
38498 * _.map([' foo ', ' bar '], _.trim);
38499 * // => ['foo', 'bar']
38500 */
38501 function trim(string, chars, guard) {
38502 string = toString(string);
38503 if (string && (guard || chars === undefined)) {
38504 return string.replace(reTrim, '');
38505 }
38506 if (!string || !(chars = baseToString(chars))) {
38507 return string;
38508 }
38509 var strSymbols = stringToArray(string),
38510 chrSymbols = stringToArray(chars),
38511 start = charsStartIndex(strSymbols, chrSymbols),
38512 end = charsEndIndex(strSymbols, chrSymbols) + 1;
38513
38514 return castSlice(strSymbols, start, end).join('');
38515 }
38516
38517 /**
38518 * Removes trailing whitespace or specified characters from `string`.
38519 *
38520 * @static
38521 * @memberOf _
38522 * @since 4.0.0
38523 * @category String
38524 * @param {string} [string=''] The string to trim.
38525 * @param {string} [chars=whitespace] The characters to trim.
38526 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
38527 * @returns {string} Returns the trimmed string.
38528 * @example
38529 *
38530 * _.trimEnd(' abc ');
38531 * // => ' abc'
38532 *
38533 * _.trimEnd('-_-abc-_-', '_-');
38534 * // => '-_-abc'
38535 */
38536 function trimEnd(string, chars, guard) {
38537 string = toString(string);
38538 if (string && (guard || chars === undefined)) {
38539 return string.replace(reTrimEnd, '');
38540 }
38541 if (!string || !(chars = baseToString(chars))) {
38542 return string;
38543 }
38544 var strSymbols = stringToArray(string),
38545 end = charsEndIndex(strSymbols, stringToArray(chars)) + 1;
38546
38547 return castSlice(strSymbols, 0, end).join('');
38548 }
38549
38550 /**
38551 * Removes leading whitespace or specified characters from `string`.
38552 *
38553 * @static
38554 * @memberOf _
38555 * @since 4.0.0
38556 * @category String
38557 * @param {string} [string=''] The string to trim.
38558 * @param {string} [chars=whitespace] The characters to trim.
38559 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
38560 * @returns {string} Returns the trimmed string.
38561 * @example
38562 *
38563 * _.trimStart(' abc ');
38564 * // => 'abc '
38565 *
38566 * _.trimStart('-_-abc-_-', '_-');
38567 * // => 'abc-_-'
38568 */
38569 function trimStart(string, chars, guard) {
38570 string = toString(string);
38571 if (string && (guard || chars === undefined)) {
38572 return string.replace(reTrimStart, '');
38573 }
38574 if (!string || !(chars = baseToString(chars))) {
38575 return string;
38576 }
38577 var strSymbols = stringToArray(string),
38578 start = charsStartIndex(strSymbols, stringToArray(chars));
38579
38580 return castSlice(strSymbols, start).join('');
38581 }
38582
38583 /**
38584 * Truncates `string` if it's longer than the given maximum string length.
38585 * The last characters of the truncated string are replaced with the omission
38586 * string which defaults to "...".
38587 *
38588 * @static
38589 * @memberOf _
38590 * @since 4.0.0
38591 * @category String
38592 * @param {string} [string=''] The string to truncate.
38593 * @param {Object} [options={}] The options object.
38594 * @param {number} [options.length=30] The maximum string length.
38595 * @param {string} [options.omission='...'] The string to indicate text is omitted.
38596 * @param {RegExp|string} [options.separator] The separator pattern to truncate to.
38597 * @returns {string} Returns the truncated string.
38598 * @example
38599 *
38600 * _.truncate('hi-diddly-ho there, neighborino');
38601 * // => 'hi-diddly-ho there, neighbo...'
38602 *
38603 * _.truncate('hi-diddly-ho there, neighborino', {
38604 * 'length': 24,
38605 * 'separator': ' '
38606 * });
38607 * // => 'hi-diddly-ho there,...'
38608 *
38609 * _.truncate('hi-diddly-ho there, neighborino', {
38610 * 'length': 24,
38611 * 'separator': /,? +/
38612 * });
38613 * // => 'hi-diddly-ho there...'
38614 *
38615 * _.truncate('hi-diddly-ho there, neighborino', {
38616 * 'omission': ' [...]'
38617 * });
38618 * // => 'hi-diddly-ho there, neig [...]'
38619 */
38620 function truncate(string, options) {
38621 var length = DEFAULT_TRUNC_LENGTH,
38622 omission = DEFAULT_TRUNC_OMISSION;
38623
38624 if (isObject(options)) {
38625 var separator = 'separator' in options ? options.separator : separator;
38626 length = 'length' in options ? toInteger(options.length) : length;
38627 omission = 'omission' in options ? baseToString(options.omission) : omission;
38628 }
38629 string = toString(string);
38630
38631 var strLength = string.length;
38632 if (hasUnicode(string)) {
38633 var strSymbols = stringToArray(string);
38634 strLength = strSymbols.length;
38635 }
38636 if (length >= strLength) {
38637 return string;
38638 }
38639 var end = length - stringSize(omission);
38640 if (end < 1) {
38641 return omission;
38642 }
38643 var result = strSymbols
38644 ? castSlice(strSymbols, 0, end).join('')
38645 : string.slice(0, end);
38646
38647 if (separator === undefined) {
38648 return result + omission;
38649 }
38650 if (strSymbols) {
38651 end += (result.length - end);
38652 }
38653 if (isRegExp(separator)) {
38654 if (string.slice(end).search(separator)) {
38655 var match,
38656 substring = result;
38657
38658 if (!separator.global) {
38659 separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g');
38660 }
38661 separator.lastIndex = 0;
38662 while ((match = separator.exec(substring))) {
38663 var newEnd = match.index;
38664 }
38665 result = result.slice(0, newEnd === undefined ? end : newEnd);
38666 }
38667 } else if (string.indexOf(baseToString(separator), end) != end) {
38668 var index = result.lastIndexOf(separator);
38669 if (index > -1) {
38670 result = result.slice(0, index);
38671 }
38672 }
38673 return result + omission;
38674 }
38675
38676 /**
38677 * The inverse of `_.escape`; this method converts the HTML entities
38678 * `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `string` to
38679 * their corresponding characters.
38680 *
38681 * **Note:** No other HTML entities are unescaped. To unescape additional
38682 * HTML entities use a third-party library like [_he_](https://mths.be/he).
38683 *
38684 * @static
38685 * @memberOf _
38686 * @since 0.6.0
38687 * @category String
38688 * @param {string} [string=''] The string to unescape.
38689 * @returns {string} Returns the unescaped string.
38690 * @example
38691 *
38692 * _.unescape('fred, barney, &amp; pebbles');
38693 * // => 'fred, barney, & pebbles'
38694 */
38695 function unescape(string) {
38696 string = toString(string);
38697 return (string && reHasEscapedHtml.test(string))
38698 ? string.replace(reEscapedHtml, unescapeHtmlChar)
38699 : string;
38700 }
38701
38702 /**
38703 * Converts `string`, as space separated words, to upper case.
38704 *
38705 * @static
38706 * @memberOf _
38707 * @since 4.0.0
38708 * @category String
38709 * @param {string} [string=''] The string to convert.
38710 * @returns {string} Returns the upper cased string.
38711 * @example
38712 *
38713 * _.upperCase('--foo-bar');
38714 * // => 'FOO BAR'
38715 *
38716 * _.upperCase('fooBar');
38717 * // => 'FOO BAR'
38718 *
38719 * _.upperCase('__foo_bar__');
38720 * // => 'FOO BAR'
38721 */
38722 var upperCase = createCompounder(function(result, word, index) {
38723 return result + (index ? ' ' : '') + word.toUpperCase();
38724 });
38725
38726 /**
38727 * Converts the first character of `string` to upper case.
38728 *
38729 * @static
38730 * @memberOf _
38731 * @since 4.0.0
38732 * @category String
38733 * @param {string} [string=''] The string to convert.
38734 * @returns {string} Returns the converted string.
38735 * @example
38736 *
38737 * _.upperFirst('fred');
38738 * // => 'Fred'
38739 *
38740 * _.upperFirst('FRED');
38741 * // => 'FRED'
38742 */
38743 var upperFirst = createCaseFirst('toUpperCase');
38744
38745 /**
38746 * Splits `string` into an array of its words.
38747 *
38748 * @static
38749 * @memberOf _
38750 * @since 3.0.0
38751 * @category String
38752 * @param {string} [string=''] The string to inspect.
38753 * @param {RegExp|string} [pattern] The pattern to match words.
38754 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
38755 * @returns {Array} Returns the words of `string`.
38756 * @example
38757 *
38758 * _.words('fred, barney, & pebbles');
38759 * // => ['fred', 'barney', 'pebbles']
38760 *
38761 * _.words('fred, barney, & pebbles', /[^, ]+/g);
38762 * // => ['fred', 'barney', '&', 'pebbles']
38763 */
38764 function words(string, pattern, guard) {
38765 string = toString(string);
38766 pattern = guard ? undefined : pattern;
38767
38768 if (pattern === undefined) {
38769 return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
38770 }
38771 return string.match(pattern) || [];
38772 }
38773
38774 /*------------------------------------------------------------------------*/
38775
38776 /**
38777 * Attempts to invoke `func`, returning either the result or the caught error
38778 * object. Any additional arguments are provided to `func` when it's invoked.
38779 *
38780 * @static
38781 * @memberOf _
38782 * @since 3.0.0
38783 * @category Util
38784 * @param {Function} func The function to attempt.
38785 * @param {...*} [args] The arguments to invoke `func` with.
38786 * @returns {*} Returns the `func` result or error object.
38787 * @example
38788 *
38789 * // Avoid throwing errors for invalid selectors.
38790 * var elements = _.attempt(function(selector) {
38791 * return document.querySelectorAll(selector);
38792 * }, '>_>');
38793 *
38794 * if (_.isError(elements)) {
38795 * elements = [];
38796 * }
38797 */
38798 var attempt = baseRest(function(func, args) {
38799 try {
38800 return apply(func, undefined, args);
38801 } catch (e) {
38802 return isError(e) ? e : new Error(e);
38803 }
38804 });
38805
38806 /**
38807 * Binds methods of an object to the object itself, overwriting the existing
38808 * method.
38809 *
38810 * **Note:** This method doesn't set the "length" property of bound functions.
38811 *
38812 * @static
38813 * @since 0.1.0
38814 * @memberOf _
38815 * @category Util
38816 * @param {Object} object The object to bind and assign the bound methods to.
38817 * @param {...(string|string[])} methodNames The object method names to bind.
38818 * @returns {Object} Returns `object`.
38819 * @example
38820 *
38821 * var view = {
38822 * 'label': 'docs',
38823 * 'click': function() {
38824 * console.log('clicked ' + this.label);
38825 * }
38826 * };
38827 *
38828 * _.bindAll(view, ['click']);
38829 * jQuery(element).on('click', view.click);
38830 * // => Logs 'clicked docs' when clicked.
38831 */
38832 var bindAll = flatRest(function(object, methodNames) {
38833 arrayEach(methodNames, function(key) {
38834 key = toKey(key);
38835 baseAssignValue(object, key, bind(object[key], object));
38836 });
38837 return object;
38838 });
38839
38840 /**
38841 * Creates a function that iterates over `pairs` and invokes the corresponding
38842 * function of the first predicate to return truthy. The predicate-function
38843 * pairs are invoked with the `this` binding and arguments of the created
38844 * function.
38845 *
38846 * @static
38847 * @memberOf _
38848 * @since 4.0.0
38849 * @category Util
38850 * @param {Array} pairs The predicate-function pairs.
38851 * @returns {Function} Returns the new composite function.
38852 * @example
38853 *
38854 * var func = _.cond([
38855 * [_.matches({ 'a': 1 }), _.constant('matches A')],
38856 * [_.conforms({ 'b': _.isNumber }), _.constant('matches B')],
38857 * [_.stubTrue, _.constant('no match')]
38858 * ]);
38859 *
38860 * func({ 'a': 1, 'b': 2 });
38861 * // => 'matches A'
38862 *
38863 * func({ 'a': 0, 'b': 1 });
38864 * // => 'matches B'
38865 *
38866 * func({ 'a': '1', 'b': '2' });
38867 * // => 'no match'
38868 */
38869 function cond(pairs) {
38870 var length = pairs ? pairs.length : 0,
38871 toIteratee = getIteratee();
38872
38873 pairs = !length ? [] : arrayMap(pairs, function(pair) {
38874 if (typeof pair[1] != 'function') {
38875 throw new TypeError(FUNC_ERROR_TEXT);
38876 }
38877 return [toIteratee(pair[0]), pair[1]];
38878 });
38879
38880 return baseRest(function(args) {
38881 var index = -1;
38882 while (++index < length) {
38883 var pair = pairs[index];
38884 if (apply(pair[0], this, args)) {
38885 return apply(pair[1], this, args);
38886 }
38887 }
38888 });
38889 }
38890
38891 /**
38892 * Creates a function that invokes the predicate properties of `source` with
38893 * the corresponding property values of a given object, returning `true` if
38894 * all predicates return truthy, else `false`.
38895 *
38896 * **Note:** The created function is equivalent to `_.conformsTo` with
38897 * `source` partially applied.
38898 *
38899 * @static
38900 * @memberOf _
38901 * @since 4.0.0
38902 * @category Util
38903 * @param {Object} source The object of property predicates to conform to.
38904 * @returns {Function} Returns the new spec function.
38905 * @example
38906 *
38907 * var objects = [
38908 * { 'a': 2, 'b': 1 },
38909 * { 'a': 1, 'b': 2 }
38910 * ];
38911 *
38912 * _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } }));
38913 * // => [{ 'a': 1, 'b': 2 }]
38914 */
38915 function conforms(source) {
38916 return baseConforms(baseClone(source, true));
38917 }
38918
38919 /**
38920 * Creates a function that returns `value`.
38921 *
38922 * @static
38923 * @memberOf _
38924 * @since 2.4.0
38925 * @category Util
38926 * @param {*} value The value to return from the new function.
38927 * @returns {Function} Returns the new constant function.
38928 * @example
38929 *
38930 * var objects = _.times(2, _.constant({ 'a': 1 }));
38931 *
38932 * console.log(objects);
38933 * // => [{ 'a': 1 }, { 'a': 1 }]
38934 *
38935 * console.log(objects[0] === objects[1]);
38936 * // => true
38937 */
38938 function constant(value) {
38939 return function() {
38940 return value;
38941 };
38942 }
38943
38944 /**
38945 * Checks `value` to determine whether a default value should be returned in
38946 * its place. The `defaultValue` is returned if `value` is `NaN`, `null`,
38947 * or `undefined`.
38948 *
38949 * @static
38950 * @memberOf _
38951 * @since 4.14.0
38952 * @category Util
38953 * @param {*} value The value to check.
38954 * @param {*} defaultValue The default value.
38955 * @returns {*} Returns the resolved value.
38956 * @example
38957 *
38958 * _.defaultTo(1, 10);
38959 * // => 1
38960 *
38961 * _.defaultTo(undefined, 10);
38962 * // => 10
38963 */
38964 function defaultTo(value, defaultValue) {
38965 return (value == null || value !== value) ? defaultValue : value;
38966 }
38967
38968 /**
38969 * Creates a function that returns the result of invoking the given functions
38970 * with the `this` binding of the created function, where each successive
38971 * invocation is supplied the return value of the previous.
38972 *
38973 * @static
38974 * @memberOf _
38975 * @since 3.0.0
38976 * @category Util
38977 * @param {...(Function|Function[])} [funcs] The functions to invoke.
38978 * @returns {Function} Returns the new composite function.
38979 * @see _.flowRight
38980 * @example
38981 *
38982 * function square(n) {
38983 * return n * n;
38984 * }
38985 *
38986 * var addSquare = _.flow([_.add, square]);
38987 * addSquare(1, 2);
38988 * // => 9
38989 */
38990 var flow = createFlow();
38991
38992 /**
38993 * This method is like `_.flow` except that it creates a function that
38994 * invokes the given functions from right to left.
38995 *
38996 * @static
38997 * @since 3.0.0
38998 * @memberOf _
38999 * @category Util
39000 * @param {...(Function|Function[])} [funcs] The functions to invoke.
39001 * @returns {Function} Returns the new composite function.
39002 * @see _.flow
39003 * @example
39004 *
39005 * function square(n) {
39006 * return n * n;
39007 * }
39008 *
39009 * var addSquare = _.flowRight([square, _.add]);
39010 * addSquare(1, 2);
39011 * // => 9
39012 */
39013 var flowRight = createFlow(true);
39014
39015 /**
39016 * This method returns the first argument it receives.
39017 *
39018 * @static
39019 * @since 0.1.0
39020 * @memberOf _
39021 * @category Util
39022 * @param {*} value Any value.
39023 * @returns {*} Returns `value`.
39024 * @example
39025 *
39026 * var object = { 'a': 1 };
39027 *
39028 * console.log(_.identity(object) === object);
39029 * // => true
39030 */
39031 function identity(value) {
39032 return value;
39033 }
39034
39035 /**
39036 * Creates a function that invokes `func` with the arguments of the created
39037 * function. If `func` is a property name, the created function returns the
39038 * property value for a given element. If `func` is an array or object, the
39039 * created function returns `true` for elements that contain the equivalent
39040 * source properties, otherwise it returns `false`.
39041 *
39042 * @static
39043 * @since 4.0.0
39044 * @memberOf _
39045 * @category Util
39046 * @param {*} [func=_.identity] The value to convert to a callback.
39047 * @returns {Function} Returns the callback.
39048 * @example
39049 *
39050 * var users = [
39051 * { 'user': 'barney', 'age': 36, 'active': true },
39052 * { 'user': 'fred', 'age': 40, 'active': false }
39053 * ];
39054 *
39055 * // The `_.matches` iteratee shorthand.
39056 * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));
39057 * // => [{ 'user': 'barney', 'age': 36, 'active': true }]
39058 *
39059 * // The `_.matchesProperty` iteratee shorthand.
39060 * _.filter(users, _.iteratee(['user', 'fred']));
39061 * // => [{ 'user': 'fred', 'age': 40 }]
39062 *
39063 * // The `_.property` iteratee shorthand.
39064 * _.map(users, _.iteratee('user'));
39065 * // => ['barney', 'fred']
39066 *
39067 * // Create custom iteratee shorthands.
39068 * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {
39069 * return !_.isRegExp(func) ? iteratee(func) : function(string) {
39070 * return func.test(string);
39071 * };
39072 * });
39073 *
39074 * _.filter(['abc', 'def'], /ef/);
39075 * // => ['def']
39076 */
39077 function iteratee(func) {
39078 return baseIteratee(typeof func == 'function' ? func : baseClone(func, true));
39079 }
39080
39081 /**
39082 * Creates a function that performs a partial deep comparison between a given
39083 * object and `source`, returning `true` if the given object has equivalent
39084 * property values, else `false`.
39085 *
39086 * **Note:** The created function is equivalent to `_.isMatch` with `source`
39087 * partially applied.
39088 *
39089 * Partial comparisons will match empty array and empty object `source`
39090 * values against any array or object value, respectively. See `_.isEqual`
39091 * for a list of supported value comparisons.
39092 *
39093 * @static
39094 * @memberOf _
39095 * @since 3.0.0
39096 * @category Util
39097 * @param {Object} source The object of property values to match.
39098 * @returns {Function} Returns the new spec function.
39099 * @example
39100 *
39101 * var objects = [
39102 * { 'a': 1, 'b': 2, 'c': 3 },
39103 * { 'a': 4, 'b': 5, 'c': 6 }
39104 * ];
39105 *
39106 * _.filter(objects, _.matches({ 'a': 4, 'c': 6 }));
39107 * // => [{ 'a': 4, 'b': 5, 'c': 6 }]
39108 */
39109 function matches(source) {
39110 return baseMatches(baseClone(source, true));
39111 }
39112
39113 /**
39114 * Creates a function that performs a partial deep comparison between the
39115 * value at `path` of a given object to `srcValue`, returning `true` if the
39116 * object value is equivalent, else `false`.
39117 *
39118 * **Note:** Partial comparisons will match empty array and empty object
39119 * `srcValue` values against any array or object value, respectively. See
39120 * `_.isEqual` for a list of supported value comparisons.
39121 *
39122 * @static
39123 * @memberOf _
39124 * @since 3.2.0
39125 * @category Util
39126 * @param {Array|string} path The path of the property to get.
39127 * @param {*} srcValue The value to match.
39128 * @returns {Function} Returns the new spec function.
39129 * @example
39130 *
39131 * var objects = [
39132 * { 'a': 1, 'b': 2, 'c': 3 },
39133 * { 'a': 4, 'b': 5, 'c': 6 }
39134 * ];
39135 *
39136 * _.find(objects, _.matchesProperty('a', 4));
39137 * // => { 'a': 4, 'b': 5, 'c': 6 }
39138 */
39139 function matchesProperty(path, srcValue) {
39140 return baseMatchesProperty(path, baseClone(srcValue, true));
39141 }
39142
39143 /**
39144 * Creates a function that invokes the method at `path` of a given object.
39145 * Any additional arguments are provided to the invoked method.
39146 *
39147 * @static
39148 * @memberOf _
39149 * @since 3.7.0
39150 * @category Util
39151 * @param {Array|string} path The path of the method to invoke.
39152 * @param {...*} [args] The arguments to invoke the method with.
39153 * @returns {Function} Returns the new invoker function.
39154 * @example
39155 *
39156 * var objects = [
39157 * { 'a': { 'b': _.constant(2) } },
39158 * { 'a': { 'b': _.constant(1) } }
39159 * ];
39160 *
39161 * _.map(objects, _.method('a.b'));
39162 * // => [2, 1]
39163 *
39164 * _.map(objects, _.method(['a', 'b']));
39165 * // => [2, 1]
39166 */
39167 var method = baseRest(function(path, args) {
39168 return function(object) {
39169 return baseInvoke(object, path, args);
39170 };
39171 });
39172
39173 /**
39174 * The opposite of `_.method`; this method creates a function that invokes
39175 * the method at a given path of `object`. Any additional arguments are
39176 * provided to the invoked method.
39177 *
39178 * @static
39179 * @memberOf _
39180 * @since 3.7.0
39181 * @category Util
39182 * @param {Object} object The object to query.
39183 * @param {...*} [args] The arguments to invoke the method with.
39184 * @returns {Function} Returns the new invoker function.
39185 * @example
39186 *
39187 * var array = _.times(3, _.constant),
39188 * object = { 'a': array, 'b': array, 'c': array };
39189 *
39190 * _.map(['a[2]', 'c[0]'], _.methodOf(object));
39191 * // => [2, 0]
39192 *
39193 * _.map([['a', '2'], ['c', '0']], _.methodOf(object));
39194 * // => [2, 0]
39195 */
39196 var methodOf = baseRest(function(object, args) {
39197 return function(path) {
39198 return baseInvoke(object, path, args);
39199 };
39200 });
39201
39202 /**
39203 * Adds all own enumerable string keyed function properties of a source
39204 * object to the destination object. If `object` is a function, then methods
39205 * are added to its prototype as well.
39206 *
39207 * **Note:** Use `_.runInContext` to create a pristine `lodash` function to
39208 * avoid conflicts caused by modifying the original.
39209 *
39210 * @static
39211 * @since 0.1.0
39212 * @memberOf _
39213 * @category Util
39214 * @param {Function|Object} [object=lodash] The destination object.
39215 * @param {Object} source The object of functions to add.
39216 * @param {Object} [options={}] The options object.
39217 * @param {boolean} [options.chain=true] Specify whether mixins are chainable.
39218 * @returns {Function|Object} Returns `object`.
39219 * @example
39220 *
39221 * function vowels(string) {
39222 * return _.filter(string, function(v) {
39223 * return /[aeiou]/i.test(v);
39224 * });
39225 * }
39226 *
39227 * _.mixin({ 'vowels': vowels });
39228 * _.vowels('fred');
39229 * // => ['e']
39230 *
39231 * _('fred').vowels().value();
39232 * // => ['e']
39233 *
39234 * _.mixin({ 'vowels': vowels }, { 'chain': false });
39235 * _('fred').vowels();
39236 * // => ['e']
39237 */
39238 function mixin(object, source, options) {
39239 var props = keys(source),
39240 methodNames = baseFunctions(source, props);
39241
39242 if (options == null &&
39243 !(isObject(source) && (methodNames.length || !props.length))) {
39244 options = source;
39245 source = object;
39246 object = this;
39247 methodNames = baseFunctions(source, keys(source));
39248 }
39249 var chain = !(isObject(options) && 'chain' in options) || !!options.chain,
39250 isFunc = isFunction(object);
39251
39252 arrayEach(methodNames, function(methodName) {
39253 var func = source[methodName];
39254 object[methodName] = func;
39255 if (isFunc) {
39256 object.prototype[methodName] = function() {
39257 var chainAll = this.__chain__;
39258 if (chain || chainAll) {
39259 var result = object(this.__wrapped__),
39260 actions = result.__actions__ = copyArray(this.__actions__);
39261
39262 actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
39263 result.__chain__ = chainAll;
39264 return result;
39265 }
39266 return func.apply(object, arrayPush([this.value()], arguments));
39267 };
39268 }
39269 });
39270
39271 return object;
39272 }
39273
39274 /**
39275 * Reverts the `_` variable to its previous value and returns a reference to
39276 * the `lodash` function.
39277 *
39278 * @static
39279 * @since 0.1.0
39280 * @memberOf _
39281 * @category Util
39282 * @returns {Function} Returns the `lodash` function.
39283 * @example
39284 *
39285 * var lodash = _.noConflict();
39286 */
39287 function noConflict() {
39288 if (root._ === this) {
39289 root._ = oldDash;
39290 }
39291 return this;
39292 }
39293
39294 /**
39295 * This method returns `undefined`.
39296 *
39297 * @static
39298 * @memberOf _
39299 * @since 2.3.0
39300 * @category Util
39301 * @example
39302 *
39303 * _.times(2, _.noop);
39304 * // => [undefined, undefined]
39305 */
39306 function noop() {
39307 // No operation performed.
39308 }
39309
39310 /**
39311 * Creates a function that gets the argument at index `n`. If `n` is negative,
39312 * the nth argument from the end is returned.
39313 *
39314 * @static
39315 * @memberOf _
39316 * @since 4.0.0
39317 * @category Util
39318 * @param {number} [n=0] The index of the argument to return.
39319 * @returns {Function} Returns the new pass-thru function.
39320 * @example
39321 *
39322 * var func = _.nthArg(1);
39323 * func('a', 'b', 'c', 'd');
39324 * // => 'b'
39325 *
39326 * var func = _.nthArg(-2);
39327 * func('a', 'b', 'c', 'd');
39328 * // => 'c'
39329 */
39330 function nthArg(n) {
39331 n = toInteger(n);
39332 return baseRest(function(args) {
39333 return baseNth(args, n);
39334 });
39335 }
39336
39337 /**
39338 * Creates a function that invokes `iteratees` with the arguments it receives
39339 * and returns their results.
39340 *
39341 * @static
39342 * @memberOf _
39343 * @since 4.0.0
39344 * @category Util
39345 * @param {...(Function|Function[])} [iteratees=[_.identity]]
39346 * The iteratees to invoke.
39347 * @returns {Function} Returns the new function.
39348 * @example
39349 *
39350 * var func = _.over([Math.max, Math.min]);
39351 *
39352 * func(1, 2, 3, 4);
39353 * // => [4, 1]
39354 */
39355 var over = createOver(arrayMap);
39356
39357 /**
39358 * Creates a function that checks if **all** of the `predicates` return
39359 * truthy when invoked with the arguments it receives.
39360 *
39361 * @static
39362 * @memberOf _
39363 * @since 4.0.0
39364 * @category Util
39365 * @param {...(Function|Function[])} [predicates=[_.identity]]
39366 * The predicates to check.
39367 * @returns {Function} Returns the new function.
39368 * @example
39369 *
39370 * var func = _.overEvery([Boolean, isFinite]);
39371 *
39372 * func('1');
39373 * // => true
39374 *
39375 * func(null);
39376 * // => false
39377 *
39378 * func(NaN);
39379 * // => false
39380 */
39381 var overEvery = createOver(arrayEvery);
39382
39383 /**
39384 * Creates a function that checks if **any** of the `predicates` return
39385 * truthy when invoked with the arguments it receives.
39386 *
39387 * @static
39388 * @memberOf _
39389 * @since 4.0.0
39390 * @category Util
39391 * @param {...(Function|Function[])} [predicates=[_.identity]]
39392 * The predicates to check.
39393 * @returns {Function} Returns the new function.
39394 * @example
39395 *
39396 * var func = _.overSome([Boolean, isFinite]);
39397 *
39398 * func('1');
39399 * // => true
39400 *
39401 * func(null);
39402 * // => true
39403 *
39404 * func(NaN);
39405 * // => false
39406 */
39407 var overSome = createOver(arraySome);
39408
39409 /**
39410 * Creates a function that returns the value at `path` of a given object.
39411 *
39412 * @static
39413 * @memberOf _
39414 * @since 2.4.0
39415 * @category Util
39416 * @param {Array|string} path The path of the property to get.
39417 * @returns {Function} Returns the new accessor function.
39418 * @example
39419 *
39420 * var objects = [
39421 * { 'a': { 'b': 2 } },
39422 * { 'a': { 'b': 1 } }
39423 * ];
39424 *
39425 * _.map(objects, _.property('a.b'));
39426 * // => [2, 1]
39427 *
39428 * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
39429 * // => [1, 2]
39430 */
39431 function property(path) {
39432 return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
39433 }
39434
39435 /**
39436 * The opposite of `_.property`; this method creates a function that returns
39437 * the value at a given path of `object`.
39438 *
39439 * @static
39440 * @memberOf _
39441 * @since 3.0.0
39442 * @category Util
39443 * @param {Object} object The object to query.
39444 * @returns {Function} Returns the new accessor function.
39445 * @example
39446 *
39447 * var array = [0, 1, 2],
39448 * object = { 'a': array, 'b': array, 'c': array };
39449 *
39450 * _.map(['a[2]', 'c[0]'], _.propertyOf(object));
39451 * // => [2, 0]
39452 *
39453 * _.map([['a', '2'], ['c', '0']], _.propertyOf(object));
39454 * // => [2, 0]
39455 */
39456 function propertyOf(object) {
39457 return function(path) {
39458 return object == null ? undefined : baseGet(object, path);
39459 };
39460 }
39461
39462 /**
39463 * Creates an array of numbers (positive and/or negative) progressing from
39464 * `start` up to, but not including, `end`. A step of `-1` is used if a negative
39465 * `start` is specified without an `end` or `step`. If `end` is not specified,
39466 * it's set to `start` with `start` then set to `0`.
39467 *
39468 * **Note:** JavaScript follows the IEEE-754 standard for resolving
39469 * floating-point values which can produce unexpected results.
39470 *
39471 * @static
39472 * @since 0.1.0
39473 * @memberOf _
39474 * @category Util
39475 * @param {number} [start=0] The start of the range.
39476 * @param {number} end The end of the range.
39477 * @param {number} [step=1] The value to increment or decrement by.
39478 * @returns {Array} Returns the range of numbers.
39479 * @see _.inRange, _.rangeRight
39480 * @example
39481 *
39482 * _.range(4);
39483 * // => [0, 1, 2, 3]
39484 *
39485 * _.range(-4);
39486 * // => [0, -1, -2, -3]
39487 *
39488 * _.range(1, 5);
39489 * // => [1, 2, 3, 4]
39490 *
39491 * _.range(0, 20, 5);
39492 * // => [0, 5, 10, 15]
39493 *
39494 * _.range(0, -4, -1);
39495 * // => [0, -1, -2, -3]
39496 *
39497 * _.range(1, 4, 0);
39498 * // => [1, 1, 1]
39499 *
39500 * _.range(0);
39501 * // => []
39502 */
39503 var range = createRange();
39504
39505 /**
39506 * This method is like `_.range` except that it populates values in
39507 * descending order.
39508 *
39509 * @static
39510 * @memberOf _
39511 * @since 4.0.0
39512 * @category Util
39513 * @param {number} [start=0] The start of the range.
39514 * @param {number} end The end of the range.
39515 * @param {number} [step=1] The value to increment or decrement by.
39516 * @returns {Array} Returns the range of numbers.
39517 * @see _.inRange, _.range
39518 * @example
39519 *
39520 * _.rangeRight(4);
39521 * // => [3, 2, 1, 0]
39522 *
39523 * _.rangeRight(-4);
39524 * // => [-3, -2, -1, 0]
39525 *
39526 * _.rangeRight(1, 5);
39527 * // => [4, 3, 2, 1]
39528 *
39529 * _.rangeRight(0, 20, 5);
39530 * // => [15, 10, 5, 0]
39531 *
39532 * _.rangeRight(0, -4, -1);
39533 * // => [-3, -2, -1, 0]
39534 *
39535 * _.rangeRight(1, 4, 0);
39536 * // => [1, 1, 1]
39537 *
39538 * _.rangeRight(0);
39539 * // => []
39540 */
39541 var rangeRight = createRange(true);
39542
39543 /**
39544 * This method returns a new empty array.
39545 *
39546 * @static
39547 * @memberOf _
39548 * @since 4.13.0
39549 * @category Util
39550 * @returns {Array} Returns the new empty array.
39551 * @example
39552 *
39553 * var arrays = _.times(2, _.stubArray);
39554 *
39555 * console.log(arrays);
39556 * // => [[], []]
39557 *
39558 * console.log(arrays[0] === arrays[1]);
39559 * // => false
39560 */
39561 function stubArray() {
39562 return [];
39563 }
39564
39565 /**
39566 * This method returns `false`.
39567 *
39568 * @static
39569 * @memberOf _
39570 * @since 4.13.0
39571 * @category Util
39572 * @returns {boolean} Returns `false`.
39573 * @example
39574 *
39575 * _.times(2, _.stubFalse);
39576 * // => [false, false]
39577 */
39578 function stubFalse() {
39579 return false;
39580 }
39581
39582 /**
39583 * This method returns a new empty object.
39584 *
39585 * @static
39586 * @memberOf _
39587 * @since 4.13.0
39588 * @category Util
39589 * @returns {Object} Returns the new empty object.
39590 * @example
39591 *
39592 * var objects = _.times(2, _.stubObject);
39593 *
39594 * console.log(objects);
39595 * // => [{}, {}]
39596 *
39597 * console.log(objects[0] === objects[1]);
39598 * // => false
39599 */
39600 function stubObject() {
39601 return {};
39602 }
39603
39604 /**
39605 * This method returns an empty string.
39606 *
39607 * @static
39608 * @memberOf _
39609 * @since 4.13.0
39610 * @category Util
39611 * @returns {string} Returns the empty string.
39612 * @example
39613 *
39614 * _.times(2, _.stubString);
39615 * // => ['', '']
39616 */
39617 function stubString() {
39618 return '';
39619 }
39620
39621 /**
39622 * This method returns `true`.
39623 *
39624 * @static
39625 * @memberOf _
39626 * @since 4.13.0
39627 * @category Util
39628 * @returns {boolean} Returns `true`.
39629 * @example
39630 *
39631 * _.times(2, _.stubTrue);
39632 * // => [true, true]
39633 */
39634 function stubTrue() {
39635 return true;
39636 }
39637
39638 /**
39639 * Invokes the iteratee `n` times, returning an array of the results of
39640 * each invocation. The iteratee is invoked with one argument; (index).
39641 *
39642 * @static
39643 * @since 0.1.0
39644 * @memberOf _
39645 * @category Util
39646 * @param {number} n The number of times to invoke `iteratee`.
39647 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
39648 * @returns {Array} Returns the array of results.
39649 * @example
39650 *
39651 * _.times(3, String);
39652 * // => ['0', '1', '2']
39653 *
39654 * _.times(4, _.constant(0));
39655 * // => [0, 0, 0, 0]
39656 */
39657 function times(n, iteratee) {
39658 n = toInteger(n);
39659 if (n < 1 || n > MAX_SAFE_INTEGER) {
39660 return [];
39661 }
39662 var index = MAX_ARRAY_LENGTH,
39663 length = nativeMin(n, MAX_ARRAY_LENGTH);
39664
39665 iteratee = getIteratee(iteratee);
39666 n -= MAX_ARRAY_LENGTH;
39667
39668 var result = baseTimes(length, iteratee);
39669 while (++index < n) {
39670 iteratee(index);
39671 }
39672 return result;
39673 }
39674
39675 /**
39676 * Converts `value` to a property path array.
39677 *
39678 * @static
39679 * @memberOf _
39680 * @since 4.0.0
39681 * @category Util
39682 * @param {*} value The value to convert.
39683 * @returns {Array} Returns the new property path array.
39684 * @example
39685 *
39686 * _.toPath('a.b.c');
39687 * // => ['a', 'b', 'c']
39688 *
39689 * _.toPath('a[0].b.c');
39690 * // => ['a', '0', 'b', 'c']
39691 */
39692 function toPath(value) {
39693 if (isArray(value)) {
39694 return arrayMap(value, toKey);
39695 }
39696 return isSymbol(value) ? [value] : copyArray(stringToPath(value));
39697 }
39698
39699 /**
39700 * Generates a unique ID. If `prefix` is given, the ID is appended to it.
39701 *
39702 * @static
39703 * @since 0.1.0
39704 * @memberOf _
39705 * @category Util
39706 * @param {string} [prefix=''] The value to prefix the ID with.
39707 * @returns {string} Returns the unique ID.
39708 * @example
39709 *
39710 * _.uniqueId('contact_');
39711 * // => 'contact_104'
39712 *
39713 * _.uniqueId();
39714 * // => '105'
39715 */
39716 function uniqueId(prefix) {
39717 var id = ++idCounter;
39718 return toString(prefix) + id;
39719 }
39720
39721 /*------------------------------------------------------------------------*/
39722
39723 /**
39724 * Adds two numbers.
39725 *
39726 * @static
39727 * @memberOf _
39728 * @since 3.4.0
39729 * @category Math
39730 * @param {number} augend The first number in an addition.
39731 * @param {number} addend The second number in an addition.
39732 * @returns {number} Returns the total.
39733 * @example
39734 *
39735 * _.add(6, 4);
39736 * // => 10
39737 */
39738 var add = createMathOperation(function(augend, addend) {
39739 return augend + addend;
39740 }, 0);
39741
39742 /**
39743 * Computes `number` rounded up to `precision`.
39744 *
39745 * @static
39746 * @memberOf _
39747 * @since 3.10.0
39748 * @category Math
39749 * @param {number} number The number to round up.
39750 * @param {number} [precision=0] The precision to round up to.
39751 * @returns {number} Returns the rounded up number.
39752 * @example
39753 *
39754 * _.ceil(4.006);
39755 * // => 5
39756 *
39757 * _.ceil(6.004, 2);
39758 * // => 6.01
39759 *
39760 * _.ceil(6040, -2);
39761 * // => 6100
39762 */
39763 var ceil = createRound('ceil');
39764
39765 /**
39766 * Divide two numbers.
39767 *
39768 * @static
39769 * @memberOf _
39770 * @since 4.7.0
39771 * @category Math
39772 * @param {number} dividend The first number in a division.
39773 * @param {number} divisor The second number in a division.
39774 * @returns {number} Returns the quotient.
39775 * @example
39776 *
39777 * _.divide(6, 4);
39778 * // => 1.5
39779 */
39780 var divide = createMathOperation(function(dividend, divisor) {
39781 return dividend / divisor;
39782 }, 1);
39783
39784 /**
39785 * Computes `number` rounded down to `precision`.
39786 *
39787 * @static
39788 * @memberOf _
39789 * @since 3.10.0
39790 * @category Math
39791 * @param {number} number The number to round down.
39792 * @param {number} [precision=0] The precision to round down to.
39793 * @returns {number} Returns the rounded down number.
39794 * @example
39795 *
39796 * _.floor(4.006);
39797 * // => 4
39798 *
39799 * _.floor(0.046, 2);
39800 * // => 0.04
39801 *
39802 * _.floor(4060, -2);
39803 * // => 4000
39804 */
39805 var floor = createRound('floor');
39806
39807 /**
39808 * Computes the maximum value of `array`. If `array` is empty or falsey,
39809 * `undefined` is returned.
39810 *
39811 * @static
39812 * @since 0.1.0
39813 * @memberOf _
39814 * @category Math
39815 * @param {Array} array The array to iterate over.
39816 * @returns {*} Returns the maximum value.
39817 * @example
39818 *
39819 * _.max([4, 2, 8, 6]);
39820 * // => 8
39821 *
39822 * _.max([]);
39823 * // => undefined
39824 */
39825 function max(array) {
39826 return (array && array.length)
39827 ? baseExtremum(array, identity, baseGt)
39828 : undefined;
39829 }
39830
39831 /**
39832 * This method is like `_.max` except that it accepts `iteratee` which is
39833 * invoked for each element in `array` to generate the criterion by which
39834 * the value is ranked. The iteratee is invoked with one argument: (value).
39835 *
39836 * @static
39837 * @memberOf _
39838 * @since 4.0.0
39839 * @category Math
39840 * @param {Array} array The array to iterate over.
39841 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
39842 * @returns {*} Returns the maximum value.
39843 * @example
39844 *
39845 * var objects = [{ 'n': 1 }, { 'n': 2 }];
39846 *
39847 * _.maxBy(objects, function(o) { return o.n; });
39848 * // => { 'n': 2 }
39849 *
39850 * // The `_.property` iteratee shorthand.
39851 * _.maxBy(objects, 'n');
39852 * // => { 'n': 2 }
39853 */
39854 function maxBy(array, iteratee) {
39855 return (array && array.length)
39856 ? baseExtremum(array, getIteratee(iteratee, 2), baseGt)
39857 : undefined;
39858 }
39859
39860 /**
39861 * Computes the mean of the values in `array`.
39862 *
39863 * @static
39864 * @memberOf _
39865 * @since 4.0.0
39866 * @category Math
39867 * @param {Array} array The array to iterate over.
39868 * @returns {number} Returns the mean.
39869 * @example
39870 *
39871 * _.mean([4, 2, 8, 6]);
39872 * // => 5
39873 */
39874 function mean(array) {
39875 return baseMean(array, identity);
39876 }
39877
39878 /**
39879 * This method is like `_.mean` except that it accepts `iteratee` which is
39880 * invoked for each element in `array` to generate the value to be averaged.
39881 * The iteratee is invoked with one argument: (value).
39882 *
39883 * @static
39884 * @memberOf _
39885 * @since 4.7.0
39886 * @category Math
39887 * @param {Array} array The array to iterate over.
39888 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
39889 * @returns {number} Returns the mean.
39890 * @example
39891 *
39892 * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
39893 *
39894 * _.meanBy(objects, function(o) { return o.n; });
39895 * // => 5
39896 *
39897 * // The `_.property` iteratee shorthand.
39898 * _.meanBy(objects, 'n');
39899 * // => 5
39900 */
39901 function meanBy(array, iteratee) {
39902 return baseMean(array, getIteratee(iteratee, 2));
39903 }
39904
39905 /**
39906 * Computes the minimum value of `array`. If `array` is empty or falsey,
39907 * `undefined` is returned.
39908 *
39909 * @static
39910 * @since 0.1.0
39911 * @memberOf _
39912 * @category Math
39913 * @param {Array} array The array to iterate over.
39914 * @returns {*} Returns the minimum value.
39915 * @example
39916 *
39917 * _.min([4, 2, 8, 6]);
39918 * // => 2
39919 *
39920 * _.min([]);
39921 * // => undefined
39922 */
39923 function min(array) {
39924 return (array && array.length)
39925 ? baseExtremum(array, identity, baseLt)
39926 : undefined;
39927 }
39928
39929 /**
39930 * This method is like `_.min` except that it accepts `iteratee` which is
39931 * invoked for each element in `array` to generate the criterion by which
39932 * the value is ranked. The iteratee is invoked with one argument: (value).
39933 *
39934 * @static
39935 * @memberOf _
39936 * @since 4.0.0
39937 * @category Math
39938 * @param {Array} array The array to iterate over.
39939 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
39940 * @returns {*} Returns the minimum value.
39941 * @example
39942 *
39943 * var objects = [{ 'n': 1 }, { 'n': 2 }];
39944 *
39945 * _.minBy(objects, function(o) { return o.n; });
39946 * // => { 'n': 1 }
39947 *
39948 * // The `_.property` iteratee shorthand.
39949 * _.minBy(objects, 'n');
39950 * // => { 'n': 1 }
39951 */
39952 function minBy(array, iteratee) {
39953 return (array && array.length)
39954 ? baseExtremum(array, getIteratee(iteratee, 2), baseLt)
39955 : undefined;
39956 }
39957
39958 /**
39959 * Multiply two numbers.
39960 *
39961 * @static
39962 * @memberOf _
39963 * @since 4.7.0
39964 * @category Math
39965 * @param {number} multiplier The first number in a multiplication.
39966 * @param {number} multiplicand The second number in a multiplication.
39967 * @returns {number} Returns the product.
39968 * @example
39969 *
39970 * _.multiply(6, 4);
39971 * // => 24
39972 */
39973 var multiply = createMathOperation(function(multiplier, multiplicand) {
39974 return multiplier * multiplicand;
39975 }, 1);
39976
39977 /**
39978 * Computes `number` rounded to `precision`.
39979 *
39980 * @static
39981 * @memberOf _
39982 * @since 3.10.0
39983 * @category Math
39984 * @param {number} number The number to round.
39985 * @param {number} [precision=0] The precision to round to.
39986 * @returns {number} Returns the rounded number.
39987 * @example
39988 *
39989 * _.round(4.006);
39990 * // => 4
39991 *
39992 * _.round(4.006, 2);
39993 * // => 4.01
39994 *
39995 * _.round(4060, -2);
39996 * // => 4100
39997 */
39998 var round = createRound('round');
39999
40000 /**
40001 * Subtract two numbers.
40002 *
40003 * @static
40004 * @memberOf _
40005 * @since 4.0.0
40006 * @category Math
40007 * @param {number} minuend The first number in a subtraction.
40008 * @param {number} subtrahend The second number in a subtraction.
40009 * @returns {number} Returns the difference.
40010 * @example
40011 *
40012 * _.subtract(6, 4);
40013 * // => 2
40014 */
40015 var subtract = createMathOperation(function(minuend, subtrahend) {
40016 return minuend - subtrahend;
40017 }, 0);
40018
40019 /**
40020 * Computes the sum of the values in `array`.
40021 *
40022 * @static
40023 * @memberOf _
40024 * @since 3.4.0
40025 * @category Math
40026 * @param {Array} array The array to iterate over.
40027 * @returns {number} Returns the sum.
40028 * @example
40029 *
40030 * _.sum([4, 2, 8, 6]);
40031 * // => 20
40032 */
40033 function sum(array) {
40034 return (array && array.length)
40035 ? baseSum(array, identity)
40036 : 0;
40037 }
40038
40039 /**
40040 * This method is like `_.sum` except that it accepts `iteratee` which is
40041 * invoked for each element in `array` to generate the value to be summed.
40042 * The iteratee is invoked with one argument: (value).
40043 *
40044 * @static
40045 * @memberOf _
40046 * @since 4.0.0
40047 * @category Math
40048 * @param {Array} array The array to iterate over.
40049 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
40050 * @returns {number} Returns the sum.
40051 * @example
40052 *
40053 * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
40054 *
40055 * _.sumBy(objects, function(o) { return o.n; });
40056 * // => 20
40057 *
40058 * // The `_.property` iteratee shorthand.
40059 * _.sumBy(objects, 'n');
40060 * // => 20
40061 */
40062 function sumBy(array, iteratee) {
40063 return (array && array.length)
40064 ? baseSum(array, getIteratee(iteratee, 2))
40065 : 0;
40066 }
40067
40068 /*------------------------------------------------------------------------*/
40069
40070 // Add methods that return wrapped values in chain sequences.
40071 lodash.after = after;
40072 lodash.ary = ary;
40073 lodash.assign = assign;
40074 lodash.assignIn = assignIn;
40075 lodash.assignInWith = assignInWith;
40076 lodash.assignWith = assignWith;
40077 lodash.at = at;
40078 lodash.before = before;
40079 lodash.bind = bind;
40080 lodash.bindAll = bindAll;
40081 lodash.bindKey = bindKey;
40082 lodash.castArray = castArray;
40083 lodash.chain = chain;
40084 lodash.chunk = chunk;
40085 lodash.compact = compact;
40086 lodash.concat = concat;
40087 lodash.cond = cond;
40088 lodash.conforms = conforms;
40089 lodash.constant = constant;
40090 lodash.countBy = countBy;
40091 lodash.create = create;
40092 lodash.curry = curry;
40093 lodash.curryRight = curryRight;
40094 lodash.debounce = debounce;
40095 lodash.defaults = defaults;
40096 lodash.defaultsDeep = defaultsDeep;
40097 lodash.defer = defer;
40098 lodash.delay = delay;
40099 lodash.difference = difference;
40100 lodash.differenceBy = differenceBy;
40101 lodash.differenceWith = differenceWith;
40102 lodash.drop = drop;
40103 lodash.dropRight = dropRight;
40104 lodash.dropRightWhile = dropRightWhile;
40105 lodash.dropWhile = dropWhile;
40106 lodash.fill = fill;
40107 lodash.filter = filter;
40108 lodash.flatMap = flatMap;
40109 lodash.flatMapDeep = flatMapDeep;
40110 lodash.flatMapDepth = flatMapDepth;
40111 lodash.flatten = flatten;
40112 lodash.flattenDeep = flattenDeep;
40113 lodash.flattenDepth = flattenDepth;
40114 lodash.flip = flip;
40115 lodash.flow = flow;
40116 lodash.flowRight = flowRight;
40117 lodash.fromPairs = fromPairs;
40118 lodash.functions = functions;
40119 lodash.functionsIn = functionsIn;
40120 lodash.groupBy = groupBy;
40121 lodash.initial = initial;
40122 lodash.intersection = intersection;
40123 lodash.intersectionBy = intersectionBy;
40124 lodash.intersectionWith = intersectionWith;
40125 lodash.invert = invert;
40126 lodash.invertBy = invertBy;
40127 lodash.invokeMap = invokeMap;
40128 lodash.iteratee = iteratee;
40129 lodash.keyBy = keyBy;
40130 lodash.keys = keys;
40131 lodash.keysIn = keysIn;
40132 lodash.map = map;
40133 lodash.mapKeys = mapKeys;
40134 lodash.mapValues = mapValues;
40135 lodash.matches = matches;
40136 lodash.matchesProperty = matchesProperty;
40137 lodash.memoize = memoize;
40138 lodash.merge = merge;
40139 lodash.mergeWith = mergeWith;
40140 lodash.method = method;
40141 lodash.methodOf = methodOf;
40142 lodash.mixin = mixin;
40143 lodash.negate = negate;
40144 lodash.nthArg = nthArg;
40145 lodash.omit = omit;
40146 lodash.omitBy = omitBy;
40147 lodash.once = once;
40148 lodash.orderBy = orderBy;
40149 lodash.over = over;
40150 lodash.overArgs = overArgs;
40151 lodash.overEvery = overEvery;
40152 lodash.overSome = overSome;
40153 lodash.partial = partial;
40154 lodash.partialRight = partialRight;
40155 lodash.partition = partition;
40156 lodash.pick = pick;
40157 lodash.pickBy = pickBy;
40158 lodash.property = property;
40159 lodash.propertyOf = propertyOf;
40160 lodash.pull = pull;
40161 lodash.pullAll = pullAll;
40162 lodash.pullAllBy = pullAllBy;
40163 lodash.pullAllWith = pullAllWith;
40164 lodash.pullAt = pullAt;
40165 lodash.range = range;
40166 lodash.rangeRight = rangeRight;
40167 lodash.rearg = rearg;
40168 lodash.reject = reject;
40169 lodash.remove = remove;
40170 lodash.rest = rest;
40171 lodash.reverse = reverse;
40172 lodash.sampleSize = sampleSize;
40173 lodash.set = set;
40174 lodash.setWith = setWith;
40175 lodash.shuffle = shuffle;
40176 lodash.slice = slice;
40177 lodash.sortBy = sortBy;
40178 lodash.sortedUniq = sortedUniq;
40179 lodash.sortedUniqBy = sortedUniqBy;
40180 lodash.split = split;
40181 lodash.spread = spread;
40182 lodash.tail = tail;
40183 lodash.take = take;
40184 lodash.takeRight = takeRight;
40185 lodash.takeRightWhile = takeRightWhile;
40186 lodash.takeWhile = takeWhile;
40187 lodash.tap = tap;
40188 lodash.throttle = throttle;
40189 lodash.thru = thru;
40190 lodash.toArray = toArray;
40191 lodash.toPairs = toPairs;
40192 lodash.toPairsIn = toPairsIn;
40193 lodash.toPath = toPath;
40194 lodash.toPlainObject = toPlainObject;
40195 lodash.transform = transform;
40196 lodash.unary = unary;
40197 lodash.union = union;
40198 lodash.unionBy = unionBy;
40199 lodash.unionWith = unionWith;
40200 lodash.uniq = uniq;
40201 lodash.uniqBy = uniqBy;
40202 lodash.uniqWith = uniqWith;
40203 lodash.unset = unset;
40204 lodash.unzip = unzip;
40205 lodash.unzipWith = unzipWith;
40206 lodash.update = update;
40207 lodash.updateWith = updateWith;
40208 lodash.values = values;
40209 lodash.valuesIn = valuesIn;
40210 lodash.without = without;
40211 lodash.words = words;
40212 lodash.wrap = wrap;
40213 lodash.xor = xor;
40214 lodash.xorBy = xorBy;
40215 lodash.xorWith = xorWith;
40216 lodash.zip = zip;
40217 lodash.zipObject = zipObject;
40218 lodash.zipObjectDeep = zipObjectDeep;
40219 lodash.zipWith = zipWith;
40220
40221 // Add aliases.
40222 lodash.entries = toPairs;
40223 lodash.entriesIn = toPairsIn;
40224 lodash.extend = assignIn;
40225 lodash.extendWith = assignInWith;
40226
40227 // Add methods to `lodash.prototype`.
40228 mixin(lodash, lodash);
40229
40230 /*------------------------------------------------------------------------*/
40231
40232 // Add methods that return unwrapped values in chain sequences.
40233 lodash.add = add;
40234 lodash.attempt = attempt;
40235 lodash.camelCase = camelCase;
40236 lodash.capitalize = capitalize;
40237 lodash.ceil = ceil;
40238 lodash.clamp = clamp;
40239 lodash.clone = clone;
40240 lodash.cloneDeep = cloneDeep;
40241 lodash.cloneDeepWith = cloneDeepWith;
40242 lodash.cloneWith = cloneWith;
40243 lodash.conformsTo = conformsTo;
40244 lodash.deburr = deburr;
40245 lodash.defaultTo = defaultTo;
40246 lodash.divide = divide;
40247 lodash.endsWith = endsWith;
40248 lodash.eq = eq;
40249 lodash.escape = escape;
40250 lodash.escapeRegExp = escapeRegExp;
40251 lodash.every = every;
40252 lodash.find = find;
40253 lodash.findIndex = findIndex;
40254 lodash.findKey = findKey;
40255 lodash.findLast = findLast;
40256 lodash.findLastIndex = findLastIndex;
40257 lodash.findLastKey = findLastKey;
40258 lodash.floor = floor;
40259 lodash.forEach = forEach;
40260 lodash.forEachRight = forEachRight;
40261 lodash.forIn = forIn;
40262 lodash.forInRight = forInRight;
40263 lodash.forOwn = forOwn;
40264 lodash.forOwnRight = forOwnRight;
40265 lodash.get = get;
40266 lodash.gt = gt;
40267 lodash.gte = gte;
40268 lodash.has = has;
40269 lodash.hasIn = hasIn;
40270 lodash.head = head;
40271 lodash.identity = identity;
40272 lodash.includes = includes;
40273 lodash.indexOf = indexOf;
40274 lodash.inRange = inRange;
40275 lodash.invoke = invoke;
40276 lodash.isArguments = isArguments;
40277 lodash.isArray = isArray;
40278 lodash.isArrayBuffer = isArrayBuffer;
40279 lodash.isArrayLike = isArrayLike;
40280 lodash.isArrayLikeObject = isArrayLikeObject;
40281 lodash.isBoolean = isBoolean;
40282 lodash.isBuffer = isBuffer;
40283 lodash.isDate = isDate;
40284 lodash.isElement = isElement;
40285 lodash.isEmpty = isEmpty;
40286 lodash.isEqual = isEqual;
40287 lodash.isEqualWith = isEqualWith;
40288 lodash.isError = isError;
40289 lodash.isFinite = isFinite;
40290 lodash.isFunction = isFunction;
40291 lodash.isInteger = isInteger;
40292 lodash.isLength = isLength;
40293 lodash.isMap = isMap;
40294 lodash.isMatch = isMatch;
40295 lodash.isMatchWith = isMatchWith;
40296 lodash.isNaN = isNaN;
40297 lodash.isNative = isNative;
40298 lodash.isNil = isNil;
40299 lodash.isNull = isNull;
40300 lodash.isNumber = isNumber;
40301 lodash.isObject = isObject;
40302 lodash.isObjectLike = isObjectLike;
40303 lodash.isPlainObject = isPlainObject;
40304 lodash.isRegExp = isRegExp;
40305 lodash.isSafeInteger = isSafeInteger;
40306 lodash.isSet = isSet;
40307 lodash.isString = isString;
40308 lodash.isSymbol = isSymbol;
40309 lodash.isTypedArray = isTypedArray;
40310 lodash.isUndefined = isUndefined;
40311 lodash.isWeakMap = isWeakMap;
40312 lodash.isWeakSet = isWeakSet;
40313 lodash.join = join;
40314 lodash.kebabCase = kebabCase;
40315 lodash.last = last;
40316 lodash.lastIndexOf = lastIndexOf;
40317 lodash.lowerCase = lowerCase;
40318 lodash.lowerFirst = lowerFirst;
40319 lodash.lt = lt;
40320 lodash.lte = lte;
40321 lodash.max = max;
40322 lodash.maxBy = maxBy;
40323 lodash.mean = mean;
40324 lodash.meanBy = meanBy;
40325 lodash.min = min;
40326 lodash.minBy = minBy;
40327 lodash.stubArray = stubArray;
40328 lodash.stubFalse = stubFalse;
40329 lodash.stubObject = stubObject;
40330 lodash.stubString = stubString;
40331 lodash.stubTrue = stubTrue;
40332 lodash.multiply = multiply;
40333 lodash.nth = nth;
40334 lodash.noConflict = noConflict;
40335 lodash.noop = noop;
40336 lodash.now = now;
40337 lodash.pad = pad;
40338 lodash.padEnd = padEnd;
40339 lodash.padStart = padStart;
40340 lodash.parseInt = parseInt;
40341 lodash.random = random;
40342 lodash.reduce = reduce;
40343 lodash.reduceRight = reduceRight;
40344 lodash.repeat = repeat;
40345 lodash.replace = replace;
40346 lodash.result = result;
40347 lodash.round = round;
40348 lodash.runInContext = runInContext;
40349 lodash.sample = sample;
40350 lodash.size = size;
40351 lodash.snakeCase = snakeCase;
40352 lodash.some = some;
40353 lodash.sortedIndex = sortedIndex;
40354 lodash.sortedIndexBy = sortedIndexBy;
40355 lodash.sortedIndexOf = sortedIndexOf;
40356 lodash.sortedLastIndex = sortedLastIndex;
40357 lodash.sortedLastIndexBy = sortedLastIndexBy;
40358 lodash.sortedLastIndexOf = sortedLastIndexOf;
40359 lodash.startCase = startCase;
40360 lodash.startsWith = startsWith;
40361 lodash.subtract = subtract;
40362 lodash.sum = sum;
40363 lodash.sumBy = sumBy;
40364 lodash.template = template;
40365 lodash.times = times;
40366 lodash.toFinite = toFinite;
40367 lodash.toInteger = toInteger;
40368 lodash.toLength = toLength;
40369 lodash.toLower = toLower;
40370 lodash.toNumber = toNumber;
40371 lodash.toSafeInteger = toSafeInteger;
40372 lodash.toString = toString;
40373 lodash.toUpper = toUpper;
40374 lodash.trim = trim;
40375 lodash.trimEnd = trimEnd;
40376 lodash.trimStart = trimStart;
40377 lodash.truncate = truncate;
40378 lodash.unescape = unescape;
40379 lodash.uniqueId = uniqueId;
40380 lodash.upperCase = upperCase;
40381 lodash.upperFirst = upperFirst;
40382
40383 // Add aliases.
40384 lodash.each = forEach;
40385 lodash.eachRight = forEachRight;
40386 lodash.first = head;
40387
40388 mixin(lodash, (function() {
40389 var source = {};
40390 baseForOwn(lodash, function(func, methodName) {
40391 if (!hasOwnProperty.call(lodash.prototype, methodName)) {
40392 source[methodName] = func;
40393 }
40394 });
40395 return source;
40396 }()), { 'chain': false });
40397
40398 /*------------------------------------------------------------------------*/
40399
40400 /**
40401 * The semantic version number.
40402 *
40403 * @static
40404 * @memberOf _
40405 * @type {string}
40406 */
40407 lodash.VERSION = VERSION;
40408
40409 // Assign default placeholders.
40410 arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) {
40411 lodash[methodName].placeholder = lodash;
40412 });
40413
40414 // Add `LazyWrapper` methods for `_.drop` and `_.take` variants.
40415 arrayEach(['drop', 'take'], function(methodName, index) {
40416 LazyWrapper.prototype[methodName] = function(n) {
40417 var filtered = this.__filtered__;
40418 if (filtered && !index) {
40419 return new LazyWrapper(this);
40420 }
40421 n = n === undefined ? 1 : nativeMax(toInteger(n), 0);
40422
40423 var result = this.clone();
40424 if (filtered) {
40425 result.__takeCount__ = nativeMin(n, result.__takeCount__);
40426 } else {
40427 result.__views__.push({
40428 'size': nativeMin(n, MAX_ARRAY_LENGTH),
40429 'type': methodName + (result.__dir__ < 0 ? 'Right' : '')
40430 });
40431 }
40432 return result;
40433 };
40434
40435 LazyWrapper.prototype[methodName + 'Right'] = function(n) {
40436 return this.reverse()[methodName](n).reverse();
40437 };
40438 });
40439
40440 // Add `LazyWrapper` methods that accept an `iteratee` value.
40441 arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) {
40442 var type = index + 1,
40443 isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG;
40444
40445 LazyWrapper.prototype[methodName] = function(iteratee) {
40446 var result = this.clone();
40447 result.__iteratees__.push({
40448 'iteratee': getIteratee(iteratee, 3),
40449 'type': type
40450 });
40451 result.__filtered__ = result.__filtered__ || isFilter;
40452 return result;
40453 };
40454 });
40455
40456 // Add `LazyWrapper` methods for `_.head` and `_.last`.
40457 arrayEach(['head', 'last'], function(methodName, index) {
40458 var takeName = 'take' + (index ? 'Right' : '');
40459
40460 LazyWrapper.prototype[methodName] = function() {
40461 return this[takeName](1).value()[0];
40462 };
40463 });
40464
40465 // Add `LazyWrapper` methods for `_.initial` and `_.tail`.
40466 arrayEach(['initial', 'tail'], function(methodName, index) {
40467 var dropName = 'drop' + (index ? '' : 'Right');
40468
40469 LazyWrapper.prototype[methodName] = function() {
40470 return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1);
40471 };
40472 });
40473
40474 LazyWrapper.prototype.compact = function() {
40475 return this.filter(identity);
40476 };
40477
40478 LazyWrapper.prototype.find = function(predicate) {
40479 return this.filter(predicate).head();
40480 };
40481
40482 LazyWrapper.prototype.findLast = function(predicate) {
40483 return this.reverse().find(predicate);
40484 };
40485
40486 LazyWrapper.prototype.invokeMap = baseRest(function(path, args) {
40487 if (typeof path == 'function') {
40488 return new LazyWrapper(this);
40489 }
40490 return this.map(function(value) {
40491 return baseInvoke(value, path, args);
40492 });
40493 });
40494
40495 LazyWrapper.prototype.reject = function(predicate) {
40496 return this.filter(negate(getIteratee(predicate)));
40497 };
40498
40499 LazyWrapper.prototype.slice = function(start, end) {
40500 start = toInteger(start);
40501
40502 var result = this;
40503 if (result.__filtered__ && (start > 0 || end < 0)) {
40504 return new LazyWrapper(result);
40505 }
40506 if (start < 0) {
40507 result = result.takeRight(-start);
40508 } else if (start) {
40509 result = result.drop(start);
40510 }
40511 if (end !== undefined) {
40512 end = toInteger(end);
40513 result = end < 0 ? result.dropRight(-end) : result.take(end - start);
40514 }
40515 return result;
40516 };
40517
40518 LazyWrapper.prototype.takeRightWhile = function(predicate) {
40519 return this.reverse().takeWhile(predicate).reverse();
40520 };
40521
40522 LazyWrapper.prototype.toArray = function() {
40523 return this.take(MAX_ARRAY_LENGTH);
40524 };
40525
40526 // Add `LazyWrapper` methods to `lodash.prototype`.
40527 baseForOwn(LazyWrapper.prototype, function(func, methodName) {
40528 var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName),
40529 isTaker = /^(?:head|last)$/.test(methodName),
40530 lodashFunc = lodash[isTaker ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName],
40531 retUnwrapped = isTaker || /^find/.test(methodName);
40532
40533 if (!lodashFunc) {
40534 return;
40535 }
40536 lodash.prototype[methodName] = function() {
40537 var value = this.__wrapped__,
40538 args = isTaker ? [1] : arguments,
40539 isLazy = value instanceof LazyWrapper,
40540 iteratee = args[0],
40541 useLazy = isLazy || isArray(value);
40542
40543 var interceptor = function(value) {
40544 var result = lodashFunc.apply(lodash, arrayPush([value], args));
40545 return (isTaker && chainAll) ? result[0] : result;
40546 };
40547
40548 if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
40549 // Avoid lazy use if the iteratee has a "length" value other than `1`.
40550 isLazy = useLazy = false;
40551 }
40552 var chainAll = this.__chain__,
40553 isHybrid = !!this.__actions__.length,
40554 isUnwrapped = retUnwrapped && !chainAll,
40555 onlyLazy = isLazy && !isHybrid;
40556
40557 if (!retUnwrapped && useLazy) {
40558 value = onlyLazy ? value : new LazyWrapper(this);
40559 var result = func.apply(value, args);
40560 result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
40561 return new LodashWrapper(result, chainAll);
40562 }
40563 if (isUnwrapped && onlyLazy) {
40564 return func.apply(this, args);
40565 }
40566 result = this.thru(interceptor);
40567 return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
40568 };
40569 });
40570
40571 // Add `Array` methods to `lodash.prototype`.
40572 arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) {
40573 var func = arrayProto[methodName],
40574 chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru',
40575 retUnwrapped = /^(?:pop|shift)$/.test(methodName);
40576
40577 lodash.prototype[methodName] = function() {
40578 var args = arguments;
40579 if (retUnwrapped && !this.__chain__) {
40580 var value = this.value();
40581 return func.apply(isArray(value) ? value : [], args);
40582 }
40583 return this[chainName](function(value) {
40584 return func.apply(isArray(value) ? value : [], args);
40585 });
40586 };
40587 });
40588
40589 // Map minified method names to their real names.
40590 baseForOwn(LazyWrapper.prototype, function(func, methodName) {
40591 var lodashFunc = lodash[methodName];
40592 if (lodashFunc) {
40593 var key = (lodashFunc.name + ''),
40594 names = realNames[key] || (realNames[key] = []);
40595
40596 names.push({ 'name': methodName, 'func': lodashFunc });
40597 }
40598 });
40599
40600 realNames[createHybrid(undefined, BIND_KEY_FLAG).name] = [{
40601 'name': 'wrapper',
40602 'func': undefined
40603 }];
40604
40605 // Add methods to `LazyWrapper`.
40606 LazyWrapper.prototype.clone = lazyClone;
40607 LazyWrapper.prototype.reverse = lazyReverse;
40608 LazyWrapper.prototype.value = lazyValue;
40609
40610 // Add chain sequence methods to the `lodash` wrapper.
40611 lodash.prototype.at = wrapperAt;
40612 lodash.prototype.chain = wrapperChain;
40613 lodash.prototype.commit = wrapperCommit;
40614 lodash.prototype.next = wrapperNext;
40615 lodash.prototype.plant = wrapperPlant;
40616 lodash.prototype.reverse = wrapperReverse;
40617 lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue;
40618
40619 // Add lazy aliases.
40620 lodash.prototype.first = lodash.prototype.head;
40621
40622 if (iteratorSymbol) {
40623 lodash.prototype[iteratorSymbol] = wrapperToIterator;
40624 }
40625 return lodash;
40626 });
40627
40628 /*--------------------------------------------------------------------------*/
40629
40630 // Export lodash.
40631 var _ = runInContext();
40632
40633 // Some AMD build optimizers, like r.js, check for condition patterns like:
40634 if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
40635 // Expose Lodash on the global object to prevent errors when Lodash is
40636 // loaded by a script tag in the presence of an AMD loader.
40637 // See http://requirejs.org/docs/errors.html#mismatch for more details.
40638 // Use `_.noConflict` to remove Lodash from the global object.
40639 root._ = _;
40640
40641 // Define as an anonymous module so, through path mapping, it can be
40642 // referenced as the "underscore" module.
40643 define(function() {
40644 return _;
40645 });
40646 }
40647 // Check for `exports` after `define` in case a build optimizer adds it.
40648 else if (freeModule) {
40649 // Export for Node.js.
40650 (freeModule.exports = _)._ = _;
40651 // Export for CommonJS support.
40652 freeExports._ = _;
40653 }
40654 else {
40655 // Export to the global object.
40656 root._ = _;
40657 }
40658}.call(this));
40659
40660}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
40661},{}],16:[function(require,module,exports){
40662(function (global){
40663"use strict";
40664
40665var numeric = (typeof exports === "undefined")?(function numeric() {}):(exports);
40666if(typeof global !== "undefined") { global.numeric = numeric; }
40667
40668numeric.version = "1.2.6";
40669
40670// 1. Utility functions
40671numeric.bench = function bench (f,interval) {
40672 var t1,t2,n,i;
40673 if(typeof interval === "undefined") { interval = 15; }
40674 n = 0.5;
40675 t1 = new Date();
40676 while(1) {
40677 n*=2;
40678 for(i=n;i>3;i-=4) { f(); f(); f(); f(); }
40679 while(i>0) { f(); i--; }
40680 t2 = new Date();
40681 if(t2-t1 > interval) break;
40682 }
40683 for(i=n;i>3;i-=4) { f(); f(); f(); f(); }
40684 while(i>0) { f(); i--; }
40685 t2 = new Date();
40686 return 1000*(3*n-1)/(t2-t1);
40687}
40688
40689numeric._myIndexOf = (function _myIndexOf(w) {
40690 var n = this.length,k;
40691 for(k=0;k<n;++k) if(this[k]===w) return k;
40692 return -1;
40693});
40694numeric.myIndexOf = (Array.prototype.indexOf)?Array.prototype.indexOf:numeric._myIndexOf;
40695
40696numeric.Function = Function;
40697numeric.precision = 4;
40698numeric.largeArray = 50;
40699
40700numeric.prettyPrint = function prettyPrint(x) {
40701 function fmtnum(x) {
40702 if(x === 0) { return '0'; }
40703 if(isNaN(x)) { return 'NaN'; }
40704 if(x<0) { return '-'+fmtnum(-x); }
40705 if(isFinite(x)) {
40706 var scale = Math.floor(Math.log(x) / Math.log(10));
40707 var normalized = x / Math.pow(10,scale);
40708 var basic = normalized.toPrecision(numeric.precision);
40709 if(parseFloat(basic) === 10) { scale++; normalized = 1; basic = normalized.toPrecision(numeric.precision); }
40710 return parseFloat(basic).toString()+'e'+scale.toString();
40711 }
40712 return 'Infinity';
40713 }
40714 var ret = [];
40715 function foo(x) {
40716 var k;
40717 if(typeof x === "undefined") { ret.push(Array(numeric.precision+8).join(' ')); return false; }
40718 if(typeof x === "string") { ret.push('"'+x+'"'); return false; }
40719 if(typeof x === "boolean") { ret.push(x.toString()); return false; }
40720 if(typeof x === "number") {
40721 var a = fmtnum(x);
40722 var b = x.toPrecision(numeric.precision);
40723 var c = parseFloat(x.toString()).toString();
40724 var d = [a,b,c,parseFloat(b).toString(),parseFloat(c).toString()];
40725 for(k=1;k<d.length;k++) { if(d[k].length < a.length) a = d[k]; }
40726 ret.push(Array(numeric.precision+8-a.length).join(' ')+a);
40727 return false;
40728 }
40729 if(x === null) { ret.push("null"); return false; }
40730 if(typeof x === "function") {
40731 ret.push(x.toString());
40732 var flag = false;
40733 for(k in x) { if(x.hasOwnProperty(k)) {
40734 if(flag) ret.push(',\n');
40735 else ret.push('\n{');
40736 flag = true;
40737 ret.push(k);
40738 ret.push(': \n');
40739 foo(x[k]);
40740 } }
40741 if(flag) ret.push('}\n');
40742 return true;
40743 }
40744 if(x instanceof Array) {
40745 if(x.length > numeric.largeArray) { ret.push('...Large Array...'); return true; }
40746 var flag = false;
40747 ret.push('[');
40748 for(k=0;k<x.length;k++) { if(k>0) { ret.push(','); if(flag) ret.push('\n '); } flag = foo(x[k]); }
40749 ret.push(']');
40750 return true;
40751 }
40752 ret.push('{');
40753 var flag = false;
40754 for(k in x) { if(x.hasOwnProperty(k)) { if(flag) ret.push(',\n'); flag = true; ret.push(k); ret.push(': \n'); foo(x[k]); } }
40755 ret.push('}');
40756 return true;
40757 }
40758 foo(x);
40759 return ret.join('');
40760}
40761
40762numeric.parseDate = function parseDate(d) {
40763 function foo(d) {
40764 if(typeof d === 'string') { return Date.parse(d.replace(/-/g,'/')); }
40765 if(!(d instanceof Array)) { throw new Error("parseDate: parameter must be arrays of strings"); }
40766 var ret = [],k;
40767 for(k=0;k<d.length;k++) { ret[k] = foo(d[k]); }
40768 return ret;
40769 }
40770 return foo(d);
40771}
40772
40773numeric.parseFloat = function parseFloat_(d) {
40774 function foo(d) {
40775 if(typeof d === 'string') { return parseFloat(d); }
40776 if(!(d instanceof Array)) { throw new Error("parseFloat: parameter must be arrays of strings"); }
40777 var ret = [],k;
40778 for(k=0;k<d.length;k++) { ret[k] = foo(d[k]); }
40779 return ret;
40780 }
40781 return foo(d);
40782}
40783
40784numeric.parseCSV = function parseCSV(t) {
40785 var foo = t.split('\n');
40786 var j,k;
40787 var ret = [];
40788 var pat = /(([^'",]*)|('[^']*')|("[^"]*")),/g;
40789 var patnum = /^\s*(([+-]?[0-9]+(\.[0-9]*)?(e[+-]?[0-9]+)?)|([+-]?[0-9]*(\.[0-9]+)?(e[+-]?[0-9]+)?))\s*$/;
40790 var stripper = function(n) { return n.substr(0,n.length-1); }
40791 var count = 0;
40792 for(k=0;k<foo.length;k++) {
40793 var bar = (foo[k]+",").match(pat),baz;
40794 if(bar.length>0) {
40795 ret[count] = [];
40796 for(j=0;j<bar.length;j++) {
40797 baz = stripper(bar[j]);
40798 if(patnum.test(baz)) { ret[count][j] = parseFloat(baz); }
40799 else ret[count][j] = baz;
40800 }
40801 count++;
40802 }
40803 }
40804 return ret;
40805}
40806
40807numeric.toCSV = function toCSV(A) {
40808 var s = numeric.dim(A);
40809 var i,j,m,n,row,ret;
40810 m = s[0];
40811 n = s[1];
40812 ret = [];
40813 for(i=0;i<m;i++) {
40814 row = [];
40815 for(j=0;j<m;j++) { row[j] = A[i][j].toString(); }
40816 ret[i] = row.join(', ');
40817 }
40818 return ret.join('\n')+'\n';
40819}
40820
40821numeric.getURL = function getURL(url) {
40822 var client = new XMLHttpRequest();
40823 client.open("GET",url,false);
40824 client.send();
40825 return client;
40826}
40827
40828numeric.imageURL = function imageURL(img) {
40829 function base64(A) {
40830 var n = A.length, i,x,y,z,p,q,r,s;
40831 var key = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
40832 var ret = "";
40833 for(i=0;i<n;i+=3) {
40834 x = A[i];
40835 y = A[i+1];
40836 z = A[i+2];
40837 p = x >> 2;
40838 q = ((x & 3) << 4) + (y >> 4);
40839 r = ((y & 15) << 2) + (z >> 6);
40840 s = z & 63;
40841 if(i+1>=n) { r = s = 64; }
40842 else if(i+2>=n) { s = 64; }
40843 ret += key.charAt(p) + key.charAt(q) + key.charAt(r) + key.charAt(s);
40844 }
40845 return ret;
40846 }
40847 function crc32Array (a,from,to) {
40848 if(typeof from === "undefined") { from = 0; }
40849 if(typeof to === "undefined") { to = a.length; }
40850 var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
40851 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
40852 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
40853 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
40854 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
40855 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
40856 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
40857 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
40858 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
40859 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
40860 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
40861 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
40862 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
40863 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
40864 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
40865 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
40866 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
40867 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
40868 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
40869 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
40870 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
40871 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
40872 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
40873 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
40874 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
40875 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
40876 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
40877 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
40878 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
40879 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
40880 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
40881 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D];
40882
40883 var crc = -1, y = 0, n = a.length,i;
40884
40885 for (i = from; i < to; i++) {
40886 y = (crc ^ a[i]) & 0xFF;
40887 crc = (crc >>> 8) ^ table[y];
40888 }
40889
40890 return crc ^ (-1);
40891 }
40892
40893 var h = img[0].length, w = img[0][0].length, s1, s2, next,k,length,a,b,i,j,adler32,crc32;
40894 var stream = [
40895 137, 80, 78, 71, 13, 10, 26, 10, // 0: PNG signature
40896 0,0,0,13, // 8: IHDR Chunk length
40897 73, 72, 68, 82, // 12: "IHDR"
40898 (w >> 24) & 255, (w >> 16) & 255, (w >> 8) & 255, w&255, // 16: Width
40899 (h >> 24) & 255, (h >> 16) & 255, (h >> 8) & 255, h&255, // 20: Height
40900 8, // 24: bit depth
40901 2, // 25: RGB
40902 0, // 26: deflate
40903 0, // 27: no filter
40904 0, // 28: no interlace
40905 -1,-2,-3,-4, // 29: CRC
40906 -5,-6,-7,-8, // 33: IDAT Chunk length
40907 73, 68, 65, 84, // 37: "IDAT"
40908 // RFC 1950 header starts here
40909 8, // 41: RFC1950 CMF
40910 29 // 42: RFC1950 FLG
40911 ];
40912 crc32 = crc32Array(stream,12,29);
40913 stream[29] = (crc32>>24)&255;
40914 stream[30] = (crc32>>16)&255;
40915 stream[31] = (crc32>>8)&255;
40916 stream[32] = (crc32)&255;
40917 s1 = 1;
40918 s2 = 0;
40919 for(i=0;i<h;i++) {
40920 if(i<h-1) { stream.push(0); }
40921 else { stream.push(1); }
40922 a = (3*w+1+(i===0))&255; b = ((3*w+1+(i===0))>>8)&255;
40923 stream.push(a); stream.push(b);
40924 stream.push((~a)&255); stream.push((~b)&255);
40925 if(i===0) stream.push(0);
40926 for(j=0;j<w;j++) {
40927 for(k=0;k<3;k++) {
40928 a = img[k][i][j];
40929 if(a>255) a = 255;
40930 else if(a<0) a=0;
40931 else a = Math.round(a);
40932 s1 = (s1 + a )%65521;
40933 s2 = (s2 + s1)%65521;
40934 stream.push(a);
40935 }
40936 }
40937 stream.push(0);
40938 }
40939 adler32 = (s2<<16)+s1;
40940 stream.push((adler32>>24)&255);
40941 stream.push((adler32>>16)&255);
40942 stream.push((adler32>>8)&255);
40943 stream.push((adler32)&255);
40944 length = stream.length - 41;
40945 stream[33] = (length>>24)&255;
40946 stream[34] = (length>>16)&255;
40947 stream[35] = (length>>8)&255;
40948 stream[36] = (length)&255;
40949 crc32 = crc32Array(stream,37);
40950 stream.push((crc32>>24)&255);
40951 stream.push((crc32>>16)&255);
40952 stream.push((crc32>>8)&255);
40953 stream.push((crc32)&255);
40954 stream.push(0);
40955 stream.push(0);
40956 stream.push(0);
40957 stream.push(0);
40958// a = stream.length;
40959 stream.push(73); // I
40960 stream.push(69); // E
40961 stream.push(78); // N
40962 stream.push(68); // D
40963 stream.push(174); // CRC1
40964 stream.push(66); // CRC2
40965 stream.push(96); // CRC3
40966 stream.push(130); // CRC4
40967 return 'data:image/png;base64,'+base64(stream);
40968}
40969
40970// 2. Linear algebra with Arrays.
40971numeric._dim = function _dim(x) {
40972 var ret = [];
40973 while(typeof x === "object") { ret.push(x.length); x = x[0]; }
40974 return ret;
40975}
40976
40977numeric.dim = function dim(x) {
40978 var y,z;
40979 if(typeof x === "object") {
40980 y = x[0];
40981 if(typeof y === "object") {
40982 z = y[0];
40983 if(typeof z === "object") {
40984 return numeric._dim(x);
40985 }
40986 return [x.length,y.length];
40987 }
40988 return [x.length];
40989 }
40990 return [];
40991}
40992
40993numeric.mapreduce = function mapreduce(body,init) {
40994 return Function('x','accum','_s','_k',
40995 'if(typeof accum === "undefined") accum = '+init+';\n'+
40996 'if(typeof x === "number") { var xi = x; '+body+'; return accum; }\n'+
40997 'if(typeof _s === "undefined") _s = numeric.dim(x);\n'+
40998 'if(typeof _k === "undefined") _k = 0;\n'+
40999 'var _n = _s[_k];\n'+
41000 'var i,xi;\n'+
41001 'if(_k < _s.length-1) {\n'+
41002 ' for(i=_n-1;i>=0;i--) {\n'+
41003 ' accum = arguments.callee(x[i],accum,_s,_k+1);\n'+
41004 ' }'+
41005 ' return accum;\n'+
41006 '}\n'+
41007 'for(i=_n-1;i>=1;i-=2) { \n'+
41008 ' xi = x[i];\n'+
41009 ' '+body+';\n'+
41010 ' xi = x[i-1];\n'+
41011 ' '+body+';\n'+
41012 '}\n'+
41013 'if(i === 0) {\n'+
41014 ' xi = x[i];\n'+
41015 ' '+body+'\n'+
41016 '}\n'+
41017 'return accum;'
41018 );
41019}
41020numeric.mapreduce2 = function mapreduce2(body,setup) {
41021 return Function('x',
41022 'var n = x.length;\n'+
41023 'var i,xi;\n'+setup+';\n'+
41024 'for(i=n-1;i!==-1;--i) { \n'+
41025 ' xi = x[i];\n'+
41026 ' '+body+';\n'+
41027 '}\n'+
41028 'return accum;'
41029 );
41030}
41031
41032
41033numeric.same = function same(x,y) {
41034 var i,n;
41035 if(!(x instanceof Array) || !(y instanceof Array)) { return false; }
41036 n = x.length;
41037 if(n !== y.length) { return false; }
41038 for(i=0;i<n;i++) {
41039 if(x[i] === y[i]) { continue; }
41040 if(typeof x[i] === "object") { if(!same(x[i],y[i])) return false; }
41041 else { return false; }
41042 }
41043 return true;
41044}
41045
41046numeric.rep = function rep(s,v,k) {
41047 if(typeof k === "undefined") { k=0; }
41048 var n = s[k], ret = Array(n), i;
41049 if(k === s.length-1) {
41050 for(i=n-2;i>=0;i-=2) { ret[i+1] = v; ret[i] = v; }
41051 if(i===-1) { ret[0] = v; }
41052 return ret;
41053 }
41054 for(i=n-1;i>=0;i--) { ret[i] = numeric.rep(s,v,k+1); }
41055 return ret;
41056}
41057
41058
41059numeric.dotMMsmall = function dotMMsmall(x,y) {
41060 var i,j,k,p,q,r,ret,foo,bar,woo,i0,k0,p0,r0;
41061 p = x.length; q = y.length; r = y[0].length;
41062 ret = Array(p);
41063 for(i=p-1;i>=0;i--) {
41064 foo = Array(r);
41065 bar = x[i];
41066 for(k=r-1;k>=0;k--) {
41067 woo = bar[q-1]*y[q-1][k];
41068 for(j=q-2;j>=1;j-=2) {
41069 i0 = j-1;
41070 woo += bar[j]*y[j][k] + bar[i0]*y[i0][k];
41071 }
41072 if(j===0) { woo += bar[0]*y[0][k]; }
41073 foo[k] = woo;
41074 }
41075 ret[i] = foo;
41076 }
41077 return ret;
41078}
41079numeric._getCol = function _getCol(A,j,x) {
41080 var n = A.length, i;
41081 for(i=n-1;i>0;--i) {
41082 x[i] = A[i][j];
41083 --i;
41084 x[i] = A[i][j];
41085 }
41086 if(i===0) x[0] = A[0][j];
41087}
41088numeric.dotMMbig = function dotMMbig(x,y){
41089 var gc = numeric._getCol, p = y.length, v = Array(p);
41090 var m = x.length, n = y[0].length, A = new Array(m), xj;
41091 var VV = numeric.dotVV;
41092 var i,j,k,z;
41093 --p;
41094 --m;
41095 for(i=m;i!==-1;--i) A[i] = Array(n);
41096 --n;
41097 for(i=n;i!==-1;--i) {
41098 gc(y,i,v);
41099 for(j=m;j!==-1;--j) {
41100 z=0;
41101 xj = x[j];
41102 A[j][i] = VV(xj,v);
41103 }
41104 }
41105 return A;
41106}
41107
41108numeric.dotMV = function dotMV(x,y) {
41109 var p = x.length, q = y.length,i;
41110 var ret = Array(p), dotVV = numeric.dotVV;
41111 for(i=p-1;i>=0;i--) { ret[i] = dotVV(x[i],y); }
41112 return ret;
41113}
41114
41115numeric.dotVM = function dotVM(x,y) {
41116 var i,j,k,p,q,r,ret,foo,bar,woo,i0,k0,p0,r0,s1,s2,s3,baz,accum;
41117 p = x.length; q = y[0].length;
41118 ret = Array(q);
41119 for(k=q-1;k>=0;k--) {
41120 woo = x[p-1]*y[p-1][k];
41121 for(j=p-2;j>=1;j-=2) {
41122 i0 = j-1;
41123 woo += x[j]*y[j][k] + x[i0]*y[i0][k];
41124 }
41125 if(j===0) { woo += x[0]*y[0][k]; }
41126 ret[k] = woo;
41127 }
41128 return ret;
41129}
41130
41131numeric.dotVV = function dotVV(x,y) {
41132 var i,n=x.length,i1,ret = x[n-1]*y[n-1];
41133 for(i=n-2;i>=1;i-=2) {
41134 i1 = i-1;
41135 ret += x[i]*y[i] + x[i1]*y[i1];
41136 }
41137 if(i===0) { ret += x[0]*y[0]; }
41138 return ret;
41139}
41140
41141numeric.dot = function dot(x,y) {
41142 var d = numeric.dim;
41143 switch(d(x).length*1000+d(y).length) {
41144 case 2002:
41145 if(y.length < 10) return numeric.dotMMsmall(x,y);
41146 else return numeric.dotMMbig(x,y);
41147 case 2001: return numeric.dotMV(x,y);
41148 case 1002: return numeric.dotVM(x,y);
41149 case 1001: return numeric.dotVV(x,y);
41150 case 1000: return numeric.mulVS(x,y);
41151 case 1: return numeric.mulSV(x,y);
41152 case 0: return x*y;
41153 default: throw new Error('numeric.dot only works on vectors and matrices');
41154 }
41155}
41156
41157numeric.diag = function diag(d) {
41158 var i,i1,j,n = d.length, A = Array(n), Ai;
41159 for(i=n-1;i>=0;i--) {
41160 Ai = Array(n);
41161 i1 = i+2;
41162 for(j=n-1;j>=i1;j-=2) {
41163 Ai[j] = 0;
41164 Ai[j-1] = 0;
41165 }
41166 if(j>i) { Ai[j] = 0; }
41167 Ai[i] = d[i];
41168 for(j=i-1;j>=1;j-=2) {
41169 Ai[j] = 0;
41170 Ai[j-1] = 0;
41171 }
41172 if(j===0) { Ai[0] = 0; }
41173 A[i] = Ai;
41174 }
41175 return A;
41176}
41177numeric.getDiag = function(A) {
41178 var n = Math.min(A.length,A[0].length),i,ret = Array(n);
41179 for(i=n-1;i>=1;--i) {
41180 ret[i] = A[i][i];
41181 --i;
41182 ret[i] = A[i][i];
41183 }
41184 if(i===0) {
41185 ret[0] = A[0][0];
41186 }
41187 return ret;
41188}
41189
41190numeric.identity = function identity(n) { return numeric.diag(numeric.rep([n],1)); }
41191numeric.pointwise = function pointwise(params,body,setup) {
41192 if(typeof setup === "undefined") { setup = ""; }
41193 var fun = [];
41194 var k;
41195 var avec = /\[i\]$/,p,thevec = '';
41196 var haveret = false;
41197 for(k=0;k<params.length;k++) {
41198 if(avec.test(params[k])) {
41199 p = params[k].substring(0,params[k].length-3);
41200 thevec = p;
41201 } else { p = params[k]; }
41202 if(p==='ret') haveret = true;
41203 fun.push(p);
41204 }
41205 fun[params.length] = '_s';
41206 fun[params.length+1] = '_k';
41207 fun[params.length+2] = (
41208 'if(typeof _s === "undefined") _s = numeric.dim('+thevec+');\n'+
41209 'if(typeof _k === "undefined") _k = 0;\n'+
41210 'var _n = _s[_k];\n'+
41211 'var i'+(haveret?'':', ret = Array(_n)')+';\n'+
41212 'if(_k < _s.length-1) {\n'+
41213 ' for(i=_n-1;i>=0;i--) ret[i] = arguments.callee('+params.join(',')+',_s,_k+1);\n'+
41214 ' return ret;\n'+
41215 '}\n'+
41216 setup+'\n'+
41217 'for(i=_n-1;i!==-1;--i) {\n'+
41218 ' '+body+'\n'+
41219 '}\n'+
41220 'return ret;'
41221 );
41222 return Function.apply(null,fun);
41223}
41224numeric.pointwise2 = function pointwise2(params,body,setup) {
41225 if(typeof setup === "undefined") { setup = ""; }
41226 var fun = [];
41227 var k;
41228 var avec = /\[i\]$/,p,thevec = '';
41229 var haveret = false;
41230 for(k=0;k<params.length;k++) {
41231 if(avec.test(params[k])) {
41232 p = params[k].substring(0,params[k].length-3);
41233 thevec = p;
41234 } else { p = params[k]; }
41235 if(p==='ret') haveret = true;
41236 fun.push(p);
41237 }
41238 fun[params.length] = (
41239 'var _n = '+thevec+'.length;\n'+
41240 'var i'+(haveret?'':', ret = Array(_n)')+';\n'+
41241 setup+'\n'+
41242 'for(i=_n-1;i!==-1;--i) {\n'+
41243 body+'\n'+
41244 '}\n'+
41245 'return ret;'
41246 );
41247 return Function.apply(null,fun);
41248}
41249numeric._biforeach = (function _biforeach(x,y,s,k,f) {
41250 if(k === s.length-1) { f(x,y); return; }
41251 var i,n=s[k];
41252 for(i=n-1;i>=0;i--) { _biforeach(typeof x==="object"?x[i]:x,typeof y==="object"?y[i]:y,s,k+1,f); }
41253});
41254numeric._biforeach2 = (function _biforeach2(x,y,s,k,f) {
41255 if(k === s.length-1) { return f(x,y); }
41256 var i,n=s[k],ret = Array(n);
41257 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); }
41258 return ret;
41259});
41260numeric._foreach = (function _foreach(x,s,k,f) {
41261 if(k === s.length-1) { f(x); return; }
41262 var i,n=s[k];
41263 for(i=n-1;i>=0;i--) { _foreach(x[i],s,k+1,f); }
41264});
41265numeric._foreach2 = (function _foreach2(x,s,k,f) {
41266 if(k === s.length-1) { return f(x); }
41267 var i,n=s[k], ret = Array(n);
41268 for(i=n-1;i>=0;i--) { ret[i] = _foreach2(x[i],s,k+1,f); }
41269 return ret;
41270});
41271
41272/*numeric.anyV = numeric.mapreduce('if(xi) return true;','false');
41273numeric.allV = numeric.mapreduce('if(!xi) return false;','true');
41274numeric.any = function(x) { if(typeof x.length === "undefined") return x; return numeric.anyV(x); }
41275numeric.all = function(x) { if(typeof x.length === "undefined") return x; return numeric.allV(x); }*/
41276
41277numeric.ops2 = {
41278 add: '+',
41279 sub: '-',
41280 mul: '*',
41281 div: '/',
41282 mod: '%',
41283 and: '&&',
41284 or: '||',
41285 eq: '===',
41286 neq: '!==',
41287 lt: '<',
41288 gt: '>',
41289 leq: '<=',
41290 geq: '>=',
41291 band: '&',
41292 bor: '|',
41293 bxor: '^',
41294 lshift: '<<',
41295 rshift: '>>',
41296 rrshift: '>>>'
41297};
41298numeric.opseq = {
41299 addeq: '+=',
41300 subeq: '-=',
41301 muleq: '*=',
41302 diveq: '/=',
41303 modeq: '%=',
41304 lshifteq: '<<=',
41305 rshifteq: '>>=',
41306 rrshifteq: '>>>=',
41307 bandeq: '&=',
41308 boreq: '|=',
41309 bxoreq: '^='
41310};
41311numeric.mathfuns = ['abs','acos','asin','atan','ceil','cos',
41312 'exp','floor','log','round','sin','sqrt','tan',
41313 'isNaN','isFinite'];
41314numeric.mathfuns2 = ['atan2','pow','max','min'];
41315numeric.ops1 = {
41316 neg: '-',
41317 not: '!',
41318 bnot: '~',
41319 clone: ''
41320};
41321numeric.mapreducers = {
41322 any: ['if(xi) return true;','var accum = false;'],
41323 all: ['if(!xi) return false;','var accum = true;'],
41324 sum: ['accum += xi;','var accum = 0;'],
41325 prod: ['accum *= xi;','var accum = 1;'],
41326 norm2Squared: ['accum += xi*xi;','var accum = 0;'],
41327 norminf: ['accum = max(accum,abs(xi));','var accum = 0, max = Math.max, abs = Math.abs;'],
41328 norm1: ['accum += abs(xi)','var accum = 0, abs = Math.abs;'],
41329 sup: ['accum = max(accum,xi);','var accum = -Infinity, max = Math.max;'],
41330 inf: ['accum = min(accum,xi);','var accum = Infinity, min = Math.min;']
41331};
41332
41333(function () {
41334 var i,o;
41335 for(i=0;i<numeric.mathfuns2.length;++i) {
41336 o = numeric.mathfuns2[i];
41337 numeric.ops2[o] = o;
41338 }
41339 for(i in numeric.ops2) {
41340 if(numeric.ops2.hasOwnProperty(i)) {
41341 o = numeric.ops2[i];
41342 var code, codeeq, setup = '';
41343 if(numeric.myIndexOf.call(numeric.mathfuns2,i)!==-1) {
41344 setup = 'var '+o+' = Math.'+o+';\n';
41345 code = function(r,x,y) { return r+' = '+o+'('+x+','+y+')'; };
41346 codeeq = function(x,y) { return x+' = '+o+'('+x+','+y+')'; };
41347 } else {
41348 code = function(r,x,y) { return r+' = '+x+' '+o+' '+y; };
41349 if(numeric.opseq.hasOwnProperty(i+'eq')) {
41350 codeeq = function(x,y) { return x+' '+o+'= '+y; };
41351 } else {
41352 codeeq = function(x,y) { return x+' = '+x+' '+o+' '+y; };
41353 }
41354 }
41355 numeric[i+'VV'] = numeric.pointwise2(['x[i]','y[i]'],code('ret[i]','x[i]','y[i]'),setup);
41356 numeric[i+'SV'] = numeric.pointwise2(['x','y[i]'],code('ret[i]','x','y[i]'),setup);
41357 numeric[i+'VS'] = numeric.pointwise2(['x[i]','y'],code('ret[i]','x[i]','y'),setup);
41358 numeric[i] = Function(
41359 'var n = arguments.length, i, x = arguments[0], y;\n'+
41360 'var VV = numeric.'+i+'VV, VS = numeric.'+i+'VS, SV = numeric.'+i+'SV;\n'+
41361 'var dim = numeric.dim;\n'+
41362 'for(i=1;i!==n;++i) { \n'+
41363 ' y = arguments[i];\n'+
41364 ' if(typeof x === "object") {\n'+
41365 ' if(typeof y === "object") x = numeric._biforeach2(x,y,dim(x),0,VV);\n'+
41366 ' else x = numeric._biforeach2(x,y,dim(x),0,VS);\n'+
41367 ' } else if(typeof y === "object") x = numeric._biforeach2(x,y,dim(y),0,SV);\n'+
41368 ' else '+codeeq('x','y')+'\n'+
41369 '}\nreturn x;\n');
41370 numeric[o] = numeric[i];
41371 numeric[i+'eqV'] = numeric.pointwise2(['ret[i]','x[i]'], codeeq('ret[i]','x[i]'),setup);
41372 numeric[i+'eqS'] = numeric.pointwise2(['ret[i]','x'], codeeq('ret[i]','x'),setup);
41373 numeric[i+'eq'] = Function(
41374 'var n = arguments.length, i, x = arguments[0], y;\n'+
41375 'var V = numeric.'+i+'eqV, S = numeric.'+i+'eqS\n'+
41376 'var s = numeric.dim(x);\n'+
41377 'for(i=1;i!==n;++i) { \n'+
41378 ' y = arguments[i];\n'+
41379 ' if(typeof y === "object") numeric._biforeach(x,y,s,0,V);\n'+
41380 ' else numeric._biforeach(x,y,s,0,S);\n'+
41381 '}\nreturn x;\n');
41382 }
41383 }
41384 for(i=0;i<numeric.mathfuns2.length;++i) {
41385 o = numeric.mathfuns2[i];
41386 delete numeric.ops2[o];
41387 }
41388 for(i=0;i<numeric.mathfuns.length;++i) {
41389 o = numeric.mathfuns[i];
41390 numeric.ops1[o] = o;
41391 }
41392 for(i in numeric.ops1) {
41393 if(numeric.ops1.hasOwnProperty(i)) {
41394 setup = '';
41395 o = numeric.ops1[i];
41396 if(numeric.myIndexOf.call(numeric.mathfuns,i)!==-1) {
41397 if(Math.hasOwnProperty(o)) setup = 'var '+o+' = Math.'+o+';\n';
41398 }
41399 numeric[i+'eqV'] = numeric.pointwise2(['ret[i]'],'ret[i] = '+o+'(ret[i]);',setup);
41400 numeric[i+'eq'] = Function('x',
41401 'if(typeof x !== "object") return '+o+'x\n'+
41402 'var i;\n'+
41403 'var V = numeric.'+i+'eqV;\n'+
41404 'var s = numeric.dim(x);\n'+
41405 'numeric._foreach(x,s,0,V);\n'+
41406 'return x;\n');
41407 numeric[i+'V'] = numeric.pointwise2(['x[i]'],'ret[i] = '+o+'(x[i]);',setup);
41408 numeric[i] = Function('x',
41409 'if(typeof x !== "object") return '+o+'(x)\n'+
41410 'var i;\n'+
41411 'var V = numeric.'+i+'V;\n'+
41412 'var s = numeric.dim(x);\n'+
41413 'return numeric._foreach2(x,s,0,V);\n');
41414 }
41415 }
41416 for(i=0;i<numeric.mathfuns.length;++i) {
41417 o = numeric.mathfuns[i];
41418 delete numeric.ops1[o];
41419 }
41420 for(i in numeric.mapreducers) {
41421 if(numeric.mapreducers.hasOwnProperty(i)) {
41422 o = numeric.mapreducers[i];
41423 numeric[i+'V'] = numeric.mapreduce2(o[0],o[1]);
41424 numeric[i] = Function('x','s','k',
41425 o[1]+
41426 'if(typeof x !== "object") {'+
41427 ' xi = x;\n'+
41428 o[0]+';\n'+
41429 ' return accum;\n'+
41430 '}'+
41431 'if(typeof s === "undefined") s = numeric.dim(x);\n'+
41432 'if(typeof k === "undefined") k = 0;\n'+
41433 'if(k === s.length-1) return numeric.'+i+'V(x);\n'+
41434 'var xi;\n'+
41435 'var n = x.length, i;\n'+
41436 'for(i=n-1;i!==-1;--i) {\n'+
41437 ' xi = arguments.callee(x[i]);\n'+
41438 o[0]+';\n'+
41439 '}\n'+
41440 'return accum;\n');
41441 }
41442 }
41443}());
41444
41445numeric.truncVV = numeric.pointwise(['x[i]','y[i]'],'ret[i] = round(x[i]/y[i])*y[i];','var round = Math.round;');
41446numeric.truncVS = numeric.pointwise(['x[i]','y'],'ret[i] = round(x[i]/y)*y;','var round = Math.round;');
41447numeric.truncSV = numeric.pointwise(['x','y[i]'],'ret[i] = round(x/y[i])*y[i];','var round = Math.round;');
41448numeric.trunc = function trunc(x,y) {
41449 if(typeof x === "object") {
41450 if(typeof y === "object") return numeric.truncVV(x,y);
41451 return numeric.truncVS(x,y);
41452 }
41453 if (typeof y === "object") return numeric.truncSV(x,y);
41454 return Math.round(x/y)*y;
41455}
41456
41457numeric.inv = function inv(x) {
41458 var s = numeric.dim(x), abs = Math.abs, m = s[0], n = s[1];
41459 var A = numeric.clone(x), Ai, Aj;
41460 var I = numeric.identity(m), Ii, Ij;
41461 var i,j,k,x;
41462 for(j=0;j<n;++j) {
41463 var i0 = -1;
41464 var v0 = -1;
41465 for(i=j;i!==m;++i) { k = abs(A[i][j]); if(k>v0) { i0 = i; v0 = k; } }
41466 Aj = A[i0]; A[i0] = A[j]; A[j] = Aj;
41467 Ij = I[i0]; I[i0] = I[j]; I[j] = Ij;
41468 x = Aj[j];
41469 for(k=j;k!==n;++k) Aj[k] /= x;
41470 for(k=n-1;k!==-1;--k) Ij[k] /= x;
41471 for(i=m-1;i!==-1;--i) {
41472 if(i!==j) {
41473 Ai = A[i];
41474 Ii = I[i];
41475 x = Ai[j];
41476 for(k=j+1;k!==n;++k) Ai[k] -= Aj[k]*x;
41477 for(k=n-1;k>0;--k) { Ii[k] -= Ij[k]*x; --k; Ii[k] -= Ij[k]*x; }
41478 if(k===0) Ii[0] -= Ij[0]*x;
41479 }
41480 }
41481 }
41482 return I;
41483}
41484
41485numeric.det = function det(x) {
41486 var s = numeric.dim(x);
41487 if(s.length !== 2 || s[0] !== s[1]) { throw new Error('numeric: det() only works on square matrices'); }
41488 var n = s[0], ret = 1,i,j,k,A = numeric.clone(x),Aj,Ai,alpha,temp,k1,k2,k3;
41489 for(j=0;j<n-1;j++) {
41490 k=j;
41491 for(i=j+1;i<n;i++) { if(Math.abs(A[i][j]) > Math.abs(A[k][j])) { k = i; } }
41492 if(k !== j) {
41493 temp = A[k]; A[k] = A[j]; A[j] = temp;
41494 ret *= -1;
41495 }
41496 Aj = A[j];
41497 for(i=j+1;i<n;i++) {
41498 Ai = A[i];
41499 alpha = Ai[j]/Aj[j];
41500 for(k=j+1;k<n-1;k+=2) {
41501 k1 = k+1;
41502 Ai[k] -= Aj[k]*alpha;
41503 Ai[k1] -= Aj[k1]*alpha;
41504 }
41505 if(k!==n) { Ai[k] -= Aj[k]*alpha; }
41506 }
41507 if(Aj[j] === 0) { return 0; }
41508 ret *= Aj[j];
41509 }
41510 return ret*A[j][j];
41511}
41512
41513numeric.transpose = function transpose(x) {
41514 var i,j,m = x.length,n = x[0].length, ret=Array(n),A0,A1,Bj;
41515 for(j=0;j<n;j++) ret[j] = Array(m);
41516 for(i=m-1;i>=1;i-=2) {
41517 A1 = x[i];
41518 A0 = x[i-1];
41519 for(j=n-1;j>=1;--j) {
41520 Bj = ret[j]; Bj[i] = A1[j]; Bj[i-1] = A0[j];
41521 --j;
41522 Bj = ret[j]; Bj[i] = A1[j]; Bj[i-1] = A0[j];
41523 }
41524 if(j===0) {
41525 Bj = ret[0]; Bj[i] = A1[0]; Bj[i-1] = A0[0];
41526 }
41527 }
41528 if(i===0) {
41529 A0 = x[0];
41530 for(j=n-1;j>=1;--j) {
41531 ret[j][0] = A0[j];
41532 --j;
41533 ret[j][0] = A0[j];
41534 }
41535 if(j===0) { ret[0][0] = A0[0]; }
41536 }
41537 return ret;
41538}
41539numeric.negtranspose = function negtranspose(x) {
41540 var i,j,m = x.length,n = x[0].length, ret=Array(n),A0,A1,Bj;
41541 for(j=0;j<n;j++) ret[j] = Array(m);
41542 for(i=m-1;i>=1;i-=2) {
41543 A1 = x[i];
41544 A0 = x[i-1];
41545 for(j=n-1;j>=1;--j) {
41546 Bj = ret[j]; Bj[i] = -A1[j]; Bj[i-1] = -A0[j];
41547 --j;
41548 Bj = ret[j]; Bj[i] = -A1[j]; Bj[i-1] = -A0[j];
41549 }
41550 if(j===0) {
41551 Bj = ret[0]; Bj[i] = -A1[0]; Bj[i-1] = -A0[0];
41552 }
41553 }
41554 if(i===0) {
41555 A0 = x[0];
41556 for(j=n-1;j>=1;--j) {
41557 ret[j][0] = -A0[j];
41558 --j;
41559 ret[j][0] = -A0[j];
41560 }
41561 if(j===0) { ret[0][0] = -A0[0]; }
41562 }
41563 return ret;
41564}
41565
41566numeric._random = function _random(s,k) {
41567 var i,n=s[k],ret=Array(n), rnd;
41568 if(k === s.length-1) {
41569 rnd = Math.random;
41570 for(i=n-1;i>=1;i-=2) {
41571 ret[i] = rnd();
41572 ret[i-1] = rnd();
41573 }
41574 if(i===0) { ret[0] = rnd(); }
41575 return ret;
41576 }
41577 for(i=n-1;i>=0;i--) ret[i] = _random(s,k+1);
41578 return ret;
41579}
41580numeric.random = function random(s) { return numeric._random(s,0); }
41581
41582numeric.norm2 = function norm2(x) { return Math.sqrt(numeric.norm2Squared(x)); }
41583
41584numeric.linspace = function linspace(a,b,n) {
41585 if(typeof n === "undefined") n = Math.max(Math.round(b-a)+1,1);
41586 if(n<2) { return n===1?[a]:[]; }
41587 var i,ret = Array(n);
41588 n--;
41589 for(i=n;i>=0;i--) { ret[i] = (i*b+(n-i)*a)/n; }
41590 return ret;
41591}
41592
41593numeric.getBlock = function getBlock(x,from,to) {
41594 var s = numeric.dim(x);
41595 function foo(x,k) {
41596 var i,a = from[k], n = to[k]-a, ret = Array(n);
41597 if(k === s.length-1) {
41598 for(i=n;i>=0;i--) { ret[i] = x[i+a]; }
41599 return ret;
41600 }
41601 for(i=n;i>=0;i--) { ret[i] = foo(x[i+a],k+1); }
41602 return ret;
41603 }
41604 return foo(x,0);
41605}
41606
41607numeric.setBlock = function setBlock(x,from,to,B) {
41608 var s = numeric.dim(x);
41609 function foo(x,y,k) {
41610 var i,a = from[k], n = to[k]-a;
41611 if(k === s.length-1) { for(i=n;i>=0;i--) { x[i+a] = y[i]; } }
41612 for(i=n;i>=0;i--) { foo(x[i+a],y[i],k+1); }
41613 }
41614 foo(x,B,0);
41615 return x;
41616}
41617
41618numeric.getRange = function getRange(A,I,J) {
41619 var m = I.length, n = J.length;
41620 var i,j;
41621 var B = Array(m), Bi, AI;
41622 for(i=m-1;i!==-1;--i) {
41623 B[i] = Array(n);
41624 Bi = B[i];
41625 AI = A[I[i]];
41626 for(j=n-1;j!==-1;--j) Bi[j] = AI[J[j]];
41627 }
41628 return B;
41629}
41630
41631numeric.blockMatrix = function blockMatrix(X) {
41632 var s = numeric.dim(X);
41633 if(s.length<4) return numeric.blockMatrix([X]);
41634 var m=s[0],n=s[1],M,N,i,j,Xij;
41635 M = 0; N = 0;
41636 for(i=0;i<m;++i) M+=X[i][0].length;
41637 for(j=0;j<n;++j) N+=X[0][j][0].length;
41638 var Z = Array(M);
41639 for(i=0;i<M;++i) Z[i] = Array(N);
41640 var I=0,J,ZI,k,l,Xijk;
41641 for(i=0;i<m;++i) {
41642 J=N;
41643 for(j=n-1;j!==-1;--j) {
41644 Xij = X[i][j];
41645 J -= Xij[0].length;
41646 for(k=Xij.length-1;k!==-1;--k) {
41647 Xijk = Xij[k];
41648 ZI = Z[I+k];
41649 for(l = Xijk.length-1;l!==-1;--l) ZI[J+l] = Xijk[l];
41650 }
41651 }
41652 I += X[i][0].length;
41653 }
41654 return Z;
41655}
41656
41657numeric.tensor = function tensor(x,y) {
41658 if(typeof x === "number" || typeof y === "number") return numeric.mul(x,y);
41659 var s1 = numeric.dim(x), s2 = numeric.dim(y);
41660 if(s1.length !== 1 || s2.length !== 1) {
41661 throw new Error('numeric: tensor product is only defined for vectors');
41662 }
41663 var m = s1[0], n = s2[0], A = Array(m), Ai, i,j,xi;
41664 for(i=m-1;i>=0;i--) {
41665 Ai = Array(n);
41666 xi = x[i];
41667 for(j=n-1;j>=3;--j) {
41668 Ai[j] = xi * y[j];
41669 --j;
41670 Ai[j] = xi * y[j];
41671 --j;
41672 Ai[j] = xi * y[j];
41673 --j;
41674 Ai[j] = xi * y[j];
41675 }
41676 while(j>=0) { Ai[j] = xi * y[j]; --j; }
41677 A[i] = Ai;
41678 }
41679 return A;
41680}
41681
41682// 3. The Tensor type T
41683numeric.T = function T(x,y) { this.x = x; this.y = y; }
41684numeric.t = function t(x,y) { return new numeric.T(x,y); }
41685
41686numeric.Tbinop = function Tbinop(rr,rc,cr,cc,setup) {
41687 var io = numeric.indexOf;
41688 if(typeof setup !== "string") {
41689 var k;
41690 setup = '';
41691 for(k in numeric) {
41692 if(numeric.hasOwnProperty(k) && (rr.indexOf(k)>=0 || rc.indexOf(k)>=0 || cr.indexOf(k)>=0 || cc.indexOf(k)>=0) && k.length>1) {
41693 setup += 'var '+k+' = numeric.'+k+';\n';
41694 }
41695 }
41696 }
41697 return Function(['y'],
41698 'var x = this;\n'+
41699 'if(!(y instanceof numeric.T)) { y = new numeric.T(y); }\n'+
41700 setup+'\n'+
41701 'if(x.y) {'+
41702 ' if(y.y) {'+
41703 ' return new numeric.T('+cc+');\n'+
41704 ' }\n'+
41705 ' return new numeric.T('+cr+');\n'+
41706 '}\n'+
41707 'if(y.y) {\n'+
41708 ' return new numeric.T('+rc+');\n'+
41709 '}\n'+
41710 'return new numeric.T('+rr+');\n'
41711 );
41712}
41713
41714numeric.T.prototype.add = numeric.Tbinop(
41715 'add(x.x,y.x)',
41716 'add(x.x,y.x),y.y',
41717 'add(x.x,y.x),x.y',
41718 'add(x.x,y.x),add(x.y,y.y)');
41719numeric.T.prototype.sub = numeric.Tbinop(
41720 'sub(x.x,y.x)',
41721 'sub(x.x,y.x),neg(y.y)',
41722 'sub(x.x,y.x),x.y',
41723 'sub(x.x,y.x),sub(x.y,y.y)');
41724numeric.T.prototype.mul = numeric.Tbinop(
41725 'mul(x.x,y.x)',
41726 'mul(x.x,y.x),mul(x.x,y.y)',
41727 'mul(x.x,y.x),mul(x.y,y.x)',
41728 'sub(mul(x.x,y.x),mul(x.y,y.y)),add(mul(x.x,y.y),mul(x.y,y.x))');
41729
41730numeric.T.prototype.reciprocal = function reciprocal() {
41731 var mul = numeric.mul, div = numeric.div;
41732 if(this.y) {
41733 var d = numeric.add(mul(this.x,this.x),mul(this.y,this.y));
41734 return new numeric.T(div(this.x,d),div(numeric.neg(this.y),d));
41735 }
41736 return new T(div(1,this.x));
41737}
41738numeric.T.prototype.div = function div(y) {
41739 if(!(y instanceof numeric.T)) y = new numeric.T(y);
41740 if(y.y) { return this.mul(y.reciprocal()); }
41741 var div = numeric.div;
41742 if(this.y) { return new numeric.T(div(this.x,y.x),div(this.y,y.x)); }
41743 return new numeric.T(div(this.x,y.x));
41744}
41745numeric.T.prototype.dot = numeric.Tbinop(
41746 'dot(x.x,y.x)',
41747 'dot(x.x,y.x),dot(x.x,y.y)',
41748 'dot(x.x,y.x),dot(x.y,y.x)',
41749 'sub(dot(x.x,y.x),dot(x.y,y.y)),add(dot(x.x,y.y),dot(x.y,y.x))'
41750 );
41751numeric.T.prototype.transpose = function transpose() {
41752 var t = numeric.transpose, x = this.x, y = this.y;
41753 if(y) { return new numeric.T(t(x),t(y)); }
41754 return new numeric.T(t(x));
41755}
41756numeric.T.prototype.transjugate = function transjugate() {
41757 var t = numeric.transpose, x = this.x, y = this.y;
41758 if(y) { return new numeric.T(t(x),numeric.negtranspose(y)); }
41759 return new numeric.T(t(x));
41760}
41761numeric.Tunop = function Tunop(r,c,s) {
41762 if(typeof s !== "string") { s = ''; }
41763 return Function(
41764 'var x = this;\n'+
41765 s+'\n'+
41766 'if(x.y) {'+
41767 ' '+c+';\n'+
41768 '}\n'+
41769 r+';\n'
41770 );
41771}
41772
41773numeric.T.prototype.exp = numeric.Tunop(
41774 'return new numeric.T(ex)',
41775 'return new numeric.T(mul(cos(x.y),ex),mul(sin(x.y),ex))',
41776 'var ex = numeric.exp(x.x), cos = numeric.cos, sin = numeric.sin, mul = numeric.mul;');
41777numeric.T.prototype.conj = numeric.Tunop(
41778 'return new numeric.T(x.x);',
41779 'return new numeric.T(x.x,numeric.neg(x.y));');
41780numeric.T.prototype.neg = numeric.Tunop(
41781 'return new numeric.T(neg(x.x));',
41782 'return new numeric.T(neg(x.x),neg(x.y));',
41783 'var neg = numeric.neg;');
41784numeric.T.prototype.sin = numeric.Tunop(
41785 'return new numeric.T(numeric.sin(x.x))',
41786 'return x.exp().sub(x.neg().exp()).div(new numeric.T(0,2));');
41787numeric.T.prototype.cos = numeric.Tunop(
41788 'return new numeric.T(numeric.cos(x.x))',
41789 'return x.exp().add(x.neg().exp()).div(2);');
41790numeric.T.prototype.abs = numeric.Tunop(
41791 'return new numeric.T(numeric.abs(x.x));',
41792 'return new numeric.T(numeric.sqrt(numeric.add(mul(x.x,x.x),mul(x.y,x.y))));',
41793 'var mul = numeric.mul;');
41794numeric.T.prototype.log = numeric.Tunop(
41795 'return new numeric.T(numeric.log(x.x));',
41796 'var theta = new numeric.T(numeric.atan2(x.y,x.x)), r = x.abs();\n'+
41797 'return new numeric.T(numeric.log(r.x),theta.x);');
41798numeric.T.prototype.norm2 = numeric.Tunop(
41799 'return numeric.norm2(x.x);',
41800 'var f = numeric.norm2Squared;\n'+
41801 'return Math.sqrt(f(x.x)+f(x.y));');
41802numeric.T.prototype.inv = function inv() {
41803 var A = this;
41804 if(typeof A.y === "undefined") { return new numeric.T(numeric.inv(A.x)); }
41805 var n = A.x.length, i, j, k;
41806 var Rx = numeric.identity(n),Ry = numeric.rep([n,n],0);
41807 var Ax = numeric.clone(A.x), Ay = numeric.clone(A.y);
41808 var Aix, Aiy, Ajx, Ajy, Rix, Riy, Rjx, Rjy;
41809 var i,j,k,d,d1,ax,ay,bx,by,temp;
41810 for(i=0;i<n;i++) {
41811 ax = Ax[i][i]; ay = Ay[i][i];
41812 d = ax*ax+ay*ay;
41813 k = i;
41814 for(j=i+1;j<n;j++) {
41815 ax = Ax[j][i]; ay = Ay[j][i];
41816 d1 = ax*ax+ay*ay;
41817 if(d1 > d) { k=j; d = d1; }
41818 }
41819 if(k!==i) {
41820 temp = Ax[i]; Ax[i] = Ax[k]; Ax[k] = temp;
41821 temp = Ay[i]; Ay[i] = Ay[k]; Ay[k] = temp;
41822 temp = Rx[i]; Rx[i] = Rx[k]; Rx[k] = temp;
41823 temp = Ry[i]; Ry[i] = Ry[k]; Ry[k] = temp;
41824 }
41825 Aix = Ax[i]; Aiy = Ay[i];
41826 Rix = Rx[i]; Riy = Ry[i];
41827 ax = Aix[i]; ay = Aiy[i];
41828 for(j=i+1;j<n;j++) {
41829 bx = Aix[j]; by = Aiy[j];
41830 Aix[j] = (bx*ax+by*ay)/d;
41831 Aiy[j] = (by*ax-bx*ay)/d;
41832 }
41833 for(j=0;j<n;j++) {
41834 bx = Rix[j]; by = Riy[j];
41835 Rix[j] = (bx*ax+by*ay)/d;
41836 Riy[j] = (by*ax-bx*ay)/d;
41837 }
41838 for(j=i+1;j<n;j++) {
41839 Ajx = Ax[j]; Ajy = Ay[j];
41840 Rjx = Rx[j]; Rjy = Ry[j];
41841 ax = Ajx[i]; ay = Ajy[i];
41842 for(k=i+1;k<n;k++) {
41843 bx = Aix[k]; by = Aiy[k];
41844 Ajx[k] -= bx*ax-by*ay;
41845 Ajy[k] -= by*ax+bx*ay;
41846 }
41847 for(k=0;k<n;k++) {
41848 bx = Rix[k]; by = Riy[k];
41849 Rjx[k] -= bx*ax-by*ay;
41850 Rjy[k] -= by*ax+bx*ay;
41851 }
41852 }
41853 }
41854 for(i=n-1;i>0;i--) {
41855 Rix = Rx[i]; Riy = Ry[i];
41856 for(j=i-1;j>=0;j--) {
41857 Rjx = Rx[j]; Rjy = Ry[j];
41858 ax = Ax[j][i]; ay = Ay[j][i];
41859 for(k=n-1;k>=0;k--) {
41860 bx = Rix[k]; by = Riy[k];
41861 Rjx[k] -= ax*bx - ay*by;
41862 Rjy[k] -= ax*by + ay*bx;
41863 }
41864 }
41865 }
41866 return new numeric.T(Rx,Ry);
41867}
41868numeric.T.prototype.get = function get(i) {
41869 var x = this.x, y = this.y, k = 0, ik, n = i.length;
41870 if(y) {
41871 while(k<n) {
41872 ik = i[k];
41873 x = x[ik];
41874 y = y[ik];
41875 k++;
41876 }
41877 return new numeric.T(x,y);
41878 }
41879 while(k<n) {
41880 ik = i[k];
41881 x = x[ik];
41882 k++;
41883 }
41884 return new numeric.T(x);
41885}
41886numeric.T.prototype.set = function set(i,v) {
41887 var x = this.x, y = this.y, k = 0, ik, n = i.length, vx = v.x, vy = v.y;
41888 if(n===0) {
41889 if(vy) { this.y = vy; }
41890 else if(y) { this.y = undefined; }
41891 this.x = x;
41892 return this;
41893 }
41894 if(vy) {
41895 if(y) { /* ok */ }
41896 else {
41897 y = numeric.rep(numeric.dim(x),0);
41898 this.y = y;
41899 }
41900 while(k<n-1) {
41901 ik = i[k];
41902 x = x[ik];
41903 y = y[ik];
41904 k++;
41905 }
41906 ik = i[k];
41907 x[ik] = vx;
41908 y[ik] = vy;
41909 return this;
41910 }
41911 if(y) {
41912 while(k<n-1) {
41913 ik = i[k];
41914 x = x[ik];
41915 y = y[ik];
41916 k++;
41917 }
41918 ik = i[k];
41919 x[ik] = vx;
41920 if(vx instanceof Array) y[ik] = numeric.rep(numeric.dim(vx),0);
41921 else y[ik] = 0;
41922 return this;
41923 }
41924 while(k<n-1) {
41925 ik = i[k];
41926 x = x[ik];
41927 k++;
41928 }
41929 ik = i[k];
41930 x[ik] = vx;
41931 return this;
41932}
41933numeric.T.prototype.getRows = function getRows(i0,i1) {
41934 var n = i1-i0+1, j;
41935 var rx = Array(n), ry, x = this.x, y = this.y;
41936 for(j=i0;j<=i1;j++) { rx[j-i0] = x[j]; }
41937 if(y) {
41938 ry = Array(n);
41939 for(j=i0;j<=i1;j++) { ry[j-i0] = y[j]; }
41940 return new numeric.T(rx,ry);
41941 }
41942 return new numeric.T(rx);
41943}
41944numeric.T.prototype.setRows = function setRows(i0,i1,A) {
41945 var j;
41946 var rx = this.x, ry = this.y, x = A.x, y = A.y;
41947 for(j=i0;j<=i1;j++) { rx[j] = x[j-i0]; }
41948 if(y) {
41949 if(!ry) { ry = numeric.rep(numeric.dim(rx),0); this.y = ry; }
41950 for(j=i0;j<=i1;j++) { ry[j] = y[j-i0]; }
41951 } else if(ry) {
41952 for(j=i0;j<=i1;j++) { ry[j] = numeric.rep([x[j-i0].length],0); }
41953 }
41954 return this;
41955}
41956numeric.T.prototype.getRow = function getRow(k) {
41957 var x = this.x, y = this.y;
41958 if(y) { return new numeric.T(x[k],y[k]); }
41959 return new numeric.T(x[k]);
41960}
41961numeric.T.prototype.setRow = function setRow(i,v) {
41962 var rx = this.x, ry = this.y, x = v.x, y = v.y;
41963 rx[i] = x;
41964 if(y) {
41965 if(!ry) { ry = numeric.rep(numeric.dim(rx),0); this.y = ry; }
41966 ry[i] = y;
41967 } else if(ry) {
41968 ry = numeric.rep([x.length],0);
41969 }
41970 return this;
41971}
41972
41973numeric.T.prototype.getBlock = function getBlock(from,to) {
41974 var x = this.x, y = this.y, b = numeric.getBlock;
41975 if(y) { return new numeric.T(b(x,from,to),b(y,from,to)); }
41976 return new numeric.T(b(x,from,to));
41977}
41978numeric.T.prototype.setBlock = function setBlock(from,to,A) {
41979 if(!(A instanceof numeric.T)) A = new numeric.T(A);
41980 var x = this.x, y = this.y, b = numeric.setBlock, Ax = A.x, Ay = A.y;
41981 if(Ay) {
41982 if(!y) { this.y = numeric.rep(numeric.dim(this),0); y = this.y; }
41983 b(x,from,to,Ax);
41984 b(y,from,to,Ay);
41985 return this;
41986 }
41987 b(x,from,to,Ax);
41988 if(y) b(y,from,to,numeric.rep(numeric.dim(Ax),0));
41989}
41990numeric.T.rep = function rep(s,v) {
41991 var T = numeric.T;
41992 if(!(v instanceof T)) v = new T(v);
41993 var x = v.x, y = v.y, r = numeric.rep;
41994 if(y) return new T(r(s,x),r(s,y));
41995 return new T(r(s,x));
41996}
41997numeric.T.diag = function diag(d) {
41998 if(!(d instanceof numeric.T)) d = new numeric.T(d);
41999 var x = d.x, y = d.y, diag = numeric.diag;
42000 if(y) return new numeric.T(diag(x),diag(y));
42001 return new numeric.T(diag(x));
42002}
42003numeric.T.eig = function eig() {
42004 if(this.y) { throw new Error('eig: not implemented for complex matrices.'); }
42005 return numeric.eig(this.x);
42006}
42007numeric.T.identity = function identity(n) { return new numeric.T(numeric.identity(n)); }
42008numeric.T.prototype.getDiag = function getDiag() {
42009 var n = numeric;
42010 var x = this.x, y = this.y;
42011 if(y) { return new n.T(n.getDiag(x),n.getDiag(y)); }
42012 return new n.T(n.getDiag(x));
42013}
42014
42015// 4. Eigenvalues of real matrices
42016
42017numeric.house = function house(x) {
42018 var v = numeric.clone(x);
42019 var s = x[0] >= 0 ? 1 : -1;
42020 var alpha = s*numeric.norm2(x);
42021 v[0] += alpha;
42022 var foo = numeric.norm2(v);
42023 if(foo === 0) { /* this should not happen */ throw new Error('eig: internal error'); }
42024 return numeric.div(v,foo);
42025}
42026
42027numeric.toUpperHessenberg = function toUpperHessenberg(me) {
42028 var s = numeric.dim(me);
42029 if(s.length !== 2 || s[0] !== s[1]) { throw new Error('numeric: toUpperHessenberg() only works on square matrices'); }
42030 var m = s[0], i,j,k,x,v,A = numeric.clone(me),B,C,Ai,Ci,Q = numeric.identity(m),Qi;
42031 for(j=0;j<m-2;j++) {
42032 x = Array(m-j-1);
42033 for(i=j+1;i<m;i++) { x[i-j-1] = A[i][j]; }
42034 if(numeric.norm2(x)>0) {
42035 v = numeric.house(x);
42036 B = numeric.getBlock(A,[j+1,j],[m-1,m-1]);
42037 C = numeric.tensor(v,numeric.dot(v,B));
42038 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]; }
42039 B = numeric.getBlock(A,[0,j+1],[m-1,m-1]);
42040 C = numeric.tensor(numeric.dot(B,v),v);
42041 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]; }
42042 B = Array(m-j-1);
42043 for(i=j+1;i<m;i++) B[i-j-1] = Q[i];
42044 C = numeric.tensor(v,numeric.dot(v,B));
42045 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]; }
42046 }
42047 }
42048 return {H:A, Q:Q};
42049}
42050
42051numeric.epsilon = 2.220446049250313e-16;
42052
42053numeric.QRFrancis = function(H,maxiter) {
42054 if(typeof maxiter === "undefined") { maxiter = 10000; }
42055 H = numeric.clone(H);
42056 var H0 = numeric.clone(H);
42057 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;
42058 if(m<3) { return {Q:Q, B:[ [0,m-1] ]}; }
42059 var epsilon = numeric.epsilon;
42060 for(iter=0;iter<maxiter;iter++) {
42061 for(j=0;j<m-1;j++) {
42062 if(Math.abs(H[j+1][j]) < epsilon*(Math.abs(H[j][j])+Math.abs(H[j+1][j+1]))) {
42063 var QH1 = numeric.QRFrancis(numeric.getBlock(H,[0,0],[j,j]),maxiter);
42064 var QH2 = numeric.QRFrancis(numeric.getBlock(H,[j+1,j+1],[m-1,m-1]),maxiter);
42065 B = Array(j+1);
42066 for(i=0;i<=j;i++) { B[i] = Q[i]; }
42067 C = numeric.dot(QH1.Q,B);
42068 for(i=0;i<=j;i++) { Q[i] = C[i]; }
42069 B = Array(m-j-1);
42070 for(i=j+1;i<m;i++) { B[i-j-1] = Q[i]; }
42071 C = numeric.dot(QH2.Q,B);
42072 for(i=j+1;i<m;i++) { Q[i] = C[i-j-1]; }
42073 return {Q:Q,B:QH1.B.concat(numeric.add(QH2.B,j+1))};
42074 }
42075 }
42076 a = H[m-2][m-2]; b = H[m-2][m-1];
42077 c = H[m-1][m-2]; d = H[m-1][m-1];
42078 tr = a+d;
42079 det = (a*d-b*c);
42080 Hloc = numeric.getBlock(H, [0,0], [2,2]);
42081 if(tr*tr>=4*det) {
42082 var s1,s2;
42083 s1 = 0.5*(tr+Math.sqrt(tr*tr-4*det));
42084 s2 = 0.5*(tr-Math.sqrt(tr*tr-4*det));
42085 Hloc = numeric.add(numeric.sub(numeric.dot(Hloc,Hloc),
42086 numeric.mul(Hloc,s1+s2)),
42087 numeric.diag(numeric.rep([3],s1*s2)));
42088 } else {
42089 Hloc = numeric.add(numeric.sub(numeric.dot(Hloc,Hloc),
42090 numeric.mul(Hloc,tr)),
42091 numeric.diag(numeric.rep([3],det)));
42092 }
42093 x = [Hloc[0][0],Hloc[1][0],Hloc[2][0]];
42094 v = numeric.house(x);
42095 B = [H[0],H[1],H[2]];
42096 C = numeric.tensor(v,numeric.dot(v,B));
42097 for(i=0;i<3;i++) { Hi = H[i]; Ci = C[i]; for(k=0;k<m;k++) Hi[k] -= 2*Ci[k]; }
42098 B = numeric.getBlock(H, [0,0],[m-1,2]);
42099 C = numeric.tensor(numeric.dot(B,v),v);
42100 for(i=0;i<m;i++) { Hi = H[i]; Ci = C[i]; for(k=0;k<3;k++) Hi[k] -= 2*Ci[k]; }
42101 B = [Q[0],Q[1],Q[2]];
42102 C = numeric.tensor(v,numeric.dot(v,B));
42103 for(i=0;i<3;i++) { Qi = Q[i]; Ci = C[i]; for(k=0;k<m;k++) Qi[k] -= 2*Ci[k]; }
42104 var J;
42105 for(j=0;j<m-2;j++) {
42106 for(k=j;k<=j+1;k++) {
42107 if(Math.abs(H[k+1][k]) < epsilon*(Math.abs(H[k][k])+Math.abs(H[k+1][k+1]))) {
42108 var QH1 = numeric.QRFrancis(numeric.getBlock(H,[0,0],[k,k]),maxiter);
42109 var QH2 = numeric.QRFrancis(numeric.getBlock(H,[k+1,k+1],[m-1,m-1]),maxiter);
42110 B = Array(k+1);
42111 for(i=0;i<=k;i++) { B[i] = Q[i]; }
42112 C = numeric.dot(QH1.Q,B);
42113 for(i=0;i<=k;i++) { Q[i] = C[i]; }
42114 B = Array(m-k-1);
42115 for(i=k+1;i<m;i++) { B[i-k-1] = Q[i]; }
42116 C = numeric.dot(QH2.Q,B);
42117 for(i=k+1;i<m;i++) { Q[i] = C[i-k-1]; }
42118 return {Q:Q,B:QH1.B.concat(numeric.add(QH2.B,k+1))};
42119 }
42120 }
42121 J = Math.min(m-1,j+3);
42122 x = Array(J-j);
42123 for(i=j+1;i<=J;i++) { x[i-j-1] = H[i][j]; }
42124 v = numeric.house(x);
42125 B = numeric.getBlock(H, [j+1,j],[J,m-1]);
42126 C = numeric.tensor(v,numeric.dot(v,B));
42127 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]; }
42128 B = numeric.getBlock(H, [0,j+1],[m-1,J]);
42129 C = numeric.tensor(numeric.dot(B,v),v);
42130 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]; }
42131 B = Array(J-j);
42132 for(i=j+1;i<=J;i++) B[i-j-1] = Q[i];
42133 C = numeric.tensor(v,numeric.dot(v,B));
42134 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]; }
42135 }
42136 }
42137 throw new Error('numeric: eigenvalue iteration does not converge -- increase maxiter?');
42138}
42139
42140numeric.eig = function eig(A,maxiter) {
42141 var QH = numeric.toUpperHessenberg(A);
42142 var QB = numeric.QRFrancis(QH.H,maxiter);
42143 var T = numeric.T;
42144 var n = A.length,i,k,flag = false,B = QB.B,H = numeric.dot(QB.Q,numeric.dot(QH.H,numeric.transpose(QB.Q)));
42145 var Q = new T(numeric.dot(QB.Q,QH.Q)),Q0;
42146 var m = B.length,j;
42147 var a,b,c,d,p1,p2,disc,x,y,p,q,n1,n2;
42148 var sqrt = Math.sqrt;
42149 for(k=0;k<m;k++) {
42150 i = B[k][0];
42151 if(i === B[k][1]) {
42152 // nothing
42153 } else {
42154 j = i+1;
42155 a = H[i][i];
42156 b = H[i][j];
42157 c = H[j][i];
42158 d = H[j][j];
42159 if(b === 0 && c === 0) continue;
42160 p1 = -a-d;
42161 p2 = a*d-b*c;
42162 disc = p1*p1-4*p2;
42163 if(disc>=0) {
42164 if(p1<0) x = -0.5*(p1-sqrt(disc));
42165 else x = -0.5*(p1+sqrt(disc));
42166 n1 = (a-x)*(a-x)+b*b;
42167 n2 = c*c+(d-x)*(d-x);
42168 if(n1>n2) {
42169 n1 = sqrt(n1);
42170 p = (a-x)/n1;
42171 q = b/n1;
42172 } else {
42173 n2 = sqrt(n2);
42174 p = c/n2;
42175 q = (d-x)/n2;
42176 }
42177 Q0 = new T([[q,-p],[p,q]]);
42178 Q.setRows(i,j,Q0.dot(Q.getRows(i,j)));
42179 } else {
42180 x = -0.5*p1;
42181 y = 0.5*sqrt(-disc);
42182 n1 = (a-x)*(a-x)+b*b;
42183 n2 = c*c+(d-x)*(d-x);
42184 if(n1>n2) {
42185 n1 = sqrt(n1+y*y);
42186 p = (a-x)/n1;
42187 q = b/n1;
42188 x = 0;
42189 y /= n1;
42190 } else {
42191 n2 = sqrt(n2+y*y);
42192 p = c/n2;
42193 q = (d-x)/n2;
42194 x = y/n2;
42195 y = 0;
42196 }
42197 Q0 = new T([[q,-p],[p,q]],[[x,y],[y,-x]]);
42198 Q.setRows(i,j,Q0.dot(Q.getRows(i,j)));
42199 }
42200 }
42201 }
42202 var R = Q.dot(A).dot(Q.transjugate()), n = A.length, E = numeric.T.identity(n);
42203 for(j=0;j<n;j++) {
42204 if(j>0) {
42205 for(k=j-1;k>=0;k--) {
42206 var Rk = R.get([k,k]), Rj = R.get([j,j]);
42207 if(numeric.neq(Rk.x,Rj.x) || numeric.neq(Rk.y,Rj.y)) {
42208 x = R.getRow(k).getBlock([k],[j-1]);
42209 y = E.getRow(j).getBlock([k],[j-1]);
42210 E.set([j,k],(R.get([k,j]).neg().sub(x.dot(y))).div(Rk.sub(Rj)));
42211 } else {
42212 E.setRow(j,E.getRow(k));
42213 continue;
42214 }
42215 }
42216 }
42217 }
42218 for(j=0;j<n;j++) {
42219 x = E.getRow(j);
42220 E.setRow(j,x.div(x.norm2()));
42221 }
42222 E = E.transpose();
42223 E = Q.transjugate().dot(E);
42224 return { lambda:R.getDiag(), E:E };
42225};
42226
42227// 5. Compressed Column Storage matrices
42228numeric.ccsSparse = function ccsSparse(A) {
42229 var m = A.length,n,foo, i,j, counts = [];
42230 for(i=m-1;i!==-1;--i) {
42231 foo = A[i];
42232 for(j in foo) {
42233 j = parseInt(j);
42234 while(j>=counts.length) counts[counts.length] = 0;
42235 if(foo[j]!==0) counts[j]++;
42236 }
42237 }
42238 var n = counts.length;
42239 var Ai = Array(n+1);
42240 Ai[0] = 0;
42241 for(i=0;i<n;++i) Ai[i+1] = Ai[i] + counts[i];
42242 var Aj = Array(Ai[n]), Av = Array(Ai[n]);
42243 for(i=m-1;i!==-1;--i) {
42244 foo = A[i];
42245 for(j in foo) {
42246 if(foo[j]!==0) {
42247 counts[j]--;
42248 Aj[Ai[j]+counts[j]] = i;
42249 Av[Ai[j]+counts[j]] = foo[j];
42250 }
42251 }
42252 }
42253 return [Ai,Aj,Av];
42254}
42255numeric.ccsFull = function ccsFull(A) {
42256 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;
42257 var B = numeric.rep([m,n],0);
42258 for(i=0;i<n;i++) {
42259 j0 = Ai[i];
42260 j1 = Ai[i+1];
42261 for(j=j0;j<j1;++j) { B[Aj[j]][i] = Av[j]; }
42262 }
42263 return B;
42264}
42265numeric.ccsTSolve = function ccsTSolve(A,b,x,bj,xj) {
42266 var Ai = A[0], Aj = A[1], Av = A[2],m = Ai.length-1, max = Math.max,n=0;
42267 if(typeof bj === "undefined") x = numeric.rep([m],0);
42268 if(typeof bj === "undefined") bj = numeric.linspace(0,x.length-1);
42269 if(typeof xj === "undefined") xj = [];
42270 function dfs(j) {
42271 var k;
42272 if(x[j] !== 0) return;
42273 x[j] = 1;
42274 for(k=Ai[j];k<Ai[j+1];++k) dfs(Aj[k]);
42275 xj[n] = j;
42276 ++n;
42277 }
42278 var i,j,j0,j1,k,l,l0,l1,a;
42279 for(i=bj.length-1;i!==-1;--i) { dfs(bj[i]); }
42280 xj.length = n;
42281 for(i=xj.length-1;i!==-1;--i) { x[xj[i]] = 0; }
42282 for(i=bj.length-1;i!==-1;--i) { j = bj[i]; x[j] = b[j]; }
42283 for(i=xj.length-1;i!==-1;--i) {
42284 j = xj[i];
42285 j0 = Ai[j];
42286 j1 = max(Ai[j+1],j0);
42287 for(k=j0;k!==j1;++k) { if(Aj[k] === j) { x[j] /= Av[k]; break; } }
42288 a = x[j];
42289 for(k=j0;k!==j1;++k) {
42290 l = Aj[k];
42291 if(l !== j) x[l] -= a*Av[k];
42292 }
42293 }
42294 return x;
42295}
42296numeric.ccsDFS = function ccsDFS(n) {
42297 this.k = Array(n);
42298 this.k1 = Array(n);
42299 this.j = Array(n);
42300}
42301numeric.ccsDFS.prototype.dfs = function dfs(J,Ai,Aj,x,xj,Pinv) {
42302 var m = 0,foo,n=xj.length;
42303 var k = this.k, k1 = this.k1, j = this.j,km,k11;
42304 if(x[J]!==0) return;
42305 x[J] = 1;
42306 j[0] = J;
42307 k[0] = km = Ai[J];
42308 k1[0] = k11 = Ai[J+1];
42309 while(1) {
42310 if(km >= k11) {
42311 xj[n] = j[m];
42312 if(m===0) return;
42313 ++n;
42314 --m;
42315 km = k[m];
42316 k11 = k1[m];
42317 } else {
42318 foo = Pinv[Aj[km]];
42319 if(x[foo] === 0) {
42320 x[foo] = 1;
42321 k[m] = km;
42322 ++m;
42323 j[m] = foo;
42324 km = Ai[foo];
42325 k1[m] = k11 = Ai[foo+1];
42326 } else ++km;
42327 }
42328 }
42329}
42330numeric.ccsLPSolve = function ccsLPSolve(A,B,x,xj,I,Pinv,dfs) {
42331 var Ai = A[0], Aj = A[1], Av = A[2],m = Ai.length-1, n=0;
42332 var Bi = B[0], Bj = B[1], Bv = B[2];
42333
42334 var i,i0,i1,j,J,j0,j1,k,l,l0,l1,a;
42335 i0 = Bi[I];
42336 i1 = Bi[I+1];
42337 xj.length = 0;
42338 for(i=i0;i<i1;++i) { dfs.dfs(Pinv[Bj[i]],Ai,Aj,x,xj,Pinv); }
42339 for(i=xj.length-1;i!==-1;--i) { x[xj[i]] = 0; }
42340 for(i=i0;i!==i1;++i) { j = Pinv[Bj[i]]; x[j] = Bv[i]; }
42341 for(i=xj.length-1;i!==-1;--i) {
42342 j = xj[i];
42343 j0 = Ai[j];
42344 j1 = Ai[j+1];
42345 for(k=j0;k<j1;++k) { if(Pinv[Aj[k]] === j) { x[j] /= Av[k]; break; } }
42346 a = x[j];
42347 for(k=j0;k<j1;++k) {
42348 l = Pinv[Aj[k]];
42349 if(l !== j) x[l] -= a*Av[k];
42350 }
42351 }
42352 return x;
42353}
42354numeric.ccsLUP1 = function ccsLUP1(A,threshold) {
42355 var m = A[0].length-1;
42356 var L = [numeric.rep([m+1],0),[],[]], U = [numeric.rep([m+1], 0),[],[]];
42357 var Li = L[0], Lj = L[1], Lv = L[2], Ui = U[0], Uj = U[1], Uv = U[2];
42358 var x = numeric.rep([m],0), xj = numeric.rep([m],0);
42359 var i,j,k,j0,j1,a,e,c,d,K;
42360 var sol = numeric.ccsLPSolve, max = Math.max, abs = Math.abs;
42361 var P = numeric.linspace(0,m-1),Pinv = numeric.linspace(0,m-1);
42362 var dfs = new numeric.ccsDFS(m);
42363 if(typeof threshold === "undefined") { threshold = 1; }
42364 for(i=0;i<m;++i) {
42365 sol(L,A,x,xj,i,Pinv,dfs);
42366 a = -1;
42367 e = -1;
42368 for(j=xj.length-1;j!==-1;--j) {
42369 k = xj[j];
42370 if(k <= i) continue;
42371 c = abs(x[k]);
42372 if(c > a) { e = k; a = c; }
42373 }
42374 if(abs(x[i])<threshold*a) {
42375 j = P[i];
42376 a = P[e];
42377 P[i] = a; Pinv[a] = i;
42378 P[e] = j; Pinv[j] = e;
42379 a = x[i]; x[i] = x[e]; x[e] = a;
42380 }
42381 a = Li[i];
42382 e = Ui[i];
42383 d = x[i];
42384 Lj[a] = P[i];
42385 Lv[a] = 1;
42386 ++a;
42387 for(j=xj.length-1;j!==-1;--j) {
42388 k = xj[j];
42389 c = x[k];
42390 xj[j] = 0;
42391 x[k] = 0;
42392 if(k<=i) { Uj[e] = k; Uv[e] = c; ++e; }
42393 else { Lj[a] = P[k]; Lv[a] = c/d; ++a; }
42394 }
42395 Li[i+1] = a;
42396 Ui[i+1] = e;
42397 }
42398 for(j=Lj.length-1;j!==-1;--j) { Lj[j] = Pinv[Lj[j]]; }
42399 return {L:L, U:U, P:P, Pinv:Pinv};
42400}
42401numeric.ccsDFS0 = function ccsDFS0(n) {
42402 this.k = Array(n);
42403 this.k1 = Array(n);
42404 this.j = Array(n);
42405}
42406numeric.ccsDFS0.prototype.dfs = function dfs(J,Ai,Aj,x,xj,Pinv,P) {
42407 var m = 0,foo,n=xj.length;
42408 var k = this.k, k1 = this.k1, j = this.j,km,k11;
42409 if(x[J]!==0) return;
42410 x[J] = 1;
42411 j[0] = J;
42412 k[0] = km = Ai[Pinv[J]];
42413 k1[0] = k11 = Ai[Pinv[J]+1];
42414 while(1) {
42415 if(isNaN(km)) throw new Error("Ow!");
42416 if(km >= k11) {
42417 xj[n] = Pinv[j[m]];
42418 if(m===0) return;
42419 ++n;
42420 --m;
42421 km = k[m];
42422 k11 = k1[m];
42423 } else {
42424 foo = Aj[km];
42425 if(x[foo] === 0) {
42426 x[foo] = 1;
42427 k[m] = km;
42428 ++m;
42429 j[m] = foo;
42430 foo = Pinv[foo];
42431 km = Ai[foo];
42432 k1[m] = k11 = Ai[foo+1];
42433 } else ++km;
42434 }
42435 }
42436}
42437numeric.ccsLPSolve0 = function ccsLPSolve0(A,B,y,xj,I,Pinv,P,dfs) {
42438 var Ai = A[0], Aj = A[1], Av = A[2],m = Ai.length-1, n=0;
42439 var Bi = B[0], Bj = B[1], Bv = B[2];
42440
42441 var i,i0,i1,j,J,j0,j1,k,l,l0,l1,a;
42442 i0 = Bi[I];
42443 i1 = Bi[I+1];
42444 xj.length = 0;
42445 for(i=i0;i<i1;++i) { dfs.dfs(Bj[i],Ai,Aj,y,xj,Pinv,P); }
42446 for(i=xj.length-1;i!==-1;--i) { j = xj[i]; y[P[j]] = 0; }
42447 for(i=i0;i!==i1;++i) { j = Bj[i]; y[j] = Bv[i]; }
42448 for(i=xj.length-1;i!==-1;--i) {
42449 j = xj[i];
42450 l = P[j];
42451 j0 = Ai[j];
42452 j1 = Ai[j+1];
42453 for(k=j0;k<j1;++k) { if(Aj[k] === l) { y[l] /= Av[k]; break; } }
42454 a = y[l];
42455 for(k=j0;k<j1;++k) y[Aj[k]] -= a*Av[k];
42456 y[l] = a;
42457 }
42458}
42459numeric.ccsLUP0 = function ccsLUP0(A,threshold) {
42460 var m = A[0].length-1;
42461 var L = [numeric.rep([m+1],0),[],[]], U = [numeric.rep([m+1], 0),[],[]];
42462 var Li = L[0], Lj = L[1], Lv = L[2], Ui = U[0], Uj = U[1], Uv = U[2];
42463 var y = numeric.rep([m],0), xj = numeric.rep([m],0);
42464 var i,j,k,j0,j1,a,e,c,d,K;
42465 var sol = numeric.ccsLPSolve0, max = Math.max, abs = Math.abs;
42466 var P = numeric.linspace(0,m-1),Pinv = numeric.linspace(0,m-1);
42467 var dfs = new numeric.ccsDFS0(m);
42468 if(typeof threshold === "undefined") { threshold = 1; }
42469 for(i=0;i<m;++i) {
42470 sol(L,A,y,xj,i,Pinv,P,dfs);
42471 a = -1;
42472 e = -1;
42473 for(j=xj.length-1;j!==-1;--j) {
42474 k = xj[j];
42475 if(k <= i) continue;
42476 c = abs(y[P[k]]);
42477 if(c > a) { e = k; a = c; }
42478 }
42479 if(abs(y[P[i]])<threshold*a) {
42480 j = P[i];
42481 a = P[e];
42482 P[i] = a; Pinv[a] = i;
42483 P[e] = j; Pinv[j] = e;
42484 }
42485 a = Li[i];
42486 e = Ui[i];
42487 d = y[P[i]];
42488 Lj[a] = P[i];
42489 Lv[a] = 1;
42490 ++a;
42491 for(j=xj.length-1;j!==-1;--j) {
42492 k = xj[j];
42493 c = y[P[k]];
42494 xj[j] = 0;
42495 y[P[k]] = 0;
42496 if(k<=i) { Uj[e] = k; Uv[e] = c; ++e; }
42497 else { Lj[a] = P[k]; Lv[a] = c/d; ++a; }
42498 }
42499 Li[i+1] = a;
42500 Ui[i+1] = e;
42501 }
42502 for(j=Lj.length-1;j!==-1;--j) { Lj[j] = Pinv[Lj[j]]; }
42503 return {L:L, U:U, P:P, Pinv:Pinv};
42504}
42505numeric.ccsLUP = numeric.ccsLUP0;
42506
42507numeric.ccsDim = function ccsDim(A) { return [numeric.sup(A[1])+1,A[0].length-1]; }
42508numeric.ccsGetBlock = function ccsGetBlock(A,i,j) {
42509 var s = numeric.ccsDim(A),m=s[0],n=s[1];
42510 if(typeof i === "undefined") { i = numeric.linspace(0,m-1); }
42511 else if(typeof i === "number") { i = [i]; }
42512 if(typeof j === "undefined") { j = numeric.linspace(0,n-1); }
42513 else if(typeof j === "number") { j = [j]; }
42514 var p,p0,p1,P = i.length,q,Q = j.length,r,jq,ip;
42515 var Bi = numeric.rep([n],0), Bj=[], Bv=[], B = [Bi,Bj,Bv];
42516 var Ai = A[0], Aj = A[1], Av = A[2];
42517 var x = numeric.rep([m],0),count=0,flags = numeric.rep([m],0);
42518 for(q=0;q<Q;++q) {
42519 jq = j[q];
42520 var q0 = Ai[jq];
42521 var q1 = Ai[jq+1];
42522 for(p=q0;p<q1;++p) {
42523 r = Aj[p];
42524 flags[r] = 1;
42525 x[r] = Av[p];
42526 }
42527 for(p=0;p<P;++p) {
42528 ip = i[p];
42529 if(flags[ip]) {
42530 Bj[count] = p;
42531 Bv[count] = x[i[p]];
42532 ++count;
42533 }
42534 }
42535 for(p=q0;p<q1;++p) {
42536 r = Aj[p];
42537 flags[r] = 0;
42538 }
42539 Bi[q+1] = count;
42540 }
42541 return B;
42542}
42543
42544numeric.ccsDot = function ccsDot(A,B) {
42545 var Ai = A[0], Aj = A[1], Av = A[2];
42546 var Bi = B[0], Bj = B[1], Bv = B[2];
42547 var sA = numeric.ccsDim(A), sB = numeric.ccsDim(B);
42548 var m = sA[0], n = sA[1], o = sB[1];
42549 var x = numeric.rep([m],0), flags = numeric.rep([m],0), xj = Array(m);
42550 var Ci = numeric.rep([o],0), Cj = [], Cv = [], C = [Ci,Cj,Cv];
42551 var i,j,k,j0,j1,i0,i1,l,p,a,b;
42552 for(k=0;k!==o;++k) {
42553 j0 = Bi[k];
42554 j1 = Bi[k+1];
42555 p = 0;
42556 for(j=j0;j<j1;++j) {
42557 a = Bj[j];
42558 b = Bv[j];
42559 i0 = Ai[a];
42560 i1 = Ai[a+1];
42561 for(i=i0;i<i1;++i) {
42562 l = Aj[i];
42563 if(flags[l]===0) {
42564 xj[p] = l;
42565 flags[l] = 1;
42566 p = p+1;
42567 }
42568 x[l] = x[l] + Av[i]*b;
42569 }
42570 }
42571 j0 = Ci[k];
42572 j1 = j0+p;
42573 Ci[k+1] = j1;
42574 for(j=p-1;j!==-1;--j) {
42575 b = j0+j;
42576 i = xj[j];
42577 Cj[b] = i;
42578 Cv[b] = x[i];
42579 flags[i] = 0;
42580 x[i] = 0;
42581 }
42582 Ci[k+1] = Ci[k]+p;
42583 }
42584 return C;
42585}
42586
42587numeric.ccsLUPSolve = function ccsLUPSolve(LUP,B) {
42588 var L = LUP.L, U = LUP.U, P = LUP.P;
42589 var Bi = B[0];
42590 var flag = false;
42591 if(typeof Bi !== "object") { B = [[0,B.length],numeric.linspace(0,B.length-1),B]; Bi = B[0]; flag = true; }
42592 var Bj = B[1], Bv = B[2];
42593 var n = L[0].length-1, m = Bi.length-1;
42594 var x = numeric.rep([n],0), xj = Array(n);
42595 var b = numeric.rep([n],0), bj = Array(n);
42596 var Xi = numeric.rep([m+1],0), Xj = [], Xv = [];
42597 var sol = numeric.ccsTSolve;
42598 var i,j,j0,j1,k,J,N=0;
42599 for(i=0;i<m;++i) {
42600 k = 0;
42601 j0 = Bi[i];
42602 j1 = Bi[i+1];
42603 for(j=j0;j<j1;++j) {
42604 J = LUP.Pinv[Bj[j]];
42605 bj[k] = J;
42606 b[J] = Bv[j];
42607 ++k;
42608 }
42609 bj.length = k;
42610 sol(L,b,x,bj,xj);
42611 for(j=bj.length-1;j!==-1;--j) b[bj[j]] = 0;
42612 sol(U,x,b,xj,bj);
42613 if(flag) return b;
42614 for(j=xj.length-1;j!==-1;--j) x[xj[j]] = 0;
42615 for(j=bj.length-1;j!==-1;--j) {
42616 J = bj[j];
42617 Xj[N] = J;
42618 Xv[N] = b[J];
42619 b[J] = 0;
42620 ++N;
42621 }
42622 Xi[i+1] = N;
42623 }
42624 return [Xi,Xj,Xv];
42625}
42626
42627numeric.ccsbinop = function ccsbinop(body,setup) {
42628 if(typeof setup === "undefined") setup='';
42629 return Function('X','Y',
42630 'var Xi = X[0], Xj = X[1], Xv = X[2];\n'+
42631 'var Yi = Y[0], Yj = Y[1], Yv = Y[2];\n'+
42632 'var n = Xi.length-1,m = Math.max(numeric.sup(Xj),numeric.sup(Yj))+1;\n'+
42633 'var Zi = numeric.rep([n+1],0), Zj = [], Zv = [];\n'+
42634 'var x = numeric.rep([m],0),y = numeric.rep([m],0);\n'+
42635 'var xk,yk,zk;\n'+
42636 'var i,j,j0,j1,k,p=0;\n'+
42637 setup+
42638 'for(i=0;i<n;++i) {\n'+
42639 ' j0 = Xi[i]; j1 = Xi[i+1];\n'+
42640 ' for(j=j0;j!==j1;++j) {\n'+
42641 ' k = Xj[j];\n'+
42642 ' x[k] = 1;\n'+
42643 ' Zj[p] = k;\n'+
42644 ' ++p;\n'+
42645 ' }\n'+
42646 ' j0 = Yi[i]; j1 = Yi[i+1];\n'+
42647 ' for(j=j0;j!==j1;++j) {\n'+
42648 ' k = Yj[j];\n'+
42649 ' y[k] = Yv[j];\n'+
42650 ' if(x[k] === 0) {\n'+
42651 ' Zj[p] = k;\n'+
42652 ' ++p;\n'+
42653 ' }\n'+
42654 ' }\n'+
42655 ' Zi[i+1] = p;\n'+
42656 ' j0 = Xi[i]; j1 = Xi[i+1];\n'+
42657 ' for(j=j0;j!==j1;++j) x[Xj[j]] = Xv[j];\n'+
42658 ' j0 = Zi[i]; j1 = Zi[i+1];\n'+
42659 ' for(j=j0;j!==j1;++j) {\n'+
42660 ' k = Zj[j];\n'+
42661 ' xk = x[k];\n'+
42662 ' yk = y[k];\n'+
42663 body+'\n'+
42664 ' Zv[j] = zk;\n'+
42665 ' }\n'+
42666 ' j0 = Xi[i]; j1 = Xi[i+1];\n'+
42667 ' for(j=j0;j!==j1;++j) x[Xj[j]] = 0;\n'+
42668 ' j0 = Yi[i]; j1 = Yi[i+1];\n'+
42669 ' for(j=j0;j!==j1;++j) y[Yj[j]] = 0;\n'+
42670 '}\n'+
42671 'return [Zi,Zj,Zv];'
42672 );
42673};
42674
42675(function() {
42676 var k,A,B,C;
42677 for(k in numeric.ops2) {
42678 if(isFinite(eval('1'+numeric.ops2[k]+'0'))) A = '[Y[0],Y[1],numeric.'+k+'(X,Y[2])]';
42679 else A = 'NaN';
42680 if(isFinite(eval('0'+numeric.ops2[k]+'1'))) B = '[X[0],X[1],numeric.'+k+'(X[2],Y)]';
42681 else B = 'NaN';
42682 if(isFinite(eval('1'+numeric.ops2[k]+'0')) && isFinite(eval('0'+numeric.ops2[k]+'1'))) C = 'numeric.ccs'+k+'MM(X,Y)';
42683 else C = 'NaN';
42684 numeric['ccs'+k+'MM'] = numeric.ccsbinop('zk = xk '+numeric.ops2[k]+'yk;');
42685 numeric['ccs'+k] = Function('X','Y',
42686 'if(typeof X === "number") return '+A+';\n'+
42687 'if(typeof Y === "number") return '+B+';\n'+
42688 'return '+C+';\n'
42689 );
42690 }
42691}());
42692
42693numeric.ccsScatter = function ccsScatter(A) {
42694 var Ai = A[0], Aj = A[1], Av = A[2];
42695 var n = numeric.sup(Aj)+1,m=Ai.length;
42696 var Ri = numeric.rep([n],0),Rj=Array(m), Rv = Array(m);
42697 var counts = numeric.rep([n],0),i;
42698 for(i=0;i<m;++i) counts[Aj[i]]++;
42699 for(i=0;i<n;++i) Ri[i+1] = Ri[i] + counts[i];
42700 var ptr = Ri.slice(0),k,Aii;
42701 for(i=0;i<m;++i) {
42702 Aii = Aj[i];
42703 k = ptr[Aii];
42704 Rj[k] = Ai[i];
42705 Rv[k] = Av[i];
42706 ptr[Aii]=ptr[Aii]+1;
42707 }
42708 return [Ri,Rj,Rv];
42709}
42710
42711numeric.ccsGather = function ccsGather(A) {
42712 var Ai = A[0], Aj = A[1], Av = A[2];
42713 var n = Ai.length-1,m = Aj.length;
42714 var Ri = Array(m), Rj = Array(m), Rv = Array(m);
42715 var i,j,j0,j1,p;
42716 p=0;
42717 for(i=0;i<n;++i) {
42718 j0 = Ai[i];
42719 j1 = Ai[i+1];
42720 for(j=j0;j!==j1;++j) {
42721 Rj[p] = i;
42722 Ri[p] = Aj[j];
42723 Rv[p] = Av[j];
42724 ++p;
42725 }
42726 }
42727 return [Ri,Rj,Rv];
42728}
42729
42730// The following sparse linear algebra routines are deprecated.
42731
42732numeric.sdim = function dim(A,ret,k) {
42733 if(typeof ret === "undefined") { ret = []; }
42734 if(typeof A !== "object") return ret;
42735 if(typeof k === "undefined") { k=0; }
42736 if(!(k in ret)) { ret[k] = 0; }
42737 if(A.length > ret[k]) ret[k] = A.length;
42738 var i;
42739 for(i in A) {
42740 if(A.hasOwnProperty(i)) dim(A[i],ret,k+1);
42741 }
42742 return ret;
42743};
42744
42745numeric.sclone = function clone(A,k,n) {
42746 if(typeof k === "undefined") { k=0; }
42747 if(typeof n === "undefined") { n = numeric.sdim(A).length; }
42748 var i,ret = Array(A.length);
42749 if(k === n-1) {
42750 for(i in A) { if(A.hasOwnProperty(i)) ret[i] = A[i]; }
42751 return ret;
42752 }
42753 for(i in A) {
42754 if(A.hasOwnProperty(i)) ret[i] = clone(A[i],k+1,n);
42755 }
42756 return ret;
42757}
42758
42759numeric.sdiag = function diag(d) {
42760 var n = d.length,i,ret = Array(n),i1,i2,i3;
42761 for(i=n-1;i>=1;i-=2) {
42762 i1 = i-1;
42763 ret[i] = []; ret[i][i] = d[i];
42764 ret[i1] = []; ret[i1][i1] = d[i1];
42765 }
42766 if(i===0) { ret[0] = []; ret[0][0] = d[i]; }
42767 return ret;
42768}
42769
42770numeric.sidentity = function identity(n) { return numeric.sdiag(numeric.rep([n],1)); }
42771
42772numeric.stranspose = function transpose(A) {
42773 var ret = [], n = A.length, i,j,Ai;
42774 for(i in A) {
42775 if(!(A.hasOwnProperty(i))) continue;
42776 Ai = A[i];
42777 for(j in Ai) {
42778 if(!(Ai.hasOwnProperty(j))) continue;
42779 if(typeof ret[j] !== "object") { ret[j] = []; }
42780 ret[j][i] = Ai[j];
42781 }
42782 }
42783 return ret;
42784}
42785
42786numeric.sLUP = function LUP(A,tol) {
42787 throw new Error("The function numeric.sLUP had a bug in it and has been removed. Please use the new numeric.ccsLUP function instead.");
42788};
42789
42790numeric.sdotMM = function dotMM(A,B) {
42791 var p = A.length, q = B.length, BT = numeric.stranspose(B), r = BT.length, Ai, BTk;
42792 var i,j,k,accum;
42793 var ret = Array(p),reti;
42794 for(i=p-1;i>=0;i--) {
42795 reti = [];
42796 Ai = A[i];
42797 for(k=r-1;k>=0;k--) {
42798 accum = 0;
42799 BTk = BT[k];
42800 for(j in Ai) {
42801 if(!(Ai.hasOwnProperty(j))) continue;
42802 if(j in BTk) { accum += Ai[j]*BTk[j]; }
42803 }
42804 if(accum) reti[k] = accum;
42805 }
42806 ret[i] = reti;
42807 }
42808 return ret;
42809}
42810
42811numeric.sdotMV = function dotMV(A,x) {
42812 var p = A.length, Ai, i,j;
42813 var ret = Array(p), accum;
42814 for(i=p-1;i>=0;i--) {
42815 Ai = A[i];
42816 accum = 0;
42817 for(j in Ai) {
42818 if(!(Ai.hasOwnProperty(j))) continue;
42819 if(x[j]) accum += Ai[j]*x[j];
42820 }
42821 if(accum) ret[i] = accum;
42822 }
42823 return ret;
42824}
42825
42826numeric.sdotVM = function dotMV(x,A) {
42827 var i,j,Ai,alpha;
42828 var ret = [], accum;
42829 for(i in x) {
42830 if(!x.hasOwnProperty(i)) continue;
42831 Ai = A[i];
42832 alpha = x[i];
42833 for(j in Ai) {
42834 if(!Ai.hasOwnProperty(j)) continue;
42835 if(!ret[j]) { ret[j] = 0; }
42836 ret[j] += alpha*Ai[j];
42837 }
42838 }
42839 return ret;
42840}
42841
42842numeric.sdotVV = function dotVV(x,y) {
42843 var i,ret=0;
42844 for(i in x) { if(x[i] && y[i]) ret+= x[i]*y[i]; }
42845 return ret;
42846}
42847
42848numeric.sdot = function dot(A,B) {
42849 var m = numeric.sdim(A).length, n = numeric.sdim(B).length;
42850 var k = m*1000+n;
42851 switch(k) {
42852 case 0: return A*B;
42853 case 1001: return numeric.sdotVV(A,B);
42854 case 2001: return numeric.sdotMV(A,B);
42855 case 1002: return numeric.sdotVM(A,B);
42856 case 2002: return numeric.sdotMM(A,B);
42857 default: throw new Error('numeric.sdot not implemented for tensors of order '+m+' and '+n);
42858 }
42859}
42860
42861numeric.sscatter = function scatter(V) {
42862 var n = V[0].length, Vij, i, j, m = V.length, A = [], Aj;
42863 for(i=n-1;i>=0;--i) {
42864 if(!V[m-1][i]) continue;
42865 Aj = A;
42866 for(j=0;j<m-2;j++) {
42867 Vij = V[j][i];
42868 if(!Aj[Vij]) Aj[Vij] = [];
42869 Aj = Aj[Vij];
42870 }
42871 Aj[V[j][i]] = V[j+1][i];
42872 }
42873 return A;
42874}
42875
42876numeric.sgather = function gather(A,ret,k) {
42877 if(typeof ret === "undefined") ret = [];
42878 if(typeof k === "undefined") k = [];
42879 var n,i,Ai;
42880 n = k.length;
42881 for(i in A) {
42882 if(A.hasOwnProperty(i)) {
42883 k[n] = parseInt(i);
42884 Ai = A[i];
42885 if(typeof Ai === "number") {
42886 if(Ai) {
42887 if(ret.length === 0) {
42888 for(i=n+1;i>=0;--i) ret[i] = [];
42889 }
42890 for(i=n;i>=0;--i) ret[i].push(k[i]);
42891 ret[n+1].push(Ai);
42892 }
42893 } else gather(Ai,ret,k);
42894 }
42895 }
42896 if(k.length>n) k.pop();
42897 return ret;
42898}
42899
42900// 6. Coordinate matrices
42901numeric.cLU = function LU(A) {
42902 var I = A[0], J = A[1], V = A[2];
42903 var p = I.length, m=0, i,j,k,a,b,c;
42904 for(i=0;i<p;i++) if(I[i]>m) m=I[i];
42905 m++;
42906 var L = Array(m), U = Array(m), left = numeric.rep([m],Infinity), right = numeric.rep([m],-Infinity);
42907 var Ui, Uj,alpha;
42908 for(k=0;k<p;k++) {
42909 i = I[k];
42910 j = J[k];
42911 if(j<left[i]) left[i] = j;
42912 if(j>right[i]) right[i] = j;
42913 }
42914 for(i=0;i<m-1;i++) { if(right[i] > right[i+1]) right[i+1] = right[i]; }
42915 for(i=m-1;i>=1;i--) { if(left[i]<left[i-1]) left[i-1] = left[i]; }
42916 var countL = 0, countU = 0;
42917 for(i=0;i<m;i++) {
42918 U[i] = numeric.rep([right[i]-left[i]+1],0);
42919 L[i] = numeric.rep([i-left[i]],0);
42920 countL += i-left[i]+1;
42921 countU += right[i]-i+1;
42922 }
42923 for(k=0;k<p;k++) { i = I[k]; U[i][J[k]-left[i]] = V[k]; }
42924 for(i=0;i<m-1;i++) {
42925 a = i-left[i];
42926 Ui = U[i];
42927 for(j=i+1;left[j]<=i && j<m;j++) {
42928 b = i-left[j];
42929 c = right[i]-i;
42930 Uj = U[j];
42931 alpha = Uj[b]/Ui[a];
42932 if(alpha) {
42933 for(k=1;k<=c;k++) { Uj[k+b] -= alpha*Ui[k+a]; }
42934 L[j][i-left[j]] = alpha;
42935 }
42936 }
42937 }
42938 var Ui = [], Uj = [], Uv = [], Li = [], Lj = [], Lv = [];
42939 var p,q,foo;
42940 p=0; q=0;
42941 for(i=0;i<m;i++) {
42942 a = left[i];
42943 b = right[i];
42944 foo = U[i];
42945 for(j=i;j<=b;j++) {
42946 if(foo[j-a]) {
42947 Ui[p] = i;
42948 Uj[p] = j;
42949 Uv[p] = foo[j-a];
42950 p++;
42951 }
42952 }
42953 foo = L[i];
42954 for(j=a;j<i;j++) {
42955 if(foo[j-a]) {
42956 Li[q] = i;
42957 Lj[q] = j;
42958 Lv[q] = foo[j-a];
42959 q++;
42960 }
42961 }
42962 Li[q] = i;
42963 Lj[q] = i;
42964 Lv[q] = 1;
42965 q++;
42966 }
42967 return {U:[Ui,Uj,Uv], L:[Li,Lj,Lv]};
42968};
42969
42970numeric.cLUsolve = function LUsolve(lu,b) {
42971 var L = lu.L, U = lu.U, ret = numeric.clone(b);
42972 var Li = L[0], Lj = L[1], Lv = L[2];
42973 var Ui = U[0], Uj = U[1], Uv = U[2];
42974 var p = Ui.length, q = Li.length;
42975 var m = ret.length,i,j,k;
42976 k = 0;
42977 for(i=0;i<m;i++) {
42978 while(Lj[k] < i) {
42979 ret[i] -= Lv[k]*ret[Lj[k]];
42980 k++;
42981 }
42982 k++;
42983 }
42984 k = p-1;
42985 for(i=m-1;i>=0;i--) {
42986 while(Uj[k] > i) {
42987 ret[i] -= Uv[k]*ret[Uj[k]];
42988 k--;
42989 }
42990 ret[i] /= Uv[k];
42991 k--;
42992 }
42993 return ret;
42994};
42995
42996numeric.cgrid = function grid(n,shape) {
42997 if(typeof n === "number") n = [n,n];
42998 var ret = numeric.rep(n,-1);
42999 var i,j,count;
43000 if(typeof shape !== "function") {
43001 switch(shape) {
43002 case 'L':
43003 shape = function(i,j) { return (i>=n[0]/2 || j<n[1]/2); }
43004 break;
43005 default:
43006 shape = function(i,j) { return true; };
43007 break;
43008 }
43009 }
43010 count=0;
43011 for(i=1;i<n[0]-1;i++) for(j=1;j<n[1]-1;j++)
43012 if(shape(i,j)) {
43013 ret[i][j] = count;
43014 count++;
43015 }
43016 return ret;
43017}
43018
43019numeric.cdelsq = function delsq(g) {
43020 var dir = [[-1,0],[0,-1],[0,1],[1,0]];
43021 var s = numeric.dim(g), m = s[0], n = s[1], i,j,k,p,q;
43022 var Li = [], Lj = [], Lv = [];
43023 for(i=1;i<m-1;i++) for(j=1;j<n-1;j++) {
43024 if(g[i][j]<0) continue;
43025 for(k=0;k<4;k++) {
43026 p = i+dir[k][0];
43027 q = j+dir[k][1];
43028 if(g[p][q]<0) continue;
43029 Li.push(g[i][j]);
43030 Lj.push(g[p][q]);
43031 Lv.push(-1);
43032 }
43033 Li.push(g[i][j]);
43034 Lj.push(g[i][j]);
43035 Lv.push(4);
43036 }
43037 return [Li,Lj,Lv];
43038}
43039
43040numeric.cdotMV = function dotMV(A,x) {
43041 var ret, Ai = A[0], Aj = A[1], Av = A[2],k,p=Ai.length,N;
43042 N=0;
43043 for(k=0;k<p;k++) { if(Ai[k]>N) N = Ai[k]; }
43044 N++;
43045 ret = numeric.rep([N],0);
43046 for(k=0;k<p;k++) { ret[Ai[k]]+=Av[k]*x[Aj[k]]; }
43047 return ret;
43048}
43049
43050// 7. Splines
43051
43052numeric.Spline = function Spline(x,yl,yr,kl,kr) { this.x = x; this.yl = yl; this.yr = yr; this.kl = kl; this.kr = kr; }
43053numeric.Spline.prototype._at = function _at(x1,p) {
43054 var x = this.x;
43055 var yl = this.yl;
43056 var yr = this.yr;
43057 var kl = this.kl;
43058 var kr = this.kr;
43059 var x1,a,b,t;
43060 var add = numeric.add, sub = numeric.sub, mul = numeric.mul;
43061 a = sub(mul(kl[p],x[p+1]-x[p]),sub(yr[p+1],yl[p]));
43062 b = add(mul(kr[p+1],x[p]-x[p+1]),sub(yr[p+1],yl[p]));
43063 t = (x1-x[p])/(x[p+1]-x[p]);
43064 var s = t*(1-t);
43065 return add(add(add(mul(1-t,yl[p]),mul(t,yr[p+1])),mul(a,s*(1-t))),mul(b,s*t));
43066}
43067numeric.Spline.prototype.at = function at(x0) {
43068 if(typeof x0 === "number") {
43069 var x = this.x;
43070 var n = x.length;
43071 var p,q,mid,floor = Math.floor,a,b,t;
43072 p = 0;
43073 q = n-1;
43074 while(q-p>1) {
43075 mid = floor((p+q)/2);
43076 if(x[mid] <= x0) p = mid;
43077 else q = mid;
43078 }
43079 return this._at(x0,p);
43080 }
43081 var n = x0.length, i, ret = Array(n);
43082 for(i=n-1;i!==-1;--i) ret[i] = this.at(x0[i]);
43083 return ret;
43084}
43085numeric.Spline.prototype.diff = function diff() {
43086 var x = this.x;
43087 var yl = this.yl;
43088 var yr = this.yr;
43089 var kl = this.kl;
43090 var kr = this.kr;
43091 var n = yl.length;
43092 var i,dx,dy;
43093 var zl = kl, zr = kr, pl = Array(n), pr = Array(n);
43094 var add = numeric.add, mul = numeric.mul, div = numeric.div, sub = numeric.sub;
43095 for(i=n-1;i!==-1;--i) {
43096 dx = x[i+1]-x[i];
43097 dy = sub(yr[i+1],yl[i]);
43098 pl[i] = div(add(mul(dy, 6),mul(kl[i],-4*dx),mul(kr[i+1],-2*dx)),dx*dx);
43099 pr[i+1] = div(add(mul(dy,-6),mul(kl[i], 2*dx),mul(kr[i+1], 4*dx)),dx*dx);
43100 }
43101 return new numeric.Spline(x,zl,zr,pl,pr);
43102}
43103numeric.Spline.prototype.roots = function roots() {
43104 function sqr(x) { return x*x; }
43105 function heval(y0,y1,k0,k1,x) {
43106 var A = k0*2-(y1-y0);
43107 var B = -k1*2+(y1-y0);
43108 var t = (x+1)*0.5;
43109 var s = t*(1-t);
43110 return (1-t)*y0+t*y1+A*s*(1-t)+B*s*t;
43111 }
43112 var ret = [];
43113 var x = this.x, yl = this.yl, yr = this.yr, kl = this.kl, kr = this.kr;
43114 if(typeof yl[0] === "number") {
43115 yl = [yl];
43116 yr = [yr];
43117 kl = [kl];
43118 kr = [kr];
43119 }
43120 var m = yl.length,n=x.length-1,i,j,k,y,s,t;
43121 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;
43122 var sqrt = Math.sqrt;
43123 for(i=0;i!==m;++i) {
43124 ai = yl[i];
43125 bi = yr[i];
43126 ci = kl[i];
43127 di = kr[i];
43128 ri = [];
43129 for(j=0;j!==n;j++) {
43130 if(j>0 && bi[j]*ai[j]<0) ri.push(x[j]);
43131 dx = (x[j+1]-x[j]);
43132 cx = x[j];
43133 y0 = ai[j];
43134 y1 = bi[j+1];
43135 k0 = ci[j]/dx;
43136 k1 = di[j+1]/dx;
43137 D = sqr(k0-k1+3*(y0-y1)) + 12*k1*y0;
43138 A = k1+3*y0+2*k0-3*y1;
43139 B = 3*(k1+k0+2*(y0-y1));
43140 if(D<=0) {
43141 z0 = A/B;
43142 if(z0>x[j] && z0<x[j+1]) stops = [x[j],z0,x[j+1]];
43143 else stops = [x[j],x[j+1]];
43144 } else {
43145 z0 = (A-sqrt(D))/B;
43146 z1 = (A+sqrt(D))/B;
43147 stops = [x[j]];
43148 if(z0>x[j] && z0<x[j+1]) stops.push(z0);
43149 if(z1>x[j] && z1<x[j+1]) stops.push(z1);
43150 stops.push(x[j+1]);
43151 }
43152 t0 = stops[0];
43153 z0 = this._at(t0,j);
43154 for(k=0;k<stops.length-1;k++) {
43155 t1 = stops[k+1];
43156 z1 = this._at(t1,j);
43157 if(z0 === 0) {
43158 ri.push(t0);
43159 t0 = t1;
43160 z0 = z1;
43161 continue;
43162 }
43163 if(z1 === 0 || z0*z1>0) {
43164 t0 = t1;
43165 z0 = z1;
43166 continue;
43167 }
43168 var side = 0;
43169 while(1) {
43170 tm = (z0*t1-z1*t0)/(z0-z1);
43171 if(tm <= t0 || tm >= t1) { break; }
43172 zm = this._at(tm,j);
43173 if(zm*z1>0) {
43174 t1 = tm;
43175 z1 = zm;
43176 if(side === -1) z0*=0.5;
43177 side = -1;
43178 } else if(zm*z0>0) {
43179 t0 = tm;
43180 z0 = zm;
43181 if(side === 1) z1*=0.5;
43182 side = 1;
43183 } else break;
43184 }
43185 ri.push(tm);
43186 t0 = stops[k+1];
43187 z0 = this._at(t0, j);
43188 }
43189 if(z1 === 0) ri.push(t1);
43190 }
43191 ret[i] = ri;
43192 }
43193 if(typeof this.yl[0] === "number") return ret[0];
43194 return ret;
43195}
43196numeric.spline = function spline(x,y,k1,kn) {
43197 var n = x.length, b = [], dx = [], dy = [];
43198 var i;
43199 var sub = numeric.sub,mul = numeric.mul,add = numeric.add;
43200 for(i=n-2;i>=0;i--) { dx[i] = x[i+1]-x[i]; dy[i] = sub(y[i+1],y[i]); }
43201 if(typeof k1 === "string" || typeof kn === "string") {
43202 k1 = kn = "periodic";
43203 }
43204 // Build sparse tridiagonal system
43205 var T = [[],[],[]];
43206 switch(typeof k1) {
43207 case "undefined":
43208 b[0] = mul(3/(dx[0]*dx[0]),dy[0]);
43209 T[0].push(0,0);
43210 T[1].push(0,1);
43211 T[2].push(2/dx[0],1/dx[0]);
43212 break;
43213 case "string":
43214 b[0] = add(mul(3/(dx[n-2]*dx[n-2]),dy[n-2]),mul(3/(dx[0]*dx[0]),dy[0]));
43215 T[0].push(0,0,0);
43216 T[1].push(n-2,0,1);
43217 T[2].push(1/dx[n-2],2/dx[n-2]+2/dx[0],1/dx[0]);
43218 break;
43219 default:
43220 b[0] = k1;
43221 T[0].push(0);
43222 T[1].push(0);
43223 T[2].push(1);
43224 break;
43225 }
43226 for(i=1;i<n-1;i++) {
43227 b[i] = add(mul(3/(dx[i-1]*dx[i-1]),dy[i-1]),mul(3/(dx[i]*dx[i]),dy[i]));
43228 T[0].push(i,i,i);
43229 T[1].push(i-1,i,i+1);
43230 T[2].push(1/dx[i-1],2/dx[i-1]+2/dx[i],1/dx[i]);
43231 }
43232 switch(typeof kn) {
43233 case "undefined":
43234 b[n-1] = mul(3/(dx[n-2]*dx[n-2]),dy[n-2]);
43235 T[0].push(n-1,n-1);
43236 T[1].push(n-2,n-1);
43237 T[2].push(1/dx[n-2],2/dx[n-2]);
43238 break;
43239 case "string":
43240 T[1][T[1].length-1] = 0;
43241 break;
43242 default:
43243 b[n-1] = kn;
43244 T[0].push(n-1);
43245 T[1].push(n-1);
43246 T[2].push(1);
43247 break;
43248 }
43249 if(typeof b[0] !== "number") b = numeric.transpose(b);
43250 else b = [b];
43251 var k = Array(b.length);
43252 if(typeof k1 === "string") {
43253 for(i=k.length-1;i!==-1;--i) {
43254 k[i] = numeric.ccsLUPSolve(numeric.ccsLUP(numeric.ccsScatter(T)),b[i]);
43255 k[i][n-1] = k[i][0];
43256 }
43257 } else {
43258 for(i=k.length-1;i!==-1;--i) {
43259 k[i] = numeric.cLUsolve(numeric.cLU(T),b[i]);
43260 }
43261 }
43262 if(typeof y[0] === "number") k = k[0];
43263 else k = numeric.transpose(k);
43264 return new numeric.Spline(x,y,y,k,k);
43265}
43266
43267// 8. FFT
43268numeric.fftpow2 = function fftpow2(x,y) {
43269 var n = x.length;
43270 if(n === 1) return;
43271 var cos = Math.cos, sin = Math.sin, i,j;
43272 var xe = Array(n/2), ye = Array(n/2), xo = Array(n/2), yo = Array(n/2);
43273 j = n/2;
43274 for(i=n-1;i!==-1;--i) {
43275 --j;
43276 xo[j] = x[i];
43277 yo[j] = y[i];
43278 --i;
43279 xe[j] = x[i];
43280 ye[j] = y[i];
43281 }
43282 fftpow2(xe,ye);
43283 fftpow2(xo,yo);
43284 j = n/2;
43285 var t,k = (-6.2831853071795864769252867665590057683943387987502116419/n),ci,si;
43286 for(i=n-1;i!==-1;--i) {
43287 --j;
43288 if(j === -1) j = n/2-1;
43289 t = k*i;
43290 ci = cos(t);
43291 si = sin(t);
43292 x[i] = xe[j] + ci*xo[j] - si*yo[j];
43293 y[i] = ye[j] + ci*yo[j] + si*xo[j];
43294 }
43295}
43296numeric._ifftpow2 = function _ifftpow2(x,y) {
43297 var n = x.length;
43298 if(n === 1) return;
43299 var cos = Math.cos, sin = Math.sin, i,j;
43300 var xe = Array(n/2), ye = Array(n/2), xo = Array(n/2), yo = Array(n/2);
43301 j = n/2;
43302 for(i=n-1;i!==-1;--i) {
43303 --j;
43304 xo[j] = x[i];
43305 yo[j] = y[i];
43306 --i;
43307 xe[j] = x[i];
43308 ye[j] = y[i];
43309 }
43310 _ifftpow2(xe,ye);
43311 _ifftpow2(xo,yo);
43312 j = n/2;
43313 var t,k = (6.2831853071795864769252867665590057683943387987502116419/n),ci,si;
43314 for(i=n-1;i!==-1;--i) {
43315 --j;
43316 if(j === -1) j = n/2-1;
43317 t = k*i;
43318 ci = cos(t);
43319 si = sin(t);
43320 x[i] = xe[j] + ci*xo[j] - si*yo[j];
43321 y[i] = ye[j] + ci*yo[j] + si*xo[j];
43322 }
43323}
43324numeric.ifftpow2 = function ifftpow2(x,y) {
43325 numeric._ifftpow2(x,y);
43326 numeric.diveq(x,x.length);
43327 numeric.diveq(y,y.length);
43328}
43329numeric.convpow2 = function convpow2(ax,ay,bx,by) {
43330 numeric.fftpow2(ax,ay);
43331 numeric.fftpow2(bx,by);
43332 var i,n = ax.length,axi,bxi,ayi,byi;
43333 for(i=n-1;i!==-1;--i) {
43334 axi = ax[i]; ayi = ay[i]; bxi = bx[i]; byi = by[i];
43335 ax[i] = axi*bxi-ayi*byi;
43336 ay[i] = axi*byi+ayi*bxi;
43337 }
43338 numeric.ifftpow2(ax,ay);
43339}
43340numeric.T.prototype.fft = function fft() {
43341 var x = this.x, y = this.y;
43342 var n = x.length, log = Math.log, log2 = log(2),
43343 p = Math.ceil(log(2*n-1)/log2), m = Math.pow(2,p);
43344 var cx = numeric.rep([m],0), cy = numeric.rep([m],0), cos = Math.cos, sin = Math.sin;
43345 var k, c = (-3.141592653589793238462643383279502884197169399375105820/n),t;
43346 var a = numeric.rep([m],0), b = numeric.rep([m],0),nhalf = Math.floor(n/2);
43347 for(k=0;k<n;k++) a[k] = x[k];
43348 if(typeof y !== "undefined") for(k=0;k<n;k++) b[k] = y[k];
43349 cx[0] = 1;
43350 for(k=1;k<=m/2;k++) {
43351 t = c*k*k;
43352 cx[k] = cos(t);
43353 cy[k] = sin(t);
43354 cx[m-k] = cos(t);
43355 cy[m-k] = sin(t)
43356 }
43357 var X = new numeric.T(a,b), Y = new numeric.T(cx,cy);
43358 X = X.mul(Y);
43359 numeric.convpow2(X.x,X.y,numeric.clone(Y.x),numeric.neg(Y.y));
43360 X = X.mul(Y);
43361 X.x.length = n;
43362 X.y.length = n;
43363 return X;
43364}
43365numeric.T.prototype.ifft = function ifft() {
43366 var x = this.x, y = this.y;
43367 var n = x.length, log = Math.log, log2 = log(2),
43368 p = Math.ceil(log(2*n-1)/log2), m = Math.pow(2,p);
43369 var cx = numeric.rep([m],0), cy = numeric.rep([m],0), cos = Math.cos, sin = Math.sin;
43370 var k, c = (3.141592653589793238462643383279502884197169399375105820/n),t;
43371 var a = numeric.rep([m],0), b = numeric.rep([m],0),nhalf = Math.floor(n/2);
43372 for(k=0;k<n;k++) a[k] = x[k];
43373 if(typeof y !== "undefined") for(k=0;k<n;k++) b[k] = y[k];
43374 cx[0] = 1;
43375 for(k=1;k<=m/2;k++) {
43376 t = c*k*k;
43377 cx[k] = cos(t);
43378 cy[k] = sin(t);
43379 cx[m-k] = cos(t);
43380 cy[m-k] = sin(t)
43381 }
43382 var X = new numeric.T(a,b), Y = new numeric.T(cx,cy);
43383 X = X.mul(Y);
43384 numeric.convpow2(X.x,X.y,numeric.clone(Y.x),numeric.neg(Y.y));
43385 X = X.mul(Y);
43386 X.x.length = n;
43387 X.y.length = n;
43388 return X.div(n);
43389}
43390
43391//9. Unconstrained optimization
43392numeric.gradient = function gradient(f,x) {
43393 var n = x.length;
43394 var f0 = f(x);
43395 if(isNaN(f0)) throw new Error('gradient: f(x) is a NaN!');
43396 var max = Math.max;
43397 var i,x0 = numeric.clone(x),f1,f2, J = Array(n);
43398 var div = numeric.div, sub = numeric.sub,errest,roundoff,max = Math.max,eps = 1e-3,abs = Math.abs, min = Math.min;
43399 var t0,t1,t2,it=0,d1,d2,N;
43400 for(i=0;i<n;i++) {
43401 var h = max(1e-6*f0,1e-8);
43402 while(1) {
43403 ++it;
43404 if(it>20) { throw new Error("Numerical gradient fails"); }
43405 x0[i] = x[i]+h;
43406 f1 = f(x0);
43407 x0[i] = x[i]-h;
43408 f2 = f(x0);
43409 x0[i] = x[i];
43410 if(isNaN(f1) || isNaN(f2)) { h/=16; continue; }
43411 J[i] = (f1-f2)/(2*h);
43412 t0 = x[i]-h;
43413 t1 = x[i];
43414 t2 = x[i]+h;
43415 d1 = (f1-f0)/h;
43416 d2 = (f0-f2)/h;
43417 N = max(abs(J[i]),abs(f0),abs(f1),abs(f2),abs(t0),abs(t1),abs(t2),1e-8);
43418 errest = min(max(abs(d1-J[i]),abs(d2-J[i]),abs(d1-d2))/N,h/N);
43419 if(errest>eps) { h/=16; }
43420 else break;
43421 }
43422 }
43423 return J;
43424}
43425
43426numeric.uncmin = function uncmin(f,x0,tol,gradient,maxit,callback,options) {
43427 var grad = numeric.gradient;
43428 if(typeof options === "undefined") { options = {}; }
43429 if(typeof tol === "undefined") { tol = 1e-8; }
43430 if(typeof gradient === "undefined") { gradient = function(x) { return grad(f,x); }; }
43431 if(typeof maxit === "undefined") maxit = 1000;
43432 x0 = numeric.clone(x0);
43433 var n = x0.length;
43434 var f0 = f(x0),f1,df0;
43435 if(isNaN(f0)) throw new Error('uncmin: f(x0) is a NaN!');
43436 var max = Math.max, norm2 = numeric.norm2;
43437 tol = max(tol,numeric.epsilon);
43438 var step,g0,g1,H1 = options.Hinv || numeric.identity(n);
43439 var dot = numeric.dot, inv = numeric.inv, sub = numeric.sub, add = numeric.add, ten = numeric.tensor, div = numeric.div, mul = numeric.mul;
43440 var all = numeric.all, isfinite = numeric.isFinite, neg = numeric.neg;
43441 var it=0,i,s,x1,y,Hy,Hs,ys,i0,t,nstep,t1,t2;
43442 var msg = "";
43443 g0 = gradient(x0);
43444 while(it<maxit) {
43445 if(typeof callback === "function") { if(callback(it,x0,f0,g0,H1)) { msg = "Callback returned true"; break; } }
43446 if(!all(isfinite(g0))) { msg = "Gradient has Infinity or NaN"; break; }
43447 step = neg(dot(H1,g0));
43448 if(!all(isfinite(step))) { msg = "Search direction has Infinity or NaN"; break; }
43449 nstep = norm2(step);
43450 if(nstep < tol) { msg="Newton step smaller than tol"; break; }
43451 t = 1;
43452 df0 = dot(g0,step);
43453 // line search
43454 x1 = x0;
43455 while(it < maxit) {
43456 if(t*nstep < tol) { break; }
43457 s = mul(step,t);
43458 x1 = add(x0,s);
43459 f1 = f(x1);
43460 if(f1-f0 >= 0.1*t*df0 || isNaN(f1)) {
43461 t *= 0.5;
43462 ++it;
43463 continue;
43464 }
43465 break;
43466 }
43467 if(t*nstep < tol) { msg = "Line search step size smaller than tol"; break; }
43468 if(it === maxit) { msg = "maxit reached during line search"; break; }
43469 g1 = gradient(x1);
43470 y = sub(g1,g0);
43471 ys = dot(y,s);
43472 Hy = dot(H1,y);
43473 H1 = sub(add(H1,
43474 mul(
43475 (ys+dot(y,Hy))/(ys*ys),
43476 ten(s,s) )),
43477 div(add(ten(Hy,s),ten(s,Hy)),ys));
43478 x0 = x1;
43479 f0 = f1;
43480 g0 = g1;
43481 ++it;
43482 }
43483 return {solution: x0, f: f0, gradient: g0, invHessian: H1, iterations:it, message: msg};
43484}
43485
43486// 10. Ode solver (Dormand-Prince)
43487numeric.Dopri = function Dopri(x,y,f,ymid,iterations,msg,events) {
43488 this.x = x;
43489 this.y = y;
43490 this.f = f;
43491 this.ymid = ymid;
43492 this.iterations = iterations;
43493 this.events = events;
43494 this.message = msg;
43495}
43496numeric.Dopri.prototype._at = function _at(xi,j) {
43497 function sqr(x) { return x*x; }
43498 var sol = this;
43499 var xs = sol.x;
43500 var ys = sol.y;
43501 var k1 = sol.f;
43502 var ymid = sol.ymid;
43503 var n = xs.length;
43504 var x0,x1,xh,y0,y1,yh,xi;
43505 var floor = Math.floor,h;
43506 var c = 0.5;
43507 var add = numeric.add, mul = numeric.mul,sub = numeric.sub, p,q,w;
43508 x0 = xs[j];
43509 x1 = xs[j+1];
43510 y0 = ys[j];
43511 y1 = ys[j+1];
43512 h = x1-x0;
43513 xh = x0+c*h;
43514 yh = ymid[j];
43515 p = sub(k1[j ],mul(y0,1/(x0-xh)+2/(x0-x1)));
43516 q = sub(k1[j+1],mul(y1,1/(x1-xh)+2/(x1-x0)));
43517 w = [sqr(xi - x1) * (xi - xh) / sqr(x0 - x1) / (x0 - xh),
43518 sqr(xi - x0) * sqr(xi - x1) / sqr(x0 - xh) / sqr(x1 - xh),
43519 sqr(xi - x0) * (xi - xh) / sqr(x1 - x0) / (x1 - xh),
43520 (xi - x0) * sqr(xi - x1) * (xi - xh) / sqr(x0-x1) / (x0 - xh),
43521 (xi - x1) * sqr(xi - x0) * (xi - xh) / sqr(x0-x1) / (x1 - xh)];
43522 return add(add(add(add(mul(y0,w[0]),
43523 mul(yh,w[1])),
43524 mul(y1,w[2])),
43525 mul( p,w[3])),
43526 mul( q,w[4]));
43527}
43528numeric.Dopri.prototype.at = function at(x) {
43529 var i,j,k,floor = Math.floor;
43530 if(typeof x !== "number") {
43531 var n = x.length, ret = Array(n);
43532 for(i=n-1;i!==-1;--i) {
43533 ret[i] = this.at(x[i]);
43534 }
43535 return ret;
43536 }
43537 var x0 = this.x;
43538 i = 0; j = x0.length-1;
43539 while(j-i>1) {
43540 k = floor(0.5*(i+j));
43541 if(x0[k] <= x) i = k;
43542 else j = k;
43543 }
43544 return this._at(x,i);
43545}
43546
43547numeric.dopri = function dopri(x0,x1,y0,f,tol,maxit,event) {
43548 if(typeof tol === "undefined") { tol = 1e-6; }
43549 if(typeof maxit === "undefined") { maxit = 1000; }
43550 var xs = [x0], ys = [y0], k1 = [f(x0,y0)], k2,k3,k4,k5,k6,k7, ymid = [];
43551 var A2 = 1/5;
43552 var A3 = [3/40,9/40];
43553 var A4 = [44/45,-56/15,32/9];
43554 var A5 = [19372/6561,-25360/2187,64448/6561,-212/729];
43555 var A6 = [9017/3168,-355/33,46732/5247,49/176,-5103/18656];
43556 var b = [35/384,0,500/1113,125/192,-2187/6784,11/84];
43557 var bm = [0.5*6025192743/30085553152,
43558 0,
43559 0.5*51252292925/65400821598,
43560 0.5*-2691868925/45128329728,
43561 0.5*187940372067/1594534317056,
43562 0.5*-1776094331/19743644256,
43563 0.5*11237099/235043384];
43564 var c = [1/5,3/10,4/5,8/9,1,1];
43565 var e = [-71/57600,0,71/16695,-71/1920,17253/339200,-22/525,1/40];
43566 var i = 0,er,j;
43567 var h = (x1-x0)/10;
43568 var it = 0;
43569 var add = numeric.add, mul = numeric.mul, y1,erinf;
43570 var max = Math.max, min = Math.min, abs = Math.abs, norminf = numeric.norminf,pow = Math.pow;
43571 var any = numeric.any, lt = numeric.lt, and = numeric.and, sub = numeric.sub;
43572 var e0, e1, ev;
43573 var ret = new numeric.Dopri(xs,ys,k1,ymid,-1,"");
43574 if(typeof event === "function") e0 = event(x0,y0);
43575 while(x0<x1 && it<maxit) {
43576 ++it;
43577 if(x0+h>x1) h = x1-x0;
43578 k2 = f(x0+c[0]*h, add(y0,mul( A2*h,k1[i])));
43579 k3 = f(x0+c[1]*h, add(add(y0,mul(A3[0]*h,k1[i])),mul(A3[1]*h,k2)));
43580 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)));
43581 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)));
43582 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)));
43583 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]));
43584 k7 = f(x0+h,y1);
43585 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]));
43586 if(typeof er === "number") erinf = abs(er);
43587 else erinf = norminf(er);
43588 if(erinf > tol) { // reject
43589 h = 0.2*h*pow(tol/erinf,0.25);
43590 if(x0+h === x0) {
43591 ret.msg = "Step size became too small";
43592 break;
43593 }
43594 continue;
43595 }
43596 ymid[i] = add(add(add(add(add(add(y0,
43597 mul(k1[i],h*bm[0])),
43598 mul(k3 ,h*bm[2])),
43599 mul(k4 ,h*bm[3])),
43600 mul(k5 ,h*bm[4])),
43601 mul(k6 ,h*bm[5])),
43602 mul(k7 ,h*bm[6]));
43603 ++i;
43604 xs[i] = x0+h;
43605 ys[i] = y1;
43606 k1[i] = k7;
43607 if(typeof event === "function") {
43608 var yi,xl = x0,xr = x0+0.5*h,xi;
43609 e1 = event(xr,ymid[i-1]);
43610 ev = and(lt(e0,0),lt(0,e1));
43611 if(!any(ev)) { xl = xr; xr = x0+h; e0 = e1; e1 = event(xr,y1); ev = and(lt(e0,0),lt(0,e1)); }
43612 if(any(ev)) {
43613 var xc, yc, en,ei;
43614 var side=0, sl = 1.0, sr = 1.0;
43615 while(1) {
43616 if(typeof e0 === "number") xi = (sr*e1*xl-sl*e0*xr)/(sr*e1-sl*e0);
43617 else {
43618 xi = xr;
43619 for(j=e0.length-1;j!==-1;--j) {
43620 if(e0[j]<0 && e1[j]>0) xi = min(xi,(sr*e1[j]*xl-sl*e0[j]*xr)/(sr*e1[j]-sl*e0[j]));
43621 }
43622 }
43623 if(xi <= xl || xi >= xr) break;
43624 yi = ret._at(xi, i-1);
43625 ei = event(xi,yi);
43626 en = and(lt(e0,0),lt(0,ei));
43627 if(any(en)) {
43628 xr = xi;
43629 e1 = ei;
43630 ev = en;
43631 sr = 1.0;
43632 if(side === -1) sl *= 0.5;
43633 else sl = 1.0;
43634 side = -1;
43635 } else {
43636 xl = xi;
43637 e0 = ei;
43638 sl = 1.0;
43639 if(side === 1) sr *= 0.5;
43640 else sr = 1.0;
43641 side = 1;
43642 }
43643 }
43644 y1 = ret._at(0.5*(x0+xi),i-1);
43645 ret.f[i] = f(xi,yi);
43646 ret.x[i] = xi;
43647 ret.y[i] = yi;
43648 ret.ymid[i-1] = y1;
43649 ret.events = ev;
43650 ret.iterations = it;
43651 return ret;
43652 }
43653 }
43654 x0 += h;
43655 y0 = y1;
43656 e0 = e1;
43657 h = min(0.8*h*pow(tol/erinf,0.25),4*h);
43658 }
43659 ret.iterations = it;
43660 return ret;
43661}
43662
43663// 11. Ax = b
43664numeric.LU = function(A, fast) {
43665 fast = fast || false;
43666
43667 var abs = Math.abs;
43668 var i, j, k, absAjk, Akk, Ak, Pk, Ai;
43669 var max;
43670 var n = A.length, n1 = n-1;
43671 var P = new Array(n);
43672 if(!fast) A = numeric.clone(A);
43673
43674 for (k = 0; k < n; ++k) {
43675 Pk = k;
43676 Ak = A[k];
43677 max = abs(Ak[k]);
43678 for (j = k + 1; j < n; ++j) {
43679 absAjk = abs(A[j][k]);
43680 if (max < absAjk) {
43681 max = absAjk;
43682 Pk = j;
43683 }
43684 }
43685 P[k] = Pk;
43686
43687 if (Pk != k) {
43688 A[k] = A[Pk];
43689 A[Pk] = Ak;
43690 Ak = A[k];
43691 }
43692
43693 Akk = Ak[k];
43694
43695 for (i = k + 1; i < n; ++i) {
43696 A[i][k] /= Akk;
43697 }
43698
43699 for (i = k + 1; i < n; ++i) {
43700 Ai = A[i];
43701 for (j = k + 1; j < n1; ++j) {
43702 Ai[j] -= Ai[k] * Ak[j];
43703 ++j;
43704 Ai[j] -= Ai[k] * Ak[j];
43705 }
43706 if(j===n1) Ai[j] -= Ai[k] * Ak[j];
43707 }
43708 }
43709
43710 return {
43711 LU: A,
43712 P: P
43713 };
43714}
43715
43716numeric.LUsolve = function LUsolve(LUP, b) {
43717 var i, j;
43718 var LU = LUP.LU;
43719 var n = LU.length;
43720 var x = numeric.clone(b);
43721 var P = LUP.P;
43722 var Pi, LUi, LUii, tmp;
43723
43724 for (i=n-1;i!==-1;--i) x[i] = b[i];
43725 for (i = 0; i < n; ++i) {
43726 Pi = P[i];
43727 if (P[i] !== i) {
43728 tmp = x[i];
43729 x[i] = x[Pi];
43730 x[Pi] = tmp;
43731 }
43732
43733 LUi = LU[i];
43734 for (j = 0; j < i; ++j) {
43735 x[i] -= x[j] * LUi[j];
43736 }
43737 }
43738
43739 for (i = n - 1; i >= 0; --i) {
43740 LUi = LU[i];
43741 for (j = i + 1; j < n; ++j) {
43742 x[i] -= x[j] * LUi[j];
43743 }
43744
43745 x[i] /= LUi[i];
43746 }
43747
43748 return x;
43749}
43750
43751numeric.solve = function solve(A,b,fast) { return numeric.LUsolve(numeric.LU(A,fast), b); }
43752
43753// 12. Linear programming
43754numeric.echelonize = function echelonize(A) {
43755 var s = numeric.dim(A), m = s[0], n = s[1];
43756 var I = numeric.identity(m);
43757 var P = Array(m);
43758 var i,j,k,l,Ai,Ii,Z,a;
43759 var abs = Math.abs;
43760 var diveq = numeric.diveq;
43761 A = numeric.clone(A);
43762 for(i=0;i<m;++i) {
43763 k = 0;
43764 Ai = A[i];
43765 Ii = I[i];
43766 for(j=1;j<n;++j) if(abs(Ai[k])<abs(Ai[j])) k=j;
43767 P[i] = k;
43768 diveq(Ii,Ai[k]);
43769 diveq(Ai,Ai[k]);
43770 for(j=0;j<m;++j) if(j!==i) {
43771 Z = A[j]; a = Z[k];
43772 for(l=n-1;l!==-1;--l) Z[l] -= Ai[l]*a;
43773 Z = I[j];
43774 for(l=m-1;l!==-1;--l) Z[l] -= Ii[l]*a;
43775 }
43776 }
43777 return {I:I, A:A, P:P};
43778}
43779
43780numeric.__solveLP = function __solveLP(c,A,b,tol,maxit,x,flag) {
43781 var sum = numeric.sum, log = numeric.log, mul = numeric.mul, sub = numeric.sub, dot = numeric.dot, div = numeric.div, add = numeric.add;
43782 var m = c.length, n = b.length,y;
43783 var unbounded = false, cb,i0=0;
43784 var alpha = 1.0;
43785 var f0,df0,AT = numeric.transpose(A), svd = numeric.svd,transpose = numeric.transpose,leq = numeric.leq, sqrt = Math.sqrt, abs = Math.abs;
43786 var muleq = numeric.muleq;
43787 var norm = numeric.norminf, any = numeric.any,min = Math.min;
43788 var all = numeric.all, gt = numeric.gt;
43789 var p = Array(m), A0 = Array(n),e=numeric.rep([n],1), H;
43790 var solve = numeric.solve, z = sub(b,dot(A,x)),count;
43791 var dotcc = dot(c,c);
43792 var g;
43793 for(count=i0;count<maxit;++count) {
43794 var i,j,d;
43795 for(i=n-1;i!==-1;--i) A0[i] = div(A[i],z[i]);
43796 var A1 = transpose(A0);
43797 for(i=m-1;i!==-1;--i) p[i] = (/*x[i]+*/sum(A1[i]));
43798 alpha = 0.25*abs(dotcc/dot(c,p));
43799 var a1 = 100*sqrt(dotcc/dot(p,p));
43800 if(!isFinite(alpha) || alpha>a1) alpha = a1;
43801 g = add(c,mul(alpha,p));
43802 H = dot(A1,A0);
43803 for(i=m-1;i!==-1;--i) H[i][i] += 1;
43804 d = solve(H,div(g,alpha),true);
43805 var t0 = div(z,dot(A,d));
43806 var t = 1.0;
43807 for(i=n-1;i!==-1;--i) if(t0[i]<0) t = min(t,-0.999*t0[i]);
43808 y = sub(x,mul(d,t));
43809 z = sub(b,dot(A,y));
43810 if(!all(gt(z,0))) return { solution: x, message: "", iterations: count };
43811 x = y;
43812 if(alpha<tol) return { solution: y, message: "", iterations: count };
43813 if(flag) {
43814 var s = dot(c,g), Ag = dot(A,g);
43815 unbounded = true;
43816 for(i=n-1;i!==-1;--i) if(s*Ag[i]<0) { unbounded = false; break; }
43817 } else {
43818 if(x[m-1]>=0) unbounded = false;
43819 else unbounded = true;
43820 }
43821 if(unbounded) return { solution: y, message: "Unbounded", iterations: count };
43822 }
43823 return { solution: x, message: "maximum iteration count exceeded", iterations:count };
43824}
43825
43826numeric._solveLP = function _solveLP(c,A,b,tol,maxit) {
43827 var m = c.length, n = b.length,y;
43828 var sum = numeric.sum, log = numeric.log, mul = numeric.mul, sub = numeric.sub, dot = numeric.dot, div = numeric.div, add = numeric.add;
43829 var c0 = numeric.rep([m],0).concat([1]);
43830 var J = numeric.rep([n,1],-1);
43831 var A0 = numeric.blockMatrix([[A , J ]]);
43832 var b0 = b;
43833 var y = numeric.rep([m],0).concat(Math.max(0,numeric.sup(numeric.neg(b)))+1);
43834 var x0 = numeric.__solveLP(c0,A0,b0,tol,maxit,y,false);
43835 var x = numeric.clone(x0.solution);
43836 x.length = m;
43837 var foo = numeric.inf(sub(b,dot(A,x)));
43838 if(foo<0) { return { solution: NaN, message: "Infeasible", iterations: x0.iterations }; }
43839 var ret = numeric.__solveLP(c, A, b, tol, maxit-x0.iterations, x, true);
43840 ret.iterations += x0.iterations;
43841 return ret;
43842};
43843
43844numeric.solveLP = function solveLP(c,A,b,Aeq,beq,tol,maxit) {
43845 if(typeof maxit === "undefined") maxit = 1000;
43846 if(typeof tol === "undefined") tol = numeric.epsilon;
43847 if(typeof Aeq === "undefined") return numeric._solveLP(c,A,b,tol,maxit);
43848 var m = Aeq.length, n = Aeq[0].length, o = A.length;
43849 var B = numeric.echelonize(Aeq);
43850 var flags = numeric.rep([n],0);
43851 var P = B.P;
43852 var Q = [];
43853 var i;
43854 for(i=P.length-1;i!==-1;--i) flags[P[i]] = 1;
43855 for(i=n-1;i!==-1;--i) if(flags[i]===0) Q.push(i);
43856 var g = numeric.getRange;
43857 var I = numeric.linspace(0,m-1), J = numeric.linspace(0,o-1);
43858 var Aeq2 = g(Aeq,I,Q), A1 = g(A,J,P), A2 = g(A,J,Q), dot = numeric.dot, sub = numeric.sub;
43859 var A3 = dot(A1,B.I);
43860 var A4 = sub(A2,dot(A3,Aeq2)), b4 = sub(b,dot(A3,beq));
43861 var c1 = Array(P.length), c2 = Array(Q.length);
43862 for(i=P.length-1;i!==-1;--i) c1[i] = c[P[i]];
43863 for(i=Q.length-1;i!==-1;--i) c2[i] = c[Q[i]];
43864 var c4 = sub(c2,dot(c1,dot(B.I,Aeq2)));
43865 var S = numeric._solveLP(c4,A4,b4,tol,maxit);
43866 var x2 = S.solution;
43867 if(x2!==x2) return S;
43868 var x1 = dot(B.I,sub(beq,dot(Aeq2,x2)));
43869 var x = Array(c.length);
43870 for(i=P.length-1;i!==-1;--i) x[P[i]] = x1[i];
43871 for(i=Q.length-1;i!==-1;--i) x[Q[i]] = x2[i];
43872 return { solution: x, message:S.message, iterations: S.iterations };
43873}
43874
43875numeric.MPStoLP = function MPStoLP(MPS) {
43876 if(MPS instanceof String) { MPS.split('\n'); }
43877 var state = 0;
43878 var states = ['Initial state','NAME','ROWS','COLUMNS','RHS','BOUNDS','ENDATA'];
43879 var n = MPS.length;
43880 var i,j,z,N=0,rows = {}, sign = [], rl = 0, vars = {}, nv = 0;
43881 var name;
43882 var c = [], A = [], b = [];
43883 function err(e) { throw new Error('MPStoLP: '+e+'\nLine '+i+': '+MPS[i]+'\nCurrent state: '+states[state]+'\n'); }
43884 for(i=0;i<n;++i) {
43885 z = MPS[i];
43886 var w0 = z.match(/\S*/g);
43887 var w = [];
43888 for(j=0;j<w0.length;++j) if(w0[j]!=="") w.push(w0[j]);
43889 if(w.length === 0) continue;
43890 for(j=0;j<states.length;++j) if(z.substr(0,states[j].length) === states[j]) break;
43891 if(j<states.length) {
43892 state = j;
43893 if(j===1) { name = w[1]; }
43894 if(j===6) return { name:name, c:c, A:numeric.transpose(A), b:b, rows:rows, vars:vars };
43895 continue;
43896 }
43897 switch(state) {
43898 case 0: case 1: err('Unexpected line');
43899 case 2:
43900 switch(w[0]) {
43901 case 'N': if(N===0) N = w[1]; else err('Two or more N rows'); break;
43902 case 'L': rows[w[1]] = rl; sign[rl] = 1; b[rl] = 0; ++rl; break;
43903 case 'G': rows[w[1]] = rl; sign[rl] = -1;b[rl] = 0; ++rl; break;
43904 case 'E': rows[w[1]] = rl; sign[rl] = 0;b[rl] = 0; ++rl; break;
43905 default: err('Parse error '+numeric.prettyPrint(w));
43906 }
43907 break;
43908 case 3:
43909 if(!vars.hasOwnProperty(w[0])) { vars[w[0]] = nv; c[nv] = 0; A[nv] = numeric.rep([rl],0); ++nv; }
43910 var p = vars[w[0]];
43911 for(j=1;j<w.length;j+=2) {
43912 if(w[j] === N) { c[p] = parseFloat(w[j+1]); continue; }
43913 var q = rows[w[j]];
43914 A[p][q] = (sign[q]<0?-1:1)*parseFloat(w[j+1]);
43915 }
43916 break;
43917 case 4:
43918 for(j=1;j<w.length;j+=2) b[rows[w[j]]] = (sign[rows[w[j]]]<0?-1:1)*parseFloat(w[j+1]);
43919 break;
43920 case 5: /*FIXME*/ break;
43921 case 6: err('Internal error');
43922 }
43923 }
43924 err('Reached end of file without ENDATA');
43925}
43926// seedrandom.js version 2.0.
43927// Author: David Bau 4/2/2011
43928//
43929// Defines a method Math.seedrandom() that, when called, substitutes
43930// an explicitly seeded RC4-based algorithm for Math.random(). Also
43931// supports automatic seeding from local or network sources of entropy.
43932//
43933// Usage:
43934//
43935// <script src=http://davidbau.com/encode/seedrandom-min.js></script>
43936//
43937// Math.seedrandom('yipee'); Sets Math.random to a function that is
43938// initialized using the given explicit seed.
43939//
43940// Math.seedrandom(); Sets Math.random to a function that is
43941// seeded using the current time, dom state,
43942// and other accumulated local entropy.
43943// The generated seed string is returned.
43944//
43945// Math.seedrandom('yowza', true);
43946// Seeds using the given explicit seed mixed
43947// together with accumulated entropy.
43948//
43949// <script src="http://bit.ly/srandom-512"></script>
43950// Seeds using physical random bits downloaded
43951// from random.org.
43952//
43953// <script src="https://jsonlib.appspot.com/urandom?callback=Math.seedrandom">
43954// </script> Seeds using urandom bits from call.jsonlib.com,
43955// which is faster than random.org.
43956//
43957// Examples:
43958//
43959// Math.seedrandom("hello"); // Use "hello" as the seed.
43960// document.write(Math.random()); // Always 0.5463663768140734
43961// document.write(Math.random()); // Always 0.43973793770592234
43962// var rng1 = Math.random; // Remember the current prng.
43963//
43964// var autoseed = Math.seedrandom(); // New prng with an automatic seed.
43965// document.write(Math.random()); // Pretty much unpredictable.
43966//
43967// Math.random = rng1; // Continue "hello" prng sequence.
43968// document.write(Math.random()); // Always 0.554769432473455
43969//
43970// Math.seedrandom(autoseed); // Restart at the previous seed.
43971// document.write(Math.random()); // Repeat the 'unpredictable' value.
43972//
43973// Notes:
43974//
43975// Each time seedrandom('arg') is called, entropy from the passed seed
43976// is accumulated in a pool to help generate future seeds for the
43977// zero-argument form of Math.seedrandom, so entropy can be injected over
43978// time by calling seedrandom with explicit data repeatedly.
43979//
43980// On speed - This javascript implementation of Math.random() is about
43981// 3-10x slower than the built-in Math.random() because it is not native
43982// code, but this is typically fast enough anyway. Seeding is more expensive,
43983// especially if you use auto-seeding. Some details (timings on Chrome 4):
43984//
43985// Our Math.random() - avg less than 0.002 milliseconds per call
43986// seedrandom('explicit') - avg less than 0.5 milliseconds per call
43987// seedrandom('explicit', true) - avg less than 2 milliseconds per call
43988// seedrandom() - avg about 38 milliseconds per call
43989//
43990// LICENSE (BSD):
43991//
43992// Copyright 2010 David Bau, all rights reserved.
43993//
43994// Redistribution and use in source and binary forms, with or without
43995// modification, are permitted provided that the following conditions are met:
43996//
43997// 1. Redistributions of source code must retain the above copyright
43998// notice, this list of conditions and the following disclaimer.
43999//
44000// 2. Redistributions in binary form must reproduce the above copyright
44001// notice, this list of conditions and the following disclaimer in the
44002// documentation and/or other materials provided with the distribution.
44003//
44004// 3. Neither the name of this module nor the names of its contributors may
44005// be used to endorse or promote products derived from this software
44006// without specific prior written permission.
44007//
44008// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
44009// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
44010// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
44011// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
44012// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44013// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
44014// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
44015// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
44016// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44017// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
44018// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44019//
44020/**
44021 * All code is in an anonymous closure to keep the global namespace clean.
44022 *
44023 * @param {number=} overflow
44024 * @param {number=} startdenom
44025 */
44026
44027// Patched by Seb so that seedrandom.js does not pollute the Math object.
44028// My tests suggest that doing Math.trouble = 1 makes Math lookups about 5%
44029// slower.
44030numeric.seedrandom = { pow:Math.pow, random:Math.random };
44031
44032(function (pool, math, width, chunks, significance, overflow, startdenom) {
44033
44034
44035//
44036// seedrandom()
44037// This is the seedrandom function described above.
44038//
44039math['seedrandom'] = function seedrandom(seed, use_entropy) {
44040 var key = [];
44041 var arc4;
44042
44043 // Flatten the seed string or build one from local entropy if needed.
44044 seed = mixkey(flatten(
44045 use_entropy ? [seed, pool] :
44046 arguments.length ? seed :
44047 [new Date().getTime(), pool, window], 3), key);
44048
44049 // Use the seed to initialize an ARC4 generator.
44050 arc4 = new ARC4(key);
44051
44052 // Mix the randomness into accumulated entropy.
44053 mixkey(arc4.S, pool);
44054
44055 // Override Math.random
44056
44057 // This function returns a random double in [0, 1) that contains
44058 // randomness in every bit of the mantissa of the IEEE 754 value.
44059
44060 math['random'] = function random() { // Closure to return a random double:
44061 var n = arc4.g(chunks); // Start with a numerator n < 2 ^ 48
44062 var d = startdenom; // and denominator d = 2 ^ 48.
44063 var x = 0; // and no 'extra last byte'.
44064 while (n < significance) { // Fill up all significant digits by
44065 n = (n + x) * width; // shifting numerator and
44066 d *= width; // denominator and generating a
44067 x = arc4.g(1); // new least-significant-byte.
44068 }
44069 while (n >= overflow) { // To avoid rounding up, before adding
44070 n /= 2; // last byte, shift everything
44071 d /= 2; // right using integer math until
44072 x >>>= 1; // we have exactly the desired bits.
44073 }
44074 return (n + x) / d; // Form the number within [0, 1).
44075 };
44076
44077 // Return the seed that was used
44078 return seed;
44079};
44080
44081//
44082// ARC4
44083//
44084// An ARC4 implementation. The constructor takes a key in the form of
44085// an array of at most (width) integers that should be 0 <= x < (width).
44086//
44087// The g(count) method returns a pseudorandom integer that concatenates
44088// the next (count) outputs from ARC4. Its return value is a number x
44089// that is in the range 0 <= x < (width ^ count).
44090//
44091/** @constructor */
44092function ARC4(key) {
44093 var t, u, me = this, keylen = key.length;
44094 var i = 0, j = me.i = me.j = me.m = 0;
44095 me.S = [];
44096 me.c = [];
44097
44098 // The empty key [] is treated as [0].
44099 if (!keylen) { key = [keylen++]; }
44100
44101 // Set up S using the standard key scheduling algorithm.
44102 while (i < width) { me.S[i] = i++; }
44103 for (i = 0; i < width; i++) {
44104 t = me.S[i];
44105 j = lowbits(j + t + key[i % keylen]);
44106 u = me.S[j];
44107 me.S[i] = u;
44108 me.S[j] = t;
44109 }
44110
44111 // The "g" method returns the next (count) outputs as one number.
44112 me.g = function getnext(count) {
44113 var s = me.S;
44114 var i = lowbits(me.i + 1); var t = s[i];
44115 var j = lowbits(me.j + t); var u = s[j];
44116 s[i] = u;
44117 s[j] = t;
44118 var r = s[lowbits(t + u)];
44119 while (--count) {
44120 i = lowbits(i + 1); t = s[i];
44121 j = lowbits(j + t); u = s[j];
44122 s[i] = u;
44123 s[j] = t;
44124 r = r * width + s[lowbits(t + u)];
44125 }
44126 me.i = i;
44127 me.j = j;
44128 return r;
44129 };
44130 // For robust unpredictability discard an initial batch of values.
44131 // See http://www.rsa.com/rsalabs/node.asp?id=2009
44132 me.g(width);
44133}
44134
44135//
44136// flatten()
44137// Converts an object tree to nested arrays of strings.
44138//
44139/** @param {Object=} result
44140 * @param {string=} prop
44141 * @param {string=} typ */
44142function flatten(obj, depth, result, prop, typ) {
44143 result = [];
44144 typ = typeof(obj);
44145 if (depth && typ == 'object') {
44146 for (prop in obj) {
44147 if (prop.indexOf('S') < 5) { // Avoid FF3 bug (local/sessionStorage)
44148 try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}
44149 }
44150 }
44151 }
44152 return (result.length ? result : obj + (typ != 'string' ? '\0' : ''));
44153}
44154
44155//
44156// mixkey()
44157// Mixes a string seed into a key that is an array of integers, and
44158// returns a shortened string seed that is equivalent to the result key.
44159//
44160/** @param {number=} smear
44161 * @param {number=} j */
44162function mixkey(seed, key, smear, j) {
44163 seed += ''; // Ensure the seed is a string
44164 smear = 0;
44165 for (j = 0; j < seed.length; j++) {
44166 key[lowbits(j)] =
44167 lowbits((smear ^= key[lowbits(j)] * 19) + seed.charCodeAt(j));
44168 }
44169 seed = '';
44170 for (j in key) { seed += String.fromCharCode(key[j]); }
44171 return seed;
44172}
44173
44174//
44175// lowbits()
44176// A quick "n mod width" for width a power of 2.
44177//
44178function lowbits(n) { return n & (width - 1); }
44179
44180//
44181// The following constants are related to IEEE 754 limits.
44182//
44183startdenom = math.pow(width, chunks);
44184significance = math.pow(2, significance);
44185overflow = significance * 2;
44186
44187//
44188// When seedrandom.js is loaded, we immediately mix a few bits
44189// from the built-in RNG into the entropy pool. Because we do
44190// not want to intefere with determinstic PRNG state later,
44191// seedrandom will not call math.random on its own again after
44192// initialization.
44193//
44194mixkey(math.random(), pool);
44195
44196// End anonymous scope, and pass initial values.
44197}(
44198 [], // pool: entropy pool starts empty
44199 numeric.seedrandom, // math: package containing random, pow, and seedrandom
44200 256, // width: each RC4 output is 0 <= x < 256
44201 6, // chunks: at least six RC4 outputs for each double
44202 52 // significance: there are 52 significant digits in a double
44203 ));
44204/* This file is a slightly modified version of quadprog.js from Alberto Santini.
44205 * It has been slightly modified by Sébastien Loisel to make sure that it handles
44206 * 0-based Arrays instead of 1-based Arrays.
44207 * License is in resources/LICENSE.quadprog */
44208(function(exports) {
44209
44210function base0to1(A) {
44211 if(typeof A !== "object") { return A; }
44212 var ret = [], i,n=A.length;
44213 for(i=0;i<n;i++) ret[i+1] = base0to1(A[i]);
44214 return ret;
44215}
44216function base1to0(A) {
44217 if(typeof A !== "object") { return A; }
44218 var ret = [], i,n=A.length;
44219 for(i=1;i<n;i++) ret[i-1] = base1to0(A[i]);
44220 return ret;
44221}
44222
44223function dpori(a, lda, n) {
44224 var i, j, k, kp1, t;
44225
44226 for (k = 1; k <= n; k = k + 1) {
44227 a[k][k] = 1 / a[k][k];
44228 t = -a[k][k];
44229 //~ dscal(k - 1, t, a[1][k], 1);
44230 for (i = 1; i < k; i = i + 1) {
44231 a[i][k] = t * a[i][k];
44232 }
44233
44234 kp1 = k + 1;
44235 if (n < kp1) {
44236 break;
44237 }
44238 for (j = kp1; j <= n; j = j + 1) {
44239 t = a[k][j];
44240 a[k][j] = 0;
44241 //~ daxpy(k, t, a[1][k], 1, a[1][j], 1);
44242 for (i = 1; i <= k; i = i + 1) {
44243 a[i][j] = a[i][j] + (t * a[i][k]);
44244 }
44245 }
44246 }
44247
44248}
44249
44250function dposl(a, lda, n, b) {
44251 var i, k, kb, t;
44252
44253 for (k = 1; k <= n; k = k + 1) {
44254 //~ t = ddot(k - 1, a[1][k], 1, b[1], 1);
44255 t = 0;
44256 for (i = 1; i < k; i = i + 1) {
44257 t = t + (a[i][k] * b[i]);
44258 }
44259
44260 b[k] = (b[k] - t) / a[k][k];
44261 }
44262
44263 for (kb = 1; kb <= n; kb = kb + 1) {
44264 k = n + 1 - kb;
44265 b[k] = b[k] / a[k][k];
44266 t = -b[k];
44267 //~ daxpy(k - 1, t, a[1][k], 1, b[1], 1);
44268 for (i = 1; i < k; i = i + 1) {
44269 b[i] = b[i] + (t * a[i][k]);
44270 }
44271 }
44272}
44273
44274function dpofa(a, lda, n, info) {
44275 var i, j, jm1, k, t, s;
44276
44277 for (j = 1; j <= n; j = j + 1) {
44278 info[1] = j;
44279 s = 0;
44280 jm1 = j - 1;
44281 if (jm1 < 1) {
44282 s = a[j][j] - s;
44283 if (s <= 0) {
44284 break;
44285 }
44286 a[j][j] = Math.sqrt(s);
44287 } else {
44288 for (k = 1; k <= jm1; k = k + 1) {
44289 //~ t = a[k][j] - ddot(k - 1, a[1][k], 1, a[1][j], 1);
44290 t = a[k][j];
44291 for (i = 1; i < k; i = i + 1) {
44292 t = t - (a[i][j] * a[i][k]);
44293 }
44294 t = t / a[k][k];
44295 a[k][j] = t;
44296 s = s + t * t;
44297 }
44298 s = a[j][j] - s;
44299 if (s <= 0) {
44300 break;
44301 }
44302 a[j][j] = Math.sqrt(s);
44303 }
44304 info[1] = 0;
44305 }
44306}
44307
44308function qpgen2(dmat, dvec, fddmat, n, sol, crval, amat,
44309 bvec, fdamat, q, meq, iact, nact, iter, work, ierr) {
44310
44311 var i, j, l, l1, info, it1, iwzv, iwrv, iwrm, iwsv, iwuv, nvl, r, iwnbv,
44312 temp, sum, t1, tt, gc, gs, nu,
44313 t1inf, t2min,
44314 vsmall, tmpa, tmpb,
44315 go;
44316
44317 r = Math.min(n, q);
44318 l = 2 * n + (r * (r + 5)) / 2 + 2 * q + 1;
44319
44320 vsmall = 1.0e-60;
44321 do {
44322 vsmall = vsmall + vsmall;
44323 tmpa = 1 + 0.1 * vsmall;
44324 tmpb = 1 + 0.2 * vsmall;
44325 } while (tmpa <= 1 || tmpb <= 1);
44326
44327 for (i = 1; i <= n; i = i + 1) {
44328 work[i] = dvec[i];
44329 }
44330 for (i = n + 1; i <= l; i = i + 1) {
44331 work[i] = 0;
44332 }
44333 for (i = 1; i <= q; i = i + 1) {
44334 iact[i] = 0;
44335 }
44336
44337 info = [];
44338
44339 if (ierr[1] === 0) {
44340 dpofa(dmat, fddmat, n, info);
44341 if (info[1] !== 0) {
44342 ierr[1] = 2;
44343 return;
44344 }
44345 dposl(dmat, fddmat, n, dvec);
44346 dpori(dmat, fddmat, n);
44347 } else {
44348 for (j = 1; j <= n; j = j + 1) {
44349 sol[j] = 0;
44350 for (i = 1; i <= j; i = i + 1) {
44351 sol[j] = sol[j] + dmat[i][j] * dvec[i];
44352 }
44353 }
44354 for (j = 1; j <= n; j = j + 1) {
44355 dvec[j] = 0;
44356 for (i = j; i <= n; i = i + 1) {
44357 dvec[j] = dvec[j] + dmat[j][i] * sol[i];
44358 }
44359 }
44360 }
44361
44362 crval[1] = 0;
44363 for (j = 1; j <= n; j = j + 1) {
44364 sol[j] = dvec[j];
44365 crval[1] = crval[1] + work[j] * sol[j];
44366 work[j] = 0;
44367 for (i = j + 1; i <= n; i = i + 1) {
44368 dmat[i][j] = 0;
44369 }
44370 }
44371 crval[1] = -crval[1] / 2;
44372 ierr[1] = 0;
44373
44374 iwzv = n;
44375 iwrv = iwzv + n;
44376 iwuv = iwrv + r;
44377 iwrm = iwuv + r + 1;
44378 iwsv = iwrm + (r * (r + 1)) / 2;
44379 iwnbv = iwsv + q;
44380
44381 for (i = 1; i <= q; i = i + 1) {
44382 sum = 0;
44383 for (j = 1; j <= n; j = j + 1) {
44384 sum = sum + amat[j][i] * amat[j][i];
44385 }
44386 work[iwnbv + i] = Math.sqrt(sum);
44387 }
44388 nact = 0;
44389 iter[1] = 0;
44390 iter[2] = 0;
44391
44392 function fn_goto_50() {
44393 iter[1] = iter[1] + 1;
44394
44395 l = iwsv;
44396 for (i = 1; i <= q; i = i + 1) {
44397 l = l + 1;
44398 sum = -bvec[i];
44399 for (j = 1; j <= n; j = j + 1) {
44400 sum = sum + amat[j][i] * sol[j];
44401 }
44402 if (Math.abs(sum) < vsmall) {
44403 sum = 0;
44404 }
44405 if (i > meq) {
44406 work[l] = sum;
44407 } else {
44408 work[l] = -Math.abs(sum);
44409 if (sum > 0) {
44410 for (j = 1; j <= n; j = j + 1) {
44411 amat[j][i] = -amat[j][i];
44412 }
44413 bvec[i] = -bvec[i];
44414 }
44415 }
44416 }
44417
44418 for (i = 1; i <= nact; i = i + 1) {
44419 work[iwsv + iact[i]] = 0;
44420 }
44421
44422 nvl = 0;
44423 temp = 0;
44424 for (i = 1; i <= q; i = i + 1) {
44425 if (work[iwsv + i] < temp * work[iwnbv + i]) {
44426 nvl = i;
44427 temp = work[iwsv + i] / work[iwnbv + i];
44428 }
44429 }
44430 if (nvl === 0) {
44431 return 999;
44432 }
44433
44434 return 0;
44435 }
44436
44437 function fn_goto_55() {
44438 for (i = 1; i <= n; i = i + 1) {
44439 sum = 0;
44440 for (j = 1; j <= n; j = j + 1) {
44441 sum = sum + dmat[j][i] * amat[j][nvl];
44442 }
44443 work[i] = sum;
44444 }
44445
44446 l1 = iwzv;
44447 for (i = 1; i <= n; i = i + 1) {
44448 work[l1 + i] = 0;
44449 }
44450 for (j = nact + 1; j <= n; j = j + 1) {
44451 for (i = 1; i <= n; i = i + 1) {
44452 work[l1 + i] = work[l1 + i] + dmat[i][j] * work[j];
44453 }
44454 }
44455
44456 t1inf = true;
44457 for (i = nact; i >= 1; i = i - 1) {
44458 sum = work[i];
44459 l = iwrm + (i * (i + 3)) / 2;
44460 l1 = l - i;
44461 for (j = i + 1; j <= nact; j = j + 1) {
44462 sum = sum - work[l] * work[iwrv + j];
44463 l = l + j;
44464 }
44465 sum = sum / work[l1];
44466 work[iwrv + i] = sum;
44467 if (iact[i] < meq) {
44468 // continue;
44469 break;
44470 }
44471 if (sum < 0) {
44472 // continue;
44473 break;
44474 }
44475 t1inf = false;
44476 it1 = i;
44477 }
44478
44479 if (!t1inf) {
44480 t1 = work[iwuv + it1] / work[iwrv + it1];
44481 for (i = 1; i <= nact; i = i + 1) {
44482 if (iact[i] < meq) {
44483 // continue;
44484 break;
44485 }
44486 if (work[iwrv + i] < 0) {
44487 // continue;
44488 break;
44489 }
44490 temp = work[iwuv + i] / work[iwrv + i];
44491 if (temp < t1) {
44492 t1 = temp;
44493 it1 = i;
44494 }
44495 }
44496 }
44497
44498 sum = 0;
44499 for (i = iwzv + 1; i <= iwzv + n; i = i + 1) {
44500 sum = sum + work[i] * work[i];
44501 }
44502 if (Math.abs(sum) <= vsmall) {
44503 if (t1inf) {
44504 ierr[1] = 1;
44505 // GOTO 999
44506 return 999;
44507 } else {
44508 for (i = 1; i <= nact; i = i + 1) {
44509 work[iwuv + i] = work[iwuv + i] - t1 * work[iwrv + i];
44510 }
44511 work[iwuv + nact + 1] = work[iwuv + nact + 1] + t1;
44512 // GOTO 700
44513 return 700;
44514 }
44515 } else {
44516 sum = 0;
44517 for (i = 1; i <= n; i = i + 1) {
44518 sum = sum + work[iwzv + i] * amat[i][nvl];
44519 }
44520 tt = -work[iwsv + nvl] / sum;
44521 t2min = true;
44522 if (!t1inf) {
44523 if (t1 < tt) {
44524 tt = t1;
44525 t2min = false;
44526 }
44527 }
44528
44529 for (i = 1; i <= n; i = i + 1) {
44530 sol[i] = sol[i] + tt * work[iwzv + i];
44531 if (Math.abs(sol[i]) < vsmall) {
44532 sol[i] = 0;
44533 }
44534 }
44535
44536 crval[1] = crval[1] + tt * sum * (tt / 2 + work[iwuv + nact + 1]);
44537 for (i = 1; i <= nact; i = i + 1) {
44538 work[iwuv + i] = work[iwuv + i] - tt * work[iwrv + i];
44539 }
44540 work[iwuv + nact + 1] = work[iwuv + nact + 1] + tt;
44541
44542 if (t2min) {
44543 nact = nact + 1;
44544 iact[nact] = nvl;
44545
44546 l = iwrm + ((nact - 1) * nact) / 2 + 1;
44547 for (i = 1; i <= nact - 1; i = i + 1) {
44548 work[l] = work[i];
44549 l = l + 1;
44550 }
44551
44552 if (nact === n) {
44553 work[l] = work[n];
44554 } else {
44555 for (i = n; i >= nact + 1; i = i - 1) {
44556 if (work[i] === 0) {
44557 // continue;
44558 break;
44559 }
44560 gc = Math.max(Math.abs(work[i - 1]), Math.abs(work[i]));
44561 gs = Math.min(Math.abs(work[i - 1]), Math.abs(work[i]));
44562 if (work[i - 1] >= 0) {
44563 temp = Math.abs(gc * Math.sqrt(1 + gs * gs / (gc * gc)));
44564 } else {
44565 temp = -Math.abs(gc * Math.sqrt(1 + gs * gs / (gc * gc)));
44566 }
44567 gc = work[i - 1] / temp;
44568 gs = work[i] / temp;
44569
44570 if (gc === 1) {
44571 // continue;
44572 break;
44573 }
44574 if (gc === 0) {
44575 work[i - 1] = gs * temp;
44576 for (j = 1; j <= n; j = j + 1) {
44577 temp = dmat[j][i - 1];
44578 dmat[j][i - 1] = dmat[j][i];
44579 dmat[j][i] = temp;
44580 }
44581 } else {
44582 work[i - 1] = temp;
44583 nu = gs / (1 + gc);
44584 for (j = 1; j <= n; j = j + 1) {
44585 temp = gc * dmat[j][i - 1] + gs * dmat[j][i];
44586 dmat[j][i] = nu * (dmat[j][i - 1] + temp) - dmat[j][i];
44587 dmat[j][i - 1] = temp;
44588
44589 }
44590 }
44591 }
44592 work[l] = work[nact];
44593 }
44594 } else {
44595 sum = -bvec[nvl];
44596 for (j = 1; j <= n; j = j + 1) {
44597 sum = sum + sol[j] * amat[j][nvl];
44598 }
44599 if (nvl > meq) {
44600 work[iwsv + nvl] = sum;
44601 } else {
44602 work[iwsv + nvl] = -Math.abs(sum);
44603 if (sum > 0) {
44604 for (j = 1; j <= n; j = j + 1) {
44605 amat[j][nvl] = -amat[j][nvl];
44606 }
44607 bvec[nvl] = -bvec[nvl];
44608 }
44609 }
44610 // GOTO 700
44611 return 700;
44612 }
44613 }
44614
44615 return 0;
44616 }
44617
44618 function fn_goto_797() {
44619 l = iwrm + (it1 * (it1 + 1)) / 2 + 1;
44620 l1 = l + it1;
44621 if (work[l1] === 0) {
44622 // GOTO 798
44623 return 798;
44624 }
44625 gc = Math.max(Math.abs(work[l1 - 1]), Math.abs(work[l1]));
44626 gs = Math.min(Math.abs(work[l1 - 1]), Math.abs(work[l1]));
44627 if (work[l1 - 1] >= 0) {
44628 temp = Math.abs(gc * Math.sqrt(1 + gs * gs / (gc * gc)));
44629 } else {
44630 temp = -Math.abs(gc * Math.sqrt(1 + gs * gs / (gc * gc)));
44631 }
44632 gc = work[l1 - 1] / temp;
44633 gs = work[l1] / temp;
44634
44635 if (gc === 1) {
44636 // GOTO 798
44637 return 798;
44638 }
44639 if (gc === 0) {
44640 for (i = it1 + 1; i <= nact; i = i + 1) {
44641 temp = work[l1 - 1];
44642 work[l1 - 1] = work[l1];
44643 work[l1] = temp;
44644 l1 = l1 + i;
44645 }
44646 for (i = 1; i <= n; i = i + 1) {
44647 temp = dmat[i][it1];
44648 dmat[i][it1] = dmat[i][it1 + 1];
44649 dmat[i][it1 + 1] = temp;
44650 }
44651 } else {
44652 nu = gs / (1 + gc);
44653 for (i = it1 + 1; i <= nact; i = i + 1) {
44654 temp = gc * work[l1 - 1] + gs * work[l1];
44655 work[l1] = nu * (work[l1 - 1] + temp) - work[l1];
44656 work[l1 - 1] = temp;
44657 l1 = l1 + i;
44658 }
44659 for (i = 1; i <= n; i = i + 1) {
44660 temp = gc * dmat[i][it1] + gs * dmat[i][it1 + 1];
44661 dmat[i][it1 + 1] = nu * (dmat[i][it1] + temp) - dmat[i][it1 + 1];
44662 dmat[i][it1] = temp;
44663 }
44664 }
44665
44666 return 0;
44667 }
44668
44669 function fn_goto_798() {
44670 l1 = l - it1;
44671 for (i = 1; i <= it1; i = i + 1) {
44672 work[l1] = work[l];
44673 l = l + 1;
44674 l1 = l1 + 1;
44675 }
44676
44677 work[iwuv + it1] = work[iwuv + it1 + 1];
44678 iact[it1] = iact[it1 + 1];
44679 it1 = it1 + 1;
44680 if (it1 < nact) {
44681 // GOTO 797
44682 return 797;
44683 }
44684
44685 return 0;
44686 }
44687
44688 function fn_goto_799() {
44689 work[iwuv + nact] = work[iwuv + nact + 1];
44690 work[iwuv + nact + 1] = 0;
44691 iact[nact] = 0;
44692 nact = nact - 1;
44693 iter[2] = iter[2] + 1;
44694
44695 return 0;
44696 }
44697
44698 go = 0;
44699 while (true) {
44700 go = fn_goto_50();
44701 if (go === 999) {
44702 return;
44703 }
44704 while (true) {
44705 go = fn_goto_55();
44706 if (go === 0) {
44707 break;
44708 }
44709 if (go === 999) {
44710 return;
44711 }
44712 if (go === 700) {
44713 if (it1 === nact) {
44714 fn_goto_799();
44715 } else {
44716 while (true) {
44717 fn_goto_797();
44718 go = fn_goto_798();
44719 if (go !== 797) {
44720 break;
44721 }
44722 }
44723 fn_goto_799();
44724 }
44725 }
44726 }
44727 }
44728
44729}
44730
44731function solveQP(Dmat, dvec, Amat, bvec, meq, factorized) {
44732 Dmat = base0to1(Dmat);
44733 dvec = base0to1(dvec);
44734 Amat = base0to1(Amat);
44735 var i, n, q,
44736 nact, r,
44737 crval = [], iact = [], sol = [], work = [], iter = [],
44738 message;
44739
44740 meq = meq || 0;
44741 factorized = factorized ? base0to1(factorized) : [undefined, 0];
44742 bvec = bvec ? base0to1(bvec) : [];
44743
44744 // In Fortran the array index starts from 1
44745 n = Dmat.length - 1;
44746 q = Amat[1].length - 1;
44747
44748 if (!bvec) {
44749 for (i = 1; i <= q; i = i + 1) {
44750 bvec[i] = 0;
44751 }
44752 }
44753 for (i = 1; i <= q; i = i + 1) {
44754 iact[i] = 0;
44755 }
44756 nact = 0;
44757 r = Math.min(n, q);
44758 for (i = 1; i <= n; i = i + 1) {
44759 sol[i] = 0;
44760 }
44761 crval[1] = 0;
44762 for (i = 1; i <= (2 * n + (r * (r + 5)) / 2 + 2 * q + 1); i = i + 1) {
44763 work[i] = 0;
44764 }
44765 for (i = 1; i <= 2; i = i + 1) {
44766 iter[i] = 0;
44767 }
44768
44769 qpgen2(Dmat, dvec, n, n, sol, crval, Amat,
44770 bvec, n, q, meq, iact, nact, iter, work, factorized);
44771
44772 message = "";
44773 if (factorized[1] === 1) {
44774 message = "constraints are inconsistent, no solution!";
44775 }
44776 if (factorized[1] === 2) {
44777 message = "matrix D in quadratic function is not positive definite!";
44778 }
44779
44780 return {
44781 solution: base1to0(sol),
44782 value: base1to0(crval),
44783 unconstrained_solution: base1to0(dvec),
44784 iterations: base1to0(iter),
44785 iact: base1to0(iact),
44786 message: message
44787 };
44788}
44789exports.solveQP = solveQP;
44790}(numeric));
44791/*
44792Shanti Rao sent me this routine by private email. I had to modify it
44793slightly to work on Arrays instead of using a Matrix object.
44794It is apparently translated from http://stitchpanorama.sourceforge.net/Python/svd.py
44795*/
44796
44797numeric.svd= function svd(A) {
44798 var temp;
44799//Compute the thin SVD from G. H. Golub and C. Reinsch, Numer. Math. 14, 403-420 (1970)
44800 var prec= numeric.epsilon; //Math.pow(2,-52) // assumes double prec
44801 var tolerance= 1.e-64/prec;
44802 var itmax= 50;
44803 var c=0;
44804 var i=0;
44805 var j=0;
44806 var k=0;
44807 var l=0;
44808
44809 var u= numeric.clone(A);
44810 var m= u.length;
44811
44812 var n= u[0].length;
44813
44814 if (m < n) throw "Need more rows than columns"
44815
44816 var e = new Array(n);
44817 var q = new Array(n);
44818 for (i=0; i<n; i++) e[i] = q[i] = 0.0;
44819 var v = numeric.rep([n,n],0);
44820// v.zero();
44821
44822 function pythag(a,b)
44823 {
44824 a = Math.abs(a)
44825 b = Math.abs(b)
44826 if (a > b)
44827 return a*Math.sqrt(1.0+(b*b/a/a))
44828 else if (b == 0.0)
44829 return a
44830 return b*Math.sqrt(1.0+(a*a/b/b))
44831 }
44832
44833 //Householder's reduction to bidiagonal form
44834
44835 var f= 0.0;
44836 var g= 0.0;
44837 var h= 0.0;
44838 var x= 0.0;
44839 var y= 0.0;
44840 var z= 0.0;
44841 var s= 0.0;
44842
44843 for (i=0; i < n; i++)
44844 {
44845 e[i]= g;
44846 s= 0.0;
44847 l= i+1;
44848 for (j=i; j < m; j++)
44849 s += (u[j][i]*u[j][i]);
44850 if (s <= tolerance)
44851 g= 0.0;
44852 else
44853 {
44854 f= u[i][i];
44855 g= Math.sqrt(s);
44856 if (f >= 0.0) g= -g;
44857 h= f*g-s
44858 u[i][i]=f-g;
44859 for (j=l; j < n; j++)
44860 {
44861 s= 0.0
44862 for (k=i; k < m; k++)
44863 s += u[k][i]*u[k][j]
44864 f= s/h
44865 for (k=i; k < m; k++)
44866 u[k][j]+=f*u[k][i]
44867 }
44868 }
44869 q[i]= g
44870 s= 0.0
44871 for (j=l; j < n; j++)
44872 s= s + u[i][j]*u[i][j]
44873 if (s <= tolerance)
44874 g= 0.0
44875 else
44876 {
44877 f= u[i][i+1]
44878 g= Math.sqrt(s)
44879 if (f >= 0.0) g= -g
44880 h= f*g - s
44881 u[i][i+1] = f-g;
44882 for (j=l; j < n; j++) e[j]= u[i][j]/h
44883 for (j=l; j < m; j++)
44884 {
44885 s=0.0
44886 for (k=l; k < n; k++)
44887 s += (u[j][k]*u[i][k])
44888 for (k=l; k < n; k++)
44889 u[j][k]+=s*e[k]
44890 }
44891 }
44892 y= Math.abs(q[i])+Math.abs(e[i])
44893 if (y>x)
44894 x=y
44895 }
44896
44897 // accumulation of right hand gtransformations
44898 for (i=n-1; i != -1; i+= -1)
44899 {
44900 if (g != 0.0)
44901 {
44902 h= g*u[i][i+1]
44903 for (j=l; j < n; j++)
44904 v[j][i]=u[i][j]/h
44905 for (j=l; j < n; j++)
44906 {
44907 s=0.0
44908 for (k=l; k < n; k++)
44909 s += u[i][k]*v[k][j]
44910 for (k=l; k < n; k++)
44911 v[k][j]+=(s*v[k][i])
44912 }
44913 }
44914 for (j=l; j < n; j++)
44915 {
44916 v[i][j] = 0;
44917 v[j][i] = 0;
44918 }
44919 v[i][i] = 1;
44920 g= e[i]
44921 l= i
44922 }
44923
44924 // accumulation of left hand transformations
44925 for (i=n-1; i != -1; i+= -1)
44926 {
44927 l= i+1
44928 g= q[i]
44929 for (j=l; j < n; j++)
44930 u[i][j] = 0;
44931 if (g != 0.0)
44932 {
44933 h= u[i][i]*g
44934 for (j=l; j < n; j++)
44935 {
44936 s=0.0
44937 for (k=l; k < m; k++) s += u[k][i]*u[k][j];
44938 f= s/h
44939 for (k=i; k < m; k++) u[k][j]+=f*u[k][i];
44940 }
44941 for (j=i; j < m; j++) u[j][i] = u[j][i]/g;
44942 }
44943 else
44944 for (j=i; j < m; j++) u[j][i] = 0;
44945 u[i][i] += 1;
44946 }
44947
44948 // diagonalization of the bidiagonal form
44949 prec= prec*x
44950 for (k=n-1; k != -1; k+= -1)
44951 {
44952 for (var iteration=0; iteration < itmax; iteration++)
44953 { // test f splitting
44954 var test_convergence = false
44955 for (l=k; l != -1; l+= -1)
44956 {
44957 if (Math.abs(e[l]) <= prec)
44958 { test_convergence= true
44959 break
44960 }
44961 if (Math.abs(q[l-1]) <= prec)
44962 break
44963 }
44964 if (!test_convergence)
44965 { // cancellation of e[l] if l>0
44966 c= 0.0
44967 s= 1.0
44968 var l1= l-1
44969 for (i =l; i<k+1; i++)
44970 {
44971 f= s*e[i]
44972 e[i]= c*e[i]
44973 if (Math.abs(f) <= prec)
44974 break
44975 g= q[i]
44976 h= pythag(f,g)
44977 q[i]= h
44978 c= g/h
44979 s= -f/h
44980 for (j=0; j < m; j++)
44981 {
44982 y= u[j][l1]
44983 z= u[j][i]
44984 u[j][l1] = y*c+(z*s)
44985 u[j][i] = -y*s+(z*c)
44986 }
44987 }
44988 }
44989 // test f convergence
44990 z= q[k]
44991 if (l== k)
44992 { //convergence
44993 if (z<0.0)
44994 { //q[k] is made non-negative
44995 q[k]= -z
44996 for (j=0; j < n; j++)
44997 v[j][k] = -v[j][k]
44998 }
44999 break //break out of iteration loop and move on to next k value
45000 }
45001 if (iteration >= itmax-1)
45002 throw 'Error: no convergence.'
45003 // shift from bottom 2x2 minor
45004 x= q[l]
45005 y= q[k-1]
45006 g= e[k-1]
45007 h= e[k]
45008 f= ((y-z)*(y+z)+(g-h)*(g+h))/(2.0*h*y)
45009 g= pythag(f,1.0)
45010 if (f < 0.0)
45011 f= ((x-z)*(x+z)+h*(y/(f-g)-h))/x
45012 else
45013 f= ((x-z)*(x+z)+h*(y/(f+g)-h))/x
45014 // next QR transformation
45015 c= 1.0
45016 s= 1.0
45017 for (i=l+1; i< k+1; i++)
45018 {
45019 g= e[i]
45020 y= q[i]
45021 h= s*g
45022 g= c*g
45023 z= pythag(f,h)
45024 e[i-1]= z
45025 c= f/z
45026 s= h/z
45027 f= x*c+g*s
45028 g= -x*s+g*c
45029 h= y*s
45030 y= y*c
45031 for (j=0; j < n; j++)
45032 {
45033 x= v[j][i-1]
45034 z= v[j][i]
45035 v[j][i-1] = x*c+z*s
45036 v[j][i] = -x*s+z*c
45037 }
45038 z= pythag(f,h)
45039 q[i-1]= z
45040 c= f/z
45041 s= h/z
45042 f= c*g+s*y
45043 x= -s*g+c*y
45044 for (j=0; j < m; j++)
45045 {
45046 y= u[j][i-1]
45047 z= u[j][i]
45048 u[j][i-1] = y*c+z*s
45049 u[j][i] = -y*s+z*c
45050 }
45051 }
45052 e[l]= 0.0
45053 e[k]= f
45054 q[k]= x
45055 }
45056 }
45057
45058 //vt= transpose(v)
45059 //return (u,q,vt)
45060 for (i=0;i<q.length; i++)
45061 if (q[i] < prec) q[i] = 0
45062
45063 //sort eigenvalues
45064 for (i=0; i< n; i++)
45065 {
45066 //writeln(q)
45067 for (j=i-1; j >= 0; j--)
45068 {
45069 if (q[j] < q[i])
45070 {
45071 // writeln(i,'-',j)
45072 c = q[j]
45073 q[j] = q[i]
45074 q[i] = c
45075 for(k=0;k<u.length;k++) { temp = u[k][i]; u[k][i] = u[k][j]; u[k][j] = temp; }
45076 for(k=0;k<v.length;k++) { temp = v[k][i]; v[k][i] = v[k][j]; v[k][j] = temp; }
45077// u.swapCols(i,j)
45078// v.swapCols(i,j)
45079 i = j
45080 }
45081 }
45082 }
45083
45084 return {U:u,S:q,V:v}
45085};
45086
45087
45088}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
45089},{}],17:[function(require,module,exports){
45090// http://cs.stanford.edu/people/karpathy/convnetjs/
45091// https://github.com/junku901/dnn
45092var NN = {};
45093
45094NN.sigmoid = function(x) {
45095 var sigmoid = (1. / (1 + Math.exp(-x)))
45096 if(sigmoid ==1) {
45097 // console.warn("Something Wrong!! Sigmoid Function returns 1. Probably javascript float precision problem?\nSlightly Controlled value to 1 - 1e-14")
45098 sigmoid = 0.99999999999999; // Javascript Float Precision Problem.. This is a limit of javascript.
45099 } else if(sigmoid ==0) {
45100 // console.warn("Something Wrong!! Sigmoid Function returns 0. Probably javascript float precision problem?\nSlightly Controlled value to 1e-14")
45101 sigmoid = 1e-14;
45102 }
45103 return sigmoid; // sigmoid cannot be 0 or 1;;
45104}
45105
45106NN.dSigmoid = function(x){
45107 a = B.sigmoid(x);
45108 return a * (1. - a);
45109}
45110
45111module.exports = NN;
45112},{}],18:[function(require,module,exports){
45113var NN = require("../neural");
45114var R, M;
45115
45116var RBM = function (rlab, settings) {
45117 R = rlab;
45118 M = R.M;
45119 Object.assign(this, settings);
45120 this.settings = {
45121 'log level' : 1 // 0 : nothing, 1 : info, 2: warn
45122 };
45123 var a = 1. / this.nVisible;
45124 this.W = this.W || M.randomM(this.nVisible,this.nHidden,-a,a);
45125 this.hbias = this.hbias || M.newV(this.nHidden);
45126 this.vbias = this.vbias || M.newV(this.nVisible);
45127}
45128
45129RBM.prototype.train = function(settings) {
45130 var lr = settings.lr||0.8;
45131 var k = settings.k||1;
45132 var epochs = settings.epochs||1500;
45133 this.input = settings.input||this.input;
45134
45135 var i,j;
45136 var currentProgress = 1;
45137 for(i=0;i<epochs;i++) {
45138 /* CD - k . Contrastive Divergence */
45139 var ph = this.sampleHgivenV(this.input);
45140 var phMean = ph[0], phSample = ph[1];
45141 var chainStart = phSample;
45142 var nvMeans, nvSamples, nhMeans, nhSamples;
45143
45144 for(j=0 ; j<k ; j++) {
45145 if (j==0) {
45146 var gibbsVH = this.gibbsHVH(chainStart);
45147 nvMeans = gibbsVH[0], nvSamples = gibbsVH[1], nhMeans = gibbsVH[2], nhSamples = gibbsVH[3];
45148 } else {
45149 var gibbsVH = this.gibbsHVH(nhSamples);
45150 nvMeans = gibbsVH[0], nvSamples = gibbsVH[1], nhMeans = gibbsVH[2], nhSamples = gibbsVH[3];
45151 }
45152 }
45153 // ((input^t*phMean)-(nvSample^t*nhMeans))*1/input.length
45154 var deltaW = this.input.tr().dot(phMean).sub(nvSamples.tr().dot(nhMeans)).mul(1./this.input.length);
45155 // deltaW = (input*phMean)-(nvSample^t * nhMeans)*1/input.length
45156 var deltaVbias = this.input.sub(nvSamples).colMean();
45157 // deltaHbias = (phSample - nhMeans).mean(row)
45158 var deltaHbias = phSample.sub(nhMeans).colMean();
45159 // W += deltaW*lr
45160 this.W = this.W.add(deltaW.mul(lr));
45161 // vbias += deltaVbias*lr
45162 this.vbias = this.vbias.add(deltaVbias.dot(lr));
45163 // hbias += deltaHbias*lr
45164 this.hbias = this.hbias.add(deltaHbias.dot(lr));
45165 if(this.settings['log level'] > 0) {
45166 var progress = (1.*i/epochs)*100;
45167 if(progress > currentProgress) {
45168 console.log("RBM",progress.toFixed(0),"% Completed.");
45169 currentProgress+=8;
45170 }
45171 }
45172 }
45173 if(this.settings['log level'] > 0)
45174 console.log("RBM Final Cross Entropy : ",this.getReconstructionCrossEntropy())
45175};
45176
45177RBM.prototype.propup = function(v) {
45178 // sigmoid(v*W+hbias)
45179 return v.dot(this.W).addMV(this.hbias).mapM(NN.sigmoid);
45180};
45181
45182RBM.prototype.probToBinaryMat = function(m) {
45183 return M.mapM(m, (x)=>(Math.random() < m[i][j])?1:0);
45184};
45185
45186RBM.prototype.propdown = function(h) {
45187 return h.dot(this.W.tr()).addMV(this.vbias).mapM(NN.sigmoid);
45188};
45189
45190RBM.prototype.sampleHgivenV = function(v0_sample) {
45191 var h1_mean = this.propup(v0_sample);
45192 var h1_sample = this.probToBinaryMat(h1_mean);
45193 return [h1_mean,h1_sample];
45194};
45195
45196RBM.prototype.sampleVgivenH = function(h0_sample) {
45197 var v1_mean = this.propdown(h0_sample);
45198 var v1_sample = this.probToBinaryMat(v1_mean);
45199 return [v1_mean,v1_sample];
45200};
45201
45202RBM.prototype.gibbsHVH = function(h0_sample) {
45203 var v1 = this.sampleVgivenH(h0_sample);
45204 var h1 = this.sampleHgivenV(v1[1]);
45205 return [v1[0],v1[1],h1[0],h1[1]];
45206};
45207
45208RBM.prototype.reconstruct = function(v) {
45209 var h = v.dot(this.W).addMV(this.hbias).mapM(NN.sigmoid);
45210 return h.dot(this.W.tr()).addMV(this.vbias).mapM(NN.sigmoid);
45211};
45212
45213RBM.prototype.getReconstructionCrossEntropy = function() {
45214 var reconstructedV = this.reconstruct(this.input);
45215 var a = M.mapMM(this.input, reconstructedV, function(x,y){
45216 return x*Math.log(y);
45217 });
45218
45219 var b = M.mapMM(this.input,reconstructedV,function(x,y){
45220 return (1-x)*Math.log(1-y);
45221 });
45222 var crossEntropy = -a.add(b).rowSum().mean();
45223 return crossEntropy
45224
45225};
45226
45227RBM.prototype.set = function(property,value) {
45228 this.settings[property] = value;
45229}
45230
45231module.exports = RBM;
45232},{"../neural":17}],19:[function(require,module,exports){
45233var R = require("./lib/math");
45234var _ = R._ = require("lodash");
45235R.Symbol = require("./lib/symbolic");
45236R.NN = require("./plugin/neural");
45237R.NN.RBM = require("./plugin/neural/rbm");
45238
45239// space 沒有加上機率參數 , 不能指定機率
45240R.samples = function(space, size, arg) {
45241 var arg = _.defaults(arg, {replace:true});
45242 if (arg.replace)
45243 return _.times(size, ()=>_.sample(space));
45244 else
45245 return _.sampleSize(space, size);
45246}
45247
45248// Global
45249R.debug = debug = function() {
45250 var arg = _.slice(arguments);
45251 console.debug.apply(console, arg);
45252}
45253
45254R.print = print = function() {
45255 var arg = _.slice(arguments);
45256 console.log.apply(console, arg);
45257}
45258
45259p = R.parse;
45260be = R.be;
45261
45262R.mixThisMap(Array.prototype, R, {
45263lu:"lu",
45264luSolve:"luSolve",
45265svd:"svd",
45266// "cdelsq",
45267// "clone",
45268rows:"rows",
45269cols:"cols",
45270row:"row",
45271col:"col",
45272tr:"tr",
45273inv:"inv",
45274// "all",
45275// "any",
45276// "same",
45277// "isFinite",
45278// "isNaN",
45279// "mapreduce",
45280// "complex",
45281det:"det",
45282// "norm2",
45283// "norm2Squared",
45284// "norm2inf",
45285dot:"dot",
45286// "dim",
45287eig:"eig",
45288// "sum",
45289rowSum:"rowSum",
45290colSum:"colSum",
45291rowMean:"rowMean",
45292colMean:"colMean",
45293addMV:"addMV",
45294mapM:"mapM",
45295mapMM:"mapMM",
45296flatM:"flatM",
45297fillVM:"fillVM",
45298fillMM:"fillMM",
45299getBlock:"getBlock",
45300setBlock:"setBlock",
45301getDiag:"getDiag",
45302diag:"diag",
45303// "parseFloat",
45304// "parseDate",
45305// "parseCSV",
45306// "toCSV",
45307mstr:"mstr",
45308// "sumM",
45309str:'astr',
45310print:'print',
45311});
45312
45313R.mixThis(Array.prototype, R, [
45314"max",
45315"min",
45316"sum",
45317"product",
45318"norm",
45319"mean",
45320"range",
45321"median",
45322"variance",
45323"deviation",
45324"sd",
45325"cov",
45326"cor",
45327"normalize",
45328"curve",
45329"hist",
45330"ihist",
45331"eval",
45332// +-*/%
45333"add",
45334"sub",
45335"mul",
45336"div",
45337"mod",
45338"neg",
45339// "inv", 和矩陣相衝
45340// logical
45341"and",
45342"or",
45343"xor",
45344"not",
45345// bits operation
45346"bnot",
45347"band",
45348"bor",
45349"bxor",
45350// function
45351"power",
45352// "dot", 和矩陣相衝
45353"sqrt",
45354"log",
45355"exp",
45356"abs",
45357"sin",
45358"cos",
45359"tan",
45360"asin",
45361"acos",
45362"atan",
45363"ceil",
45364"floor",
45365"round",
45366]);
45367
45368R.mixThisMap(Number.prototype, R, {
45369 str:'nstr',
45370 print:'print',
45371});
45372
45373R.mixThis(Number.prototype, R, [
45374 'eval',
45375 'add',
45376 'sub',
45377 'mul',
45378 'div',
45379 'mod',
45380 'power',
45381 'neg',
45382 'inv',
45383 'sqrt',
45384 'log',
45385 'exp',
45386 'abs',
45387 'sin',
45388 'cos',
45389 'tan',
45390 'asin',
45391 'acos',
45392 'atan',
45393 'ceil',
45394 'floor',
45395 'round',
45396]);
45397R.mixThisMap(Function.prototype, R, {
45398 add:'fadd',
45399 sub:'fsub',
45400 mul:'fmul',
45401 div:'fdiv',
45402 compose:'fcompose',
45403 eval:'feval',
45404 diff:'fdiff',
45405 integral:'fintegral',
45406});
45407R.mixThisMap(String.prototype, R, {str:'sstr',print:'print'});
45408R.mixThisMap(Object.prototype, R, {str:'ostr',print:'print'});
45409R.mixThisMap(Object.prototype, R, {
45410 proto:'proto',
45411 eq:'eq',
45412 neq:'neq',
45413 geq:'geq',
45414 leq:'leq',
45415 gt:'gt',
45416 lt:'lt',
45417});
45418
45419R.mixThisMap(Array.prototype, R._, {
45420// lodash
45421_chunk:'chunk',
45422_compact:'compact',
45423_concat:'concat',
45424_difference:'difference',
45425_differenceBy:'differenceBy',
45426_differenceWith:'differenceWith',
45427_drop:'drop',
45428_dropRight:'dropRight',
45429_dropRightWhile:'dropRightWhile',
45430_dropWhile:'dropWhile',
45431_fill:'fill',
45432_findIndex:'findIndex',
45433_findLastIndex:'findLastIndex',
45434_flatten:'flatten',
45435_flattenDeep:'flattenDeep',
45436_flattenDepth:'flattenDepth',
45437_fromPairs:'flattenPairs',
45438_head:'head',
45439_indexOf:'indexOf',
45440_initial:'initial',
45441_intersection:'intersection',
45442_intersectionBy:'intersectonBy',
45443_intersectionWith:'intersectionWith',
45444_join:'join',
45445_last:'last',
45446_lastIndexOf:'lastIndexOf',
45447_nth:'nth',
45448_pull:'pull',
45449_pullAll:'pullAll',
45450_pullAllBy:'pullAllBy',
45451_pullAllWith:'pullAllWith',
45452_pullAt:'pullAt',
45453_remove:'remove',
45454_reverse:'reverse',
45455_slice:'slice',
45456_sortedIndex:'sortedIndex',
45457_sortedIndexBy:'sortedIndexBy',
45458_sortedIndexOf:'sortedIndexOf',
45459_sortedLastIndex:'sortedLastIndex',
45460_sortedLastIndexBy:'sortedLastIndexBy',
45461_sortedLastIndexOf:'sortedLastIndexOf',
45462_sortedUniq:'sortedUniq',
45463_sortedUniqBy:'sortedUniqBy',
45464_tail:'tail',
45465_take:'take',
45466_takeRight:'takeRight',
45467_takeRightWhile:'takeRightWhile',
45468_takeWhile:'takeWhile',
45469_union:'union',
45470_unionBy:'unionBy',
45471_unionWith:'unionWith',
45472_uniq:'uniq',
45473_uniqBy:'uniqBy',
45474_uniqWith:'uniqWith',
45475_unzip:'unzip',
45476_unzipWith:'unzipWith',
45477_without:'without',
45478_xor:'xor',
45479_xorBy:'xorBy',
45480_xorWith:'xorWith',
45481_zip:'zip',
45482_zipObject:'zipObject',
45483_zipObjectDeep:'zipObjectDeep',
45484_zipWith:'zipWith',
45485// Collection
45486_countBy:'countBy',
45487// each→ forEach
45488// _eachRight → forEachRight
45489_every:'every',
45490_filter:'filter',
45491_find:'find',
45492_findLast:'findLast',
45493_flatMap:'flatMap',
45494_flatMapDeep:'flatMapDeep',
45495_flatMapDepth:'flatMapDepth',
45496_forEach:'forEach',
45497_forEachRight:'forEachRight',
45498_groupBy:'groupBy',
45499_includes:'includes',
45500_invokeMap:'invokeMap',
45501_keyBy:'keyBy',
45502_map:'map',
45503_orderBy:'orderBy',
45504_partition:'partition',
45505_reduce:'reduce',
45506_reduceRight:'reduceRight',
45507_reject:'reject',
45508_sample:'sample',
45509_sampleSize:'sampleSize',
45510_shuffle:'shuffle',
45511_size:'size',
45512_some:'some',
45513_sortBy:'sortBy',
45514});
45515
45516module.exports = R;
45517
45518// R.mixThis(Array.prototype, {str:R.astr}, ['str']);
45519// R.mixThisMap(Array.prototype, R, {str:'astr',print:'print'});
45520// R.mixThisMap(Object.prototype, R, {strM:'strM'});
45521// ==== Copy functions to R ======
45522// R.copyFunctions(R, D, "differential,integral".split(","));
45523// R.copyFunctions(R, Math, "abs,acos,asin,atan,ceil,cos,exp,floor,log,pow,random,round,sin,sqrt,tan".split(","));
45524
45525// R.copyFunctions(R, M, "solveLP,solveMP,ODE,minimize,complex,spline,linspace".split(","));
45526
45527// not include : bench, xxxeq, ccsXXX, cgrid,
45528// Complex = R.Complex;
45529// Ratio = R.Ratio;
45530
45531},{"./lib/math":7,"./lib/symbolic":11,"./plugin/neural":17,"./plugin/neural/rbm":18,"lodash":15}],20:[function(require,module,exports){
45532R=rlab=require("../rlab");
45533},{"../rlab":19}]},{},[20]);