forked from evrimagaci/periodum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.js
61 lines (57 loc) · 1.35 KB
/
test.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
const formula = 'C2H5OH'
const availableElements = []
const elements = [
{
symbol: 'C',
count: 2,
},
{
symbol: 'H',
count: 1,
},
]
const finalized = []
let symbol = ''
let count = ''
let flagElement = false
const chars = formula.split('')
chars.forEach((char, index) => {
if (!flagElement && isNaN(char * 1) && char === char.toUpperCase()) {
symbol += char
flagElement = true
} else if (isNaN(char * 1) && char === char.toLowerCase()) {
symbol += char
} else if (!isNaN(char * 1)) {
count += char
} else {
availableElements.push({
symbol,
count: count === '' ? 1 : Number(count),
})
symbol = char
count = ''
}
pushAvailableElement(index)
})
let foundIndex = null
const lastElement = elements[elements.length - 1]
availableElements.forEach((availableElement, index) => {
if (foundIndex !== null && lastElement.symbol === availableElement.symbol) {
if (lastElement.count < availableElement.count) {
finalized.push(availableElement.symbol)
}
foundIndex = index
} else if (index > foundIndex) {
finalized.push(availableElement.symbol)
}
})
function pushAvailableElement(index) {
if (chars.length - 1 === index) {
availableElements.push({
symbol,
count: count === '' ? 1 : Number(count),
})
}
}
console.log(availableElements)
console.log(finalized)