-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathindex.js
52 lines (43 loc) · 1.45 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
'use strict';
const mongoose = require('mongoose');
const util = require('util');
module.exports.loadType = function (mongoose) {
mongoose.Types.Currency = mongoose.SchemaTypes.Currency = Currency;
return Currency;
};
function Currency(path, options) {
mongoose.SchemaTypes.Number.call(this, path, options);
}
/*!
* inherits
*/
util.inherits(Currency, mongoose.SchemaTypes.Number);
Currency.prototype.cast = function (val) {
if (isType('String', val)) {
let currencyAsString = val.toString();
const findDigitsAndDotRegex = /\d*\.\d{1,2}/;
const findCommasAndLettersRegex = /\,+|[a-zA-Z]+/g;
const findNegativeRegex = /^-/;
let currency;
currencyAsString = currencyAsString.replace(findCommasAndLettersRegex, "");
currency = findDigitsAndDotRegex.exec(currencyAsString + ".0")[0]; // Adds .0 so it works with whole numbers
if (findNegativeRegex.test(currencyAsString)) {
return (currency * -100).toFixed(0) * 1;
} else {
return (currency * 100).toFixed(0) * 1;
}
} else if (isType('Number', val)) {
return val.toFixed(0) * 1;
} else {
return new Error('Should pass in a number or string');
}
};
/**
* isType(type, obj)
* Supported types: 'Function', 'String', 'Number', 'Date', 'RegExp',
* 'Arguments'
* source: https://github.com/jashkenas/underscore/blob/1.5.2/underscore.js#L996
*/
function isType(type, obj) {
return Object.prototype.toString.call(obj) == '[object ' + type + ']';
}