-
Notifications
You must be signed in to change notification settings - Fork 2
/
lodash-arithmetic.js
74 lines (65 loc) · 1.64 KB
/
lodash-arithmetic.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
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['lodash'], factory);
}
else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require('lodash').runInContext());
}
else {
// Browser globals (root is window)
root._.mixin(factory(root._));
}
}(this, function (_, undefined) {
'use strict';
function add(a, b) {
var fa = getFactor(a);
var fb = getFactor(b);
var ia = toInt(a);
var ib = toInt(b);
return (ia * fb + ib * fa) / (fa * fb);
}
function subtract(a, b) {
var fa = getFactor(a);
var fb = getFactor(b);
var ia = toInt(a);
var ib = toInt(b);
return (ia * fb - ib * fa) / (fa * fb);
}
function multiply(a, b) {
var fa = getFactor(a);
var fb = getFactor(b);
var ia = toInt(a);
var ib = toInt(b);
return (ia * ib) / (fa * fb);
}
function divide(a, b) {
var fa = getFactor(a);
var fb = getFactor(b);
var ia = toInt(a);
var ib = toInt(b);
return (ia * fb) / (ib * fa);
}
// Return the number needed to convert a floating number to an integer
function getFactor(str) {
try {
return Math.pow(10, /[.](\d*)/.exec(String(str))[1].length)
} catch (e) {
return 1;
}
}
function toInt(str) {
return Number(String(str).replace('.', ''));
}
var mixins = {
add: add,
subtract: subtract,
divide: divide,
multiply: multiply
};
_.mixin(mixins);
return mixins;
}));