/
cash.umd.js
348 lines (292 loc) · 10.9 KB
/
cash.umd.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
/* cash.js
* Transaction safe currency object for JavaScript.
* (c) 2012 David (daXXog) Volm ><> + + + <><
* Released under Apache License, Version 2.0:
* http://www.apache.org/licenses/LICENSE-2.0.html
*/
//
/* UMD LOADER: https://github.com/umdjs/umd/blob/master/returnExports.js */
(function (root, factory) {
if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like enviroments that support module.exports,
// like Node.
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(factory);
} else {
// Browser globals (root is window)
root.returnExports = factory();
}
}(this, function() {
//
//
var Cash = {};
Cash = function(mixed, cents) { //Cash constructor
switch(typeof mixed) {
case 'undefined':
return new Cash(0, 0);
case 'object':
if(mixed instanceof Array) { //array containing arguments
cents = mixed[1]; //parse
mixed = mixed[0]; //^
return new Cash(mixed, cents); //^
} else { //object with\without functions
this.dec = mixed.dec;
this.a = mixed.a;
this.b = mixed.b;
}
break;
case 'string': //a string of JSON
mixed = JSON.parse(mixed); //parse
return new Cash(mixed); //^
case 'number': //one number argument
if(typeof cents != 'number') {
return new Cash(mixed, 0);
} else { //two number arguments
this.dec = cents.toString().strip(['-', '.']).length; //length of cents
this.a = mixed;
this.b = cents;
}
break;
}
};
Cash._strproto = function ___(cp) { //save String.prototype
var _to = {}; //create a temp object to hold the functions
for(var val in cp) {
_to[val] = cp[val]; //grab functions from String.prototype
}
return _to;
}(String.prototype);
Cash.prototype.toObject = function() { //turn this Cash object into a regular object
return {
"a": this.a,
"b": this.b,
"dec": this.dec
};
};
/**
* ReplaceAll by Fagner Brack (MIT Licensed)
* Replaces all occurrences of a substring in a string
*/
String.prototype.replaceAll = function(token, newToken, ignoreCase) {
var str, i = -1,
_token;
if ((str = this.toString()) && typeof token === "string") {
_token = ignoreCase === true ? token.toLowerCase() : undefined;
while ((i = (
_token !== undefined ? str.toLowerCase().indexOf(
_token,
i >= 0 ? i + newToken.length : 0) : str.indexOf(
token,
i >= 0 ? i + newToken.length : 0))) !== -1) {
str = str.substring(0, i).concat(newToken).concat(str.substring(i + token.length));
}
}
return str;
};
String.prototype.strip = function(a) { //strip an array of strings from a string
var _new = this; //clone me
a.forEach(function(v, i, a) { //loop through array
_new = _new.replaceAll(v, ''); //replace all values with blank strings
});
return _new; //return the new string
};
String.prototype.repeat = function(x) { //like "ruby" * 2 - "javascript".repeat(2)
var _new = '';
for(var i=0; i<x; i++) {
_new += this;
}
return _new;
};
Cash.isNUM = function(n) {
return !isNaN(parseFloat(n)) && isFinite(n); //passes 34 unit tests: http://dl.getdropbox.com/u/35146/js/tests/isNumber.html
};
Cash._parse = function(val) { //pre-parser for strings/numbers
var str = val.toString(); //convert whatever value to a string
var _parse = str.replaceAll('$', '').replaceAll(',', '').replaceAll('c', ''); //remove dollar signs, commas, and c's
return _parse;
};
Cash._parseMode = {
strict: false
};
Cash.parseMode = function(mode) {
if(typeof mode == 'undefined') {
return Cash._parseMode;
} else {
Cash._parseMode = mode;
}
};
Cash.parsable = function(val) { //can we even parse this value?
var _p = Cash._parse(val);
var _q = _p.split(".");
if((typeof _q[1] != 'undefined') && (Cash.parseMode().strict === true)) {
return Cash.isNUM(_p) && (_q[1].length <= Cash.automin()); //check if the output of _parse is a valid number and check if it is the correct number of decimals
} else {
return Cash.isNUM(_p); //check if the output of _parse is a valid number
}
};
Cash.parseToJSON = function(val) {
if(Cash.parsable(val)) {
var _p = Cash._parse(val.toString()).split("."); //parse: string -> better string -> array
var _n = Cash.isNUM(parseInt(_p[1], 10)); //if _p[1] is a number
var _q = ('[' + (parseInt(_p[0], 10).toString() + ',' + //parse: array -> valid JSON
(_n ?
parseInt(_p[1], 10)
: 0 //B=0 if _p[1]==NaN
).toString()) + ']').replace('.', ',').replace('NaN', '0');
return {
json: _q,
dec: _n ? (_p[1].length) : 1
};
} else {
return -1; //parse error, just return -1
}
};
Cash.parse = function(val) { //parse some cash from a string like "$2.50" or "25c" or "1,200" or "$1,000,000"
if(Cash.parsable(val)) {
var _o = Cash.parseToJSON(val);
return new Cash(_o.json).d(_o.dec).ms(); //make cash object from JSON
} else {
return -1; //parse error, just return -1
}
};
Cash.killme = function(cb) { //self destruct (useful for returning String.prototype back to normal)
var val;
for(val in String.prototype) { //delete all functions in String.prototype
delete String.prototype[val];
}
for(val in Cash._strproto) { //restore String.prototype to it's original state
String.prototype[val] = Cash._strproto[val];
}
setTimeout(function() {
Cash = undefined; //kill Cash
setTimeout(cb, 1); //call the callback
}, 250); //in the future
};
Cash.validate = function(cash) { //if cash.dec,a,b are all a numbers..
return typeof cash.dec == 'number' && typeof cash.a == 'number' && typeof cash.b == 'number';
};
Cash._ = function(mixed, cents) { //argument parser
if(Cash.validate(mixed) === true) { //check if the object is valid
return mixed;
} else {
return new Cash(mixed, cents); //make a new one!
}
};
Cash.prototype.validate = function() { //prototype version of Cash.validate
return Cash.validate(this);
};
Cash.prototype.toNumber = function() { //convert Cash object to a number
var _b = Math.abs(this.b).toString().strip(['-', '.']); //strip down b
if(_b.length == this.dec) { //if the decimal place is what it is supposed to be
_b = '' + _b; //convert to a string
} else { //it's (probably) less than what it is supposed to be
_b = '0'.repeat(this.dec - _b.length) + _b; //append zeros
}
return (new Number(this.a.toString() + '.' + _b)).valueOf(); //parse the string
};
Cash.prototype.clone = function() { //clone this
return new Cash(this);
};
Cash.prototype.d = function(val) { //change the decimal place
var _new = this.clone(); //clone this
_new.dec = val; //change the decimal place
return _new; //return the clone
};
Cash.prototype.BIG_NUMBER = 1000000;
Cash.prototype.add = function(mixed, cents) { //addition
var _new = new Cash(), //create a new Cash object
cash = Cash._(mixed, cents).ms(), //parse the arguments
n = { //numbers
t: this.toNumber(),
c: cash.toNumber()
};
/* OLD ALGOrithm
_new.dec = Math.max(this.ms().dec, cash.dec); //set the new decimal place to the greatest decimal place
var d = Math.pow(10, _new.dec); //get the max value + 1 of the B number
var p = (this.ms().b + cash.b); //add the B numbers and store as temp P
_new.a = this.a + cash.a + Math.floor(p / d); //new A number = SUM(all A numbers) + floor(P / D)
_new.b = p % d; //new B number = P mod D
*/
//fake addition with FLOATing points
var j = Cash.prototype.BIG_NUMBER,
x = Math.floor(n.t * j),
y = Math.floor(n.c * j),
z = (Math.floor(x + y) / j) * -1;
_new = Cash.parse(z.toString()).invert();
return _new.ms(); //return the new Cash object
};
Cash.prototype.invert = function() {
return new Cash(this.a * (-1), this.b * (-1)); //invert the cash object
};
Cash.prototype.sub = function(mixed, cents) { //subtraction
var _new = new Cash(), //create a new Cash object
_flo = _new, //dupe it
cash = Cash._(mixed, cents).ms(), //parse the arguments
uf = this.dec !== cash.dec; //using flo?
var n = {
t: this.toNumber(),
c: cash.toNumber()
};
if(!uf) {
//ALGOrithm based subtraction
_new.dec = this.ms().dec; //set the new decimal place to the greatest decimal place
var d = Math.pow(10, _new.dec), //get the max value + 1 of the B number
p = (cash.b - this.ms().b) * (-1), //SUB(B values) * (-1)
q = (p < 0), //if P is negative
r = Math.abs(p), //ABS(P)
s = q ? -1 : 0, //negative carry
t = q ? (d - r) : r, //if used carry do D - R and store as T else copy R to T
u = cash.a * (-1), //A inverted
v = this.a + s + u; //SUM(A, S, U)
_new.a = v;
_new.b = t;
} else {
//fake subtraction with FLOATing points
var j = Cash.prototype.BIG_NUMBER,
x = Math.floor(n.t * j),
y = Math.floor(n.c * j),
z = (Math.floor(x - y) / j) * -1;
_flo = Cash.parse(z.toString()).invert();
}
if(uf) {
return _flo.ms();
} else {
return _new.ms();
}
};
Cash.prototype.min = function(dec) {
if(typeof dec == 'undefined') {
return Cash.parse(this.toNumber()); //use the least possible amount of decimal points
} else {
if(this.dec==dec) {
return this; //=, return current state
} else if(this.dec<dec) {
return this; //<, return current state
} else if(this.dec>dec) {
return new Cash(Cash.parseToJSON(this.toNumber().toFixed(dec)).json); //return a new Cash object limited to dec
}
}
};
Cash._automin = false;
Cash.automin = function(dec) { //use min decimal places before all operations on everything. dec=false to disable
if(typeof dec == 'undefined') {
return Cash._automin;
} else {
this._automin = dec;
}
};
Cash.prototype.ms = function() { //function to get Cash object clone with a safe decimal place
if(Cash.automin() !== false) { //if we want to use automin
return this.min(Cash._automin);
} else {
return this.clone(); //just return a clone of this
}
};
// (end of file)
//
return Cash;
}));
//