forked from jiggzson/nerdamer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnerdamer.core.js
6039 lines (5502 loc) · 230 KB
/
nerdamer.core.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Author : Martin Donk
* Website : http://www.nerdamer.com
* Email : martin.r.donk@gmail.com
* Source : https://github.com/jiggzson/nerdamer
*/
var nerdamer = (function(imports) {
"use strict";
var version = '0.6.4',
_ = new Parser(), //nerdamer's parser
//import bigInt
bigInt = imports.bigInt,
Groups = {},
//container of pregenerated primes
PRIMES = [],
//this is the class which holds the utilities which are exported to the core
//All utility functions which are to be made available to the core should be added to this object
Utils = {},
//Settings
Settings = {
//the max number up to which to cache primes. Making this too high causes performance issues
init_primes: 1000,
exclude: [],
//If you don't care about division by zero for example then this can be set to true.
//Has some nasty side effects so choose carefully.
suppress_errors: false,
//the global used to invoke the libary to parse to a number. Normally cos(9) for example returns
//cos(9) for convenience but parse to number will always try to return a number if set to true.
PARSE2NUMBER: false,
//this flag forces the a clone to be returned when add, subtract, etc... is called
SAFE: false,
//the symbol to use for imaginary symbols
IMAGINARY: 'i'
},
//Add the groups. These have been reorganized as of v0.5.1 to make CP the highest group
//The groups that help with organizing during parsing. Note that for FN is still a function even
//when it's raised to a symbol, which typically results in an EX
N = Groups.N = 1, // A number
P = Groups.P = 2, // A number with a rational power e.g. 2^(3/5).
S = Groups.S = 3, // A single variable e.g. x.
EX = Groups.EX = 4, // An exponential
FN = Groups.FN = 5, // A function
PL = Groups.PL = 6, // A symbol/expression having same name with different powers e.g. 1/x + x^2
CB = Groups.CB = 7, // A symbol/expression composed of one or more variables through multiplication e.g. x*y
CP = Groups.CP = 8, // A symbol/expression composed of one variable and any other symbol or number x+1 or x+y
CONST_HASH = '#',
//GLOBALS
PARENTHESIS = 'parens',
//the function which represent vector
VECTOR = 'vector',
SQRT = 'sqrt',
ABS = 'abs',
//the storage container "memory" for parsed expressions
EXPRESSIONS = [],
//variables
VARS = {},
//the container used to store all the reserved functions
RESERVED = [],
WARNINGS = '',
/**
* Checks to see if value is one of nerdamer's reserved names
* @param {String} value
* @return boolean
*/
isReserved = Utils.isReserved = function(value) {
return RESERVED.indexOf(value) !== -1;
},
/**
* Use this when errors are suppressible
* @param {String} msg
*/
err = function(msg) {
if(!Settings.suppress_errors) throw new Error(msg);
},
/**
* Used to pass warnings or low severity errors about the library
* @type type
*/
warn = function(msg) {
WARNINGS += (msg+'\n');
},
/**
* Enforces rule: "must start with a letter or underscore and
* can have any number of underscores, letters, and numbers thereafter."
* @param name The name of the symbol being checked
* @param {String} typ - The type of symbols that's being validated
* @throws {Exception} - Throws an exception on fail
*/
validateName = Utils.validateName = function(name, typ) {
typ = typ || 'variable';
var regex = /^[a-z_][a-z\d\_]*$/gi;
if(!(regex.test( name)) ) {
throw new Error(name+' is not a valid '+typ+' name');
}
},
/**
* Finds intersection of two arrays
* @param {array} a
* @param {Array} b
* @returns {Array}
*/
intersection = Utils.intersection = function(a, b, compare_fn) {
var c = [];
if(a.length > b.length) {
var t = a; a = b; b = t;
}
b = b.slice();
var l = a.length, l2 = b.length;
for(var i=0; i<l; i++) {
var item = a[i];
for(var j=0; j<l2; j++) {
var item2 = b[j];
if(item2 === undefined) continue;
var equals = compare_fn ? compare_fn(item, item2) : item === item2;
if(equals) {
b[j] = undefined;
c.push(item);
continue;
}
}
}
return c;
},
/**
* Replace n! to fact(n)
* @param {String}
*/
insertFactorial = Utils.insertFactorial = function(expression) {
var factorial;
var regex = /(\d+|\w+)!/ig;
do {
factorial = regex.exec(expression);
if (factorial !== null) {
expression = expression.replace(factorial[0], 'fact(' + factorial[0] + ')').expression.replace('!', '');
}
} while(factorial);
return expression;
},
/**
* Checks if number is a prime number
* @param {Number} n - the number to be checked
*/
isPrime = Utils.isPrime = function(n) {
var q = Math.floor(Math.sqrt(n));
for (var i = 2; i <= q; i++) {
if (n % i === 0) return false;
}
return true;
},
/**
* Checks to see if a number or Symbol is a fraction
* @type {Number|Symbol} num
* @returns {boolean}
*/
isFraction = Utils.isFraction = function(num) {
if(isSymbol(num)) return isFraction(num.multiplier.toDecimal());
return (num % 1 !== 0);
},
/**
* Checks to see if the object provided is a Symbol
* @param {Object} obj
*/
isSymbol = Utils.isSymbol = function(obj) {
return (obj instanceof Symbol);
},
/**
*
* Checks to see if the object provided is a Vector
* @param {Object} obj
*/
isVector = Utils.isVector = function(obj) {
return (obj instanceof Vector);
},
/**
* Checks to see if the object provided is a Matrix
* @param {Object} obj
*/
isMatrix = Utils.isMatrix = function(obj) {
return (obj instanceof Matrix);
},
/**
* @param {Symbol} symbol
*/
isNumericSymbol = Utils.isNumericSymbol = function(symbol) {
return symbol.group === N;
},
/**
* Checks to see if the object provided is an Array
* @param {Object} arr
*/
isArray = Utils.isArray = function(arr) {
return arr instanceof Array;
},
/**
* Checks to see if a number is an integer
* @param {Number} num
*/
isInt = Utils.isInt = function(num) {
return num % 1 === 0;
},
/**
* @param {Number|Symbol} obj
* @returns {boolean}
*/
isNegative = Utils.isNegative = function(obj) {
if( isSymbol(obj) ) {
obj = obj.multiplier;
}
return obj.lessThan(0);
},
/**
* @param {String} str
* @returns {String} - returns a formatted string surrounded by brackets
*/
inBrackets = Utils.inBrackets = function(str) {
return '('+str+')';
},
/**
* A helper function to replace parts of string
* @param {String} str - The original string
* @param {Integer} from - The starting index
* @param {Integer} to - The ending index
* @param {String} with_str - The replacement string
* @returns {String} - A formatted string
*/
stringReplace = Utils.stringReplace = function(str, from, to, with_str) {
return str.substr(0, from)+with_str+str.substr(to, str.length);
},
/**
* the Parser uses this to check if it's allowed to convert the obj to type Symbol
* @obj {Object} obj
* @returns {boolean}
* @description
*/
customType = Utils.customType = function(obj) {
return obj !== undefined && obj.custom;
},
/**
* Checks to see if numbers are both negative or are both positive
* @param {Number} a
* @param {Number} b
* @returns {boolean}
*/
sameSign = Utils.sameSign = function(a, b) {
return (a < 0) === (b < 0);
},
/**
* A helper function to replace multiple occurences in a string. Takes multiple arguments
* @example format('{0} nice, {0} sweet')
* //returns 'something nice, something sweet'
*/
format = Utils.format = function() {
var args = [].slice.call(arguments),
str = args.shift();
var new_str = str.replace(/{(\d+)}/g, function(match, index) {
var arg = args[index];
return typeof arg === 'function' ? arg() : arg;
});
return new_str;
},
/**
* Returns an array of all the keys in an array
* @param {Object} obj
* @returns {Array}
*/
keys = Utils.keys = Object.keys,
/**
* Returns the first encountered item in an object. Items do not have a fixed order in objects
* so only use if you need any first random or if there's only one item in the object
* @param {Object} obj
* @returns {*}
*/
firstObject = Utils.firstObject = function(obj) {
for( var x in obj ) break;
return obj[x];
},
/**
* Returns the minimum number in an array
* @param {Array} arr
* @returns {Number}
*/
arrayMax = Utils.arrayMax = function(arr) {
return Math.max.apply(undefined, arr);
},
/**
* Returns the maximum number in an array
* @param {Array} arr
* @returns {Number}
*/
arrayMin = Utils.arrayMin = function(arr) {
return Math.min.apply(undefined, arr);
},
/**
* Clones array with clonable items
* @param {Array} arr
* @returns {Array}
*/
arrayClone = Utils.arrayClone = function(arr) {
var new_array = [], l = arr.length;
for(var i=0; i<l; i++) new_array[i] = arr[i].clone();
return new_array;
},
/**
* Rounds a number up to x decimal places
* @param {Number} x
* @param {Number} s
*/
round = Utils.round = function( x, s ) {
s = s || 14;
return Math.round( x*Math.pow( 10,s ) )/Math.pow( 10,s );
},
/**
* This method traverses the symbol structure and grabs all the variables in a symbol. The variable
* names are then returned in alphabetical order.
* @param {Symbol} obj
* @param {Object} vars - An object containing the variables. Do not pass this in as it generated
* automatically. In the future this will be a Collector object.
* @returns {String[]} - An array containing variable names
*/
variables = Utils.variables = function(obj, poly, vars) {
vars = vars || {
c: [],
add: function(value) {
if(this.c.indexOf(value) === -1 && isNaN(value)) this.c.push(value);
}
};
if(isSymbol(obj)) {
var group = obj.group,
prevgroup = obj.previousGroup;
if(group === EX) variables(obj.power, poly, vars);
if(group === CP || group === CB || prevgroup === CP || prevgroup === CB) {
for(var x in obj.symbols) variables(obj.symbols[x], poly, vars);
}
else if(group === S) {
vars.add(obj.value);
}
else if(group === PL) {
variables(firstObject(obj.symbols), poly, vars);
}
else if(group === EX) {
if(!isNaN(obj.value)) vars.add(obj.value);
variables(obj.power, poly, vars);
}
else if(group === FN && !poly) {
for(var i=0; i<obj.args.length; i++) {
variables(obj.args[i], poly, vars);
}
}
}
return vars.c.sort();
},
/**
* Loops through each item in object and calls function with item as param
* @param {Object|Array} obj
* @param {Function} fn
*/
each = Utils.each = function(obj, fn) {
if(isArray(obj)) {
var l = obj.length;
for(var i=0; i<l; i++) fn.call(obj, i);
}
else {
for(var x in obj) if(obj.hasOwnProperty(x)) fn.call(obj, x);
}
},
/**
* Checks to see if a number is an even number
* @param {Number} num
* @returns {boolean}
*/
even = Utils.even = function(num) {
return num % 2 === 0;
},
/**
* Checks to see if a fraction is divisible by 2
* @param {Number} num
* @returns {boolean}
*/
evenFraction = Utils.evenFraction = function(num) {
return 1/( num % 1) % 2 === 0;
},
/**
* Strips duplicates out of an array
* @param {Array} arr
*/
arrayUnique = Utils.arrayUnique = function(arr) {
var l = arr.length, a = [];
for(var i=0; i<l; i++) {
var item = arr[i];
if(a.indexOf(item) === -1) a.push(item);
}
return a;
},
/**
* Reserves the names in an object so they cannot be used as function names
* @param {Object} obj
*/
reserveNames = Utils.reserveNames = function(obj) {
var add = function(item) {
if(RESERVED.indexOf(item) === -1) RESERVED.push(item);
};
if(typeof obj === 'string') add(obj);
else {
each(obj, function(x) {
add(x);
});
}
},
/**
* Removes an item from either an array or an object. If the object is an array, the index must be
* specified after the array. If it's an object then the key must be specified
* @param {Object|Array} obj
* @param {Integer} indexOrKey
*/
remove = Utils.remove = function( obj, indexOrKey ) {
var result;
if( isArray(obj) ) {
result = obj.splice(indexOrKey, 1)[0];
}
else {
result = obj[indexOrKey];
delete obj[indexOrKey];
}
return result;
},
/**
* Creates a temporary block in which one of the global settings is temporarily modified while
* the function is called. For instance if you want to parse directly to a number rather than have a symbolic
* answer for a period you would set PARSE2NUMBER to true in the block.
* @example block('PARSE2NUMBER', function(){//symbol being parsed to number}, true);
* @param {String} setting - The setting being accessed
* @param {Function} f
* @param {boolean} opt - The value of the setting in the block
* @param {String} obj - The obj of interest. Usually a Symbol but could be any object
*/
block = Utils.block = function(setting, f, opt, obj) {
var current_setting = Settings[setting];
Settings[setting] = opt === undefined ? true : !! opt;
var retval = f.call(obj);
Settings[setting] = current_setting;
return retval;
},
/**
* Converts function arguments to an array. I had hopes for this function :(
* @param {Object} obj - arguments obj
*/
arguments2Array = Utils.arguments2Array = function(obj) {
return [].slice.call(obj);
},
/**
* Using a regex to get between brackets can be a bit tricky. This functions makes it more abstract
* to fetch between brackets within a string from any given index. If the starting index is a bracket
* then it will fail. returns [matched_string, first_bracket_index, end_bracket_index]
* @param {Char} ob - open bracket
* @param {Char} cb - close bracket
* @param {String} str - The string being read
* @param {Integer} start - Where in the string to start
* @returns {Array}
*/
betweenBrackets = function(ob, cb, str, start) {
start = start || 0;
var l = str.length,
open = 0, fb;
for(var i=start; i<l; i++) {
var ch = str.charAt(i); //get the character at this position
if(ch === ob) { //if an open bracket was found
if(fb === undefined) fb = i+1;//mark the first bracket found
open++; //mark a new open bracket
}
if(ch === cb) { //if a close bracket was found
open--; //close a bracket
if(open === 0 && fb !== undefined) {
var nb = i;
return [str.substring(fb, nb), fb, nb];
}
}
}
return [];
},
/**
* A helper function to make substitutions
* @param {Object} subs
*/
format_subs = function(subs) {
for(var x in subs) subs[x] = _.parse(subs[x].toString());
return subs;
},
generatePrimes = Utils.generatePrimes = function(upto) {
//get the last prime in the array
var last_prime = PRIMES[PRIMES.length-1] || 2;
//no need to check if we've already encountered the number. Just check the cache.
for(var i=last_prime; i<upto; i++) {
if(isPrime(i)) PRIMES.push(i);
}
},
//This object holds additional functions for nerdamer. Think of it as an extension of the Math object.
//I really don't like touching objects which aren't mine hence the reason for Math2. The names of the
//functions within are pretty self-explanatory.
Math2 = {
csc: function(x) { return 1/Math.sin(x); },
sec: function(x) { return 1/Math.cos(x); },
cot: function(x) { return 1/Math.tan(x); },
//https://gist.github.com/kcrt/6210661
erf: function(x){
// erf(x) = 2/sqrt(pi) * integrate(from=0, to=x, e^-(t^2) ) dt
// with using Taylor expansion,
// = 2/sqrt(pi) * sigma(n=0 to +inf, ((-1)^n * x^(2n+1))/(n! * (2n+1)))
// calculationg n=0 to 50 bellow (note that inside sigma equals x when n = 0, and 50 may be enough)
var m = 1.00,
s = 1.00,
sum = x * 1.0;
for(var i = 1; i < 50; i++){
m *= i;
s *= -1;
sum += (s * Math.pow(x, 2.0 * i + 1.0)) / (m * (2.0 * i + 1.0));
}
return 2 * sum / Math.sqrt(3.14159265358979);
},
fact: function(x) {
var retval=1;
for (var i = 2; i <= x; i++) retval = retval * i;
return retval;
},
mod: function(x, y) {
return x % y;
},
GCD: function() {
var args = arrayUnique([].slice.call(arguments)
.map(function(x){ return Math.abs(x); })).sort(),
a = Math.abs(args.shift()),
n = args.length;
while(n-- > 0) {
var b = Math.abs(args.shift());
while(true) {
a %= b;
if (a === 0) {
a = b;
break;
}
b %= a;
if (b === 0) break;;
}
}
return a;
},
QGCD: function() {
var args = [].slice.call(arguments);
var a = args[0];
for(var i=1; i<args.length; i++) {
a = args[i].gcd(a);
}
return a;
},
LCM: function(a, b) {
return (a * b) / Math2.GCD(a, b);
},
//pow but with the handling of negative numbers
//http://stackoverflow.com/questions/12810765/calculating-cubic-root-for-negative-number
pow: function(b, e) {
if (b < 0) {
if (Math.abs(e) < 1) {
//nth root of a negative number is imaginary when n is even
if (1 / e % 2 === 0) return NaN;
return -Math.pow(Math.abs(b), e);
}
}
return Math.pow(b, e);
},
//uses trial division to get factors
ifactor: function(n, factors) {
factors = factors || {};
var r = Math.floor(Math.sqrt(n));
var lcprime = PRIMES[PRIMES.length-1];
//a one-time cost... Hopefully ... And don't bother for more than a million
//takes too long
if(r > lcprime && n < 1e6) generatePrimes(r);
var l = PRIMES.length;
for(var i=0; i<l; i++) {
var prime = PRIMES[i];
//trial division
while(n%prime === 0) {
n = n/prime;
factors[prime] = (factors[prime] || 0)+1;
}
}
if(n > 1) factors[n] = 1;
return factors;
}
};
//safeties
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/
Math.sign = Math.sign || function(x) {
x = +x; // convert to a number
if (x === 0 || isNaN(x)) {
return x;
}
return x > 0 ? 1 : -1;
};
Math.cosh = Math.cosh || function(x) {
var y = Math.exp(x);
return (y + 1 / y) / 2;
};
Math.sinh = Math.sinh || function(x) {
var y = Math.exp(x);
return (y - 1 / y) / 2;
};
Math.tanh = Math.tanh || function(x) {
if (x === Infinity) {
return 1;
} else if (x === -Infinity) {
return -1;
} else {
var y = Math.exp(2 * x);
return (y - 1) / (y + 1);
}
};
Math.asinh = Math.asinh || function(x) {
if (x === -Infinity) {
return x;
} else {
return Math.log(x + Math.sqrt(x * x + 1));
}
};
Math.acosh = Math.acosh || function(x) {
return Math.log(x + Math.sqrt(x * x - 1));
};
Math.atanh = Math.atanh || function(x) {
return Math.log((1+x)/(1-x)) / 2;
};
reserveNames(Math2); //reserve the names in Math2
/* GLOBAL FUNCTIONS */
/**
* This method will return a hash or a text representation of a Symbol, Matrix, or Vector.
* If all else fails it *assumes* the object has a toString method and will call that.
*
* @param {Object} obj
* @param {String} option get is as a hash
* @returns {String}
*/
function text(obj, option, useGroup) {
var asHash = option === 'hash',
asDecimal = option === 'decimals',
opt = asHash ? undefined : option;
//if the object is a symbol
if(isSymbol(obj)) {
var multiplier = '',
power = '',
sign = '',
group = obj.group || useGroup,
value = obj.value;
//if the value is to be used as a hash then the power and multiplier need to be suppressed
if(!asHash) {
//use asDecimal to get the object back as a decimal
var om = asDecimal ? obj.multiplier.valueOf() : obj.multiplier.toString();
if(om == '-1') {
sign = '-';
om = '1';
}
//only add the multiplier if it's not 1
if(om != '1') multiplier = om;
//use asDecimal to get the object back as a decimal
var p = obj.power ? (asDecimal ? obj.power.valueOf() : obj.power.toString()) : '';
//only add the multiplier
if(p != '1') {
//is it a symbol
if(isSymbol(p)) {
power = text(p, opt);
}
else {
power = p;
}
}
}
switch(group) {
case N:
multiplier = '';
//if it's numerical then all we need is the multiplier
value = obj.multiplier == '-1' ? '1' : asDecimal ? obj.valueOf() : obj.multiplier.toString();
power = '';
break;
case PL:
value = obj.collectSymbols(text, opt).join('+').replace(/\+\-/g, '-');
break;
case CP:
value = obj.collectSymbols(text, opt).join('+').replace(/\+\-/g, '-');
break;
case CB:
value = obj.collectSymbols(function(symbol){
var g = symbol.group;
//both groups will already be in brackets if their power is greater than 1
//so skip it.
if((g === PL || g === CP) && (symbol.power.equals(1) && symbol.multiplier.equals(1))) {
return inBrackets(text(symbol, opt));
}
return text(symbol, opt);
}).join('*');
break;
case EX:
var pg = obj.previousGroup,
pwg = obj.power.group;
//PL are the exception. It's simpler to just collect and set the value
if(pg === PL) value = obj.collectSymbols(text, opt).join('+').replace('+-', '-');
if(!(pg === N || pg === S || pg === FN) && !asHash) { value = inBrackets(value); }
if((pwg === CP || pwg === CB || pwg === PL || obj.power.multiplier.toString() != '1') && power) {
power = inBrackets(power);
}
break;
}
if(group === FN && asDecimal) {
value = obj.fname+inBrackets(obj.args.map(function(symbol) {
return text(symbol, opt);
}).join(','));
}
//wrap the power since / is less than ^
//TODO: introduce method call isSimple
if(power && !isInt(power) && group !== EX && !asDecimal) { power = inBrackets(power); }
//the following groups are held together by plus or minus. They can be raised to a power or multiplied
//by a multiplier and have to be in brackets to preserve the order of precedence
if(((group === CP || group === PL) && (multiplier && multiplier != '1' || sign === '-'))
|| ((group === CB || group === CP || group === PL) && (power && power != '1'))
|| !asHash && group === P && value == -1
|| obj.fname === PARENTHESIS) {
value = inBrackets(value);
}
var c = sign+multiplier;
if(multiplier && !isInt(multiplier) && !asDecimal) c = inBrackets(c);
if(power < 0) power = inBrackets(power);
if(multiplier) c = c + '*';
if(power) power = '^' + power;
//this needs serious rethinking. Must fix
if(group === EX && value.charAt(0) === '-') value = inBrackets(value);
var cv = c+value;
if(obj.parens) cv = inBrackets(cv);
return cv+power;
}
else if(isVector(obj)) {
var l = obj.elements.length,
c = [];
for(var i=0; i<l; i++) c.push(obj.elements[i].text());
return '['+c.join(',')+']';
}
else {
return obj.toString();
}
}
Utils.text = text;
/* END GLOBAL FUNCTIONS */
/**** CLASSES *****/
/**
* The Collector is used to find unique values within objects
* @param {Function} extra_conditions - A function which performs a check on the values and returns a boolean
* @returns {Collector}
*/
function Collector(extra_conditions) {
this.c = [];
this.add = function(value) {
var condition_true = extra_conditions ? extra_conditions(value) : true;
if(this.c.indexOf(value) === -1 && condition_true) this.c.push(value);
};
}
/**
* Wraps a function name in this object
* @param {String} fn_name
* @returns {Func}
*/
function Func(fn_name) {
this.name = fn_name;
}
/**
* This is what nerdamer returns. It's sort of a wrapper around the symbol class and
* provides the user with some useful functions. If you want to provide the user with extra
* library functions then add them to this class's prototype.
* @param {Symbol} symbol
* @returns {Expression} wraps around the Symbol class
*/
function Expression(symbol) {
this.symbol = symbol;
}
/**
* Returns stored expression at index. For first index use 1 not 0.
* @param {Integer} expression_number
*/
Expression.getExpression = function(expression_number, asType) {
if(expression_number === 'last' || !expression_number) expression_number = EXPRESSIONS.length;
if(expression_number === 'first') expression_number = 1;
var index = expression_number -1,
expression = EXPRESSIONS[index],
retval = expression ? new Expression(expression) : expression;
return retval;
};
Expression.prototype = {
/**
* Returns the text representation of the expression
* @returns {String}
*/
text: function(opt) {
opt = opt || 'decimals';
return text(this.symbol, opt);
},
/**
* Returns the latex representation of the expression
* @returns {String}
*/
latex: function(option) {
return LaTeX.latex(this.symbol, option);
},
valueOf: function() {
return this.symbol.valueOf();
},
/**
* Evaluates the expression and tries to reduce it to a number if possible.
* If an argument is given in the form of %{integer} it will evaluate that expression.
* Other than that it will just use it's own text and reparse
* @returns {Expression}
*/
evaluate: function() {
var first_arg = arguments[0], expression, idx = 1;
if(typeof first_arg === 'string') {
expression = (first_arg.charAt(0) === '%') ? Expression.getExpression(first_arg.substr(1)).text() : first_arg;
}
else if(first_arg instanceof Expression || isSymbol(first_arg)) {
expression = first_arg.text();
}
else {
expression = this.symbol.text(); idx--;
}
var subs = arguments[idx] || {};
//link pi and e
subs.e = _.constants.E;
subs.pi = _.constants.PI;
return new Expression(block('PARSE2NUMBER', function() {
return _.parse(expression, format_subs(subs));
}, true));
},
/**
* Converts a symbol to a JS function. Pass in an array of variables to use that order instead of
* the default alphabetical order
* @param {Array}
*/
buildFunction: function(vars) {
return build(this.symbol, vars);
},
/**
* Checks to see if the expression is just a plain old number
* @returns {boolean}
*/
isNumber: function() {
return isNumericSymbol(this.symbol);
},
/**
* Checks to see if the expression is infinity
* @returns {boolean}
*/
isInfinity: function() {
return Math.abs(this.symbol.multiplier) === Infinity;
},
/**
* Returns all the variables in the expression
* @returns {Array}
*/
variables: function() {
return variables(this.symbol);
},
toString: function() {
if(isArray(this.symbol)) return '['+this.symbol.toString()+']'
return this.symbol.toString();
},
toDecimal: function() {
return this.symbol.toDecimal();
},
isFraction: function() {
return isFraction(this.symbol);
},
isPolynomial: function() {
return this.symbol.isPoly();
}
};
//Aliases
Expression.prototype.toTeX = Expression.prototype.latex;
function Frac(n) {
if(n instanceof Frac) return n;
if(n === undefined) return this;
if(isInt(n)) {
this.num = bigInt(n);
this.den = bigInt(1);
}
else {
var frac = Fraction.convert(n);
this.num = new bigInt(frac[0]);
this.den = new bigInt(frac[1]);
}
}
Frac.isFrac = function(o) {
return (o instanceof Frac);
};
Frac.quick = function(n, d) {
var frac = new Frac();
frac.num = new bigInt(n);
frac.den = new bigInt(d);
return frac;
};
Frac.prototype = {