-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbignumber-notation.js
More file actions
178 lines (160 loc) · 4.43 KB
/
bignumber-notation.js
File metadata and controls
178 lines (160 loc) · 4.43 KB
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
import BigNumber from 'bignumber.js'
/**
* Zips two arrays together into pairs
* @param {Array} a - First array
* @param {Array} b - Second array
* @returns {Array} Array of pairs
*/
const zip = (a, b) => {
const length = Math.min(a.length, b.length)
const result = []
for (let i = 0; i < length; i++) {
result.push([a[i], b[i]])
}
return result
}
/**
* Returns the last element of an array
* @param {Array} arr - Input array
* @returns {*} Last element, or empty array if input is empty
*/
const last = (arr) => (arr.length > 0 ? arr[arr.length - 1] : [])
/**
* Replaces all occurrences of keys in map with their values
* @param {Object} map - Key-value pairs for replacement
* @param {string} input - Input string
* @returns {string} String with replacements applied
*/
const replace = (map, input) =>
Object.entries(map).reduce(
(acc, [key, val]) =>
acc.replace(
new RegExp(key.replace(/([.*+?^=!:${}()|[\]/\\])/g, '\\$1'), 'g'),
val,
),
input,
)
/**
* Finds matching bracket pairs in a token array
* @param {string} tagA - Opening bracket
* @param {string} tagB - Closing bracket
* @param {Array} arr - Token array
* @returns {Array} Array of [openIndex, closeIndex] pairs
*/
function getMatchingTags(tagA, tagB, arr) {
if (arr.indexOf(tagA) === -1) {
return []
}
const stack = []
const result = []
for (let i = 0; i < arr.length; i++) {
if (arr[i] === tagA) {
stack.push(i)
} else if (arr[i] === tagB) {
if (stack.length > 0) {
const openIndex = stack.pop()
result.push([openIndex, i])
}
}
}
return result
}
/**
* Operator mapping to BigNumber methods
*/
const operators = {
'+': 'plus',
'-': 'minus',
'*': 'times',
'/': 'div',
}
/**
* Operators in order of precedence (highest first)
*/
const orderedOperators = ['*', '/', '-', '+']
/**
* Operators and brackets with surrounding spaces for tokenization
*/
const operatorsWithSpaces = [...orderedOperators, '(', ')'].reduce((acc, o) => {
acc[o] = ` ${o} `
return acc
}, {})
/**
* Parses template strings and values into tokens
* @param {TemplateStringsArray} strings - Template strings
* @param {Array} values - Interpolated values
* @returns {Array} Array of tokens
*/
function parse(strings, values) {
const zipped = zip([...strings], values)
const merged =
strings.length > values.length
? [...zipped, [last([...strings]), '']]
: zipped
const split = merged.map((pair) => [
replace(operatorsWithSpaces, pair[0])
.replace(/e \+ /g, 'e+')
.replace(/e - /g, 'e-')
.split(' '),
pair[1],
])
return split.flat(2).filter((e) => e !== '')
}
/**
* Recursively calculates the result from a token array
* @param {Array} arr - Token array
* @returns {BigNumber} Calculated result
*/
function calculate(arr) {
if (arr.length === 1) {
return arr[0] instanceof BigNumber ? arr[0] : new BigNumber(arr[0])
}
const [bracketOpenIndex, bracketCloseIndex] = last(
getMatchingTags('(', ')', arr),
)
if (bracketCloseIndex !== undefined) {
const beginning = arr.slice(0, bracketOpenIndex)
const mid = arr.slice(bracketOpenIndex + 1, bracketCloseIndex)
const end = arr.slice(bracketCloseIndex + 1)
return calculate([...beginning, calculate(mid), ...end])
}
return orderedOperators.reduce((result, operatorSymbol) => {
const index = arr.indexOf(operatorSymbol)
if (result instanceof BigNumber || index === -1) {
return result
}
const a = new BigNumber(arr[index - 1])
const o = operators[operatorSymbol]
const b = new BigNumber(arr[index + 1])
const beginning = arr.slice(0, index - 1)
const calculated = a[o](b)
const end = arr.slice(index + 2)
return calculate([...beginning, calculated, ...end])
}, {})
}
/**
* Tagged template literal function for BigNumber arithmetic
*
* @example
* // Basic arithmetic
* n`1 + 2 * 3` // BigNumber(7)
*
* @example
* // With variables
* const x = 100
* n`${x} * 2 + 50` // BigNumber(250)
*
* @example
* // Chain BigNumber methods
* n`1.5 * 2 + 9`.dividedBy(4).integerValue() // BigNumber(3)
*
* @param {TemplateStringsArray} strings - Template strings
* @param {...*} values - Interpolated values
* @returns {BigNumber} Result of the arithmetic expression
*/
function n(strings, ...values) {
const parsed = parse(strings, values)
return calculate(parsed)
}
export default n
export { n, getMatchingTags, parse, calculate }