-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
108 lines (89 loc) · 2.7 KB
/
index.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
/**
* USD
*/
if ( typeof module === "object" && module && typeof module.exports === "object" ){
var isNode = true, define = function (factory) {
module.exports = factory(require, exports, module);
};
}
define( function( require, exports, module ){
module.exports = require('stampit')()
.state({
_pennies: 0
})
.enclose( function(){
if ( typeof this.pennies === 'number' ){
throw new Error('Do not create with `pennies` set');
}
})
.methods({
pennies: function( val ){
if ( !val ) return this.toPennies();
this._pennies = val;
return this;
}
, dollars: function( val ){
if ( !val && val != 0 ) return this.toDollars();
val = Math.round( parseFloat( val ) * 100 );
if ( isNaN( val ) ){
throw new Error('Invalid dollars value');
}
return this.pennies( val );
}
, toDollarsNoCents: function(){
// parse as float incase of partial cents
var pennies = parseFloat( this._pennies );
if ( isNaN( pennies ) ){
return '0';
}
return +module.exports
.round10( pennies / 100, -2 )
.toFixed(2)
.split('.')[0];
}
, toDollars: function(){
// parse as float incase of partial cents
var pennies = parseFloat( this._pennies );
if ( isNaN( pennies ) ){
return '0';
}
return module.exports.round10( pennies / 100, -2 ).toFixed(2);
}
, toPennies: function(){
return this._pennies;
}
, valueOf: function(){
return this.toPennies();
}
});
/**
* Decimal adjustment of a number.
*
* @param {String} type The type of adjustment.
* @param {Number} value The number.
* @param {Integer} exp The exponent (the 10 logarithm of the adjustment base).
* @returns {Number} The adjusted value.
*/
module.exports.decimalAdjust = function(type, value, exp) {
// If the exp is undefined or zero...
if (typeof exp === 'undefined' || +exp === 0) {
return Math[type](value);
}
value = +value;
exp = +exp;
// If the value is not a number or the exp is not an integer...
if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
return NaN;
}
// Shift
value = value.toString().split('e');
value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
// Shift back
value = value.toString().split('e');
return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
};
module.exports.round10 = function(value, exp) {
return module.exports.decimalAdjust('round', value, exp);
};
return module.exports;
});