Easy to understand JavaScript solution
\nvar countOfAtoms = function(formula) {\n    let stack = [];\n    let cur = {};\n    let i = 0;\n    while (i < formula.length) {\n        if (formula[i] === \
```\nvar countOfAtoms = function(formula) {\n    let stack = [];\n    let cur = {};\n    let i = 0;\n    while (i < formula.length) {\n        if (formula[i] === \'(\') {\n            stack.push(cur);\n            cur = {};\n            i++;\n        } else if (formula[i] === \')\') {\n            const [mult, newI] = readNextDigit(++i);\n            i = newI;\n            Object.keys(cur).forEach(key => cur[key] *= mult);\n            const last = stack[stack.length - 1];\n            // merge\n            Object.keys(last).forEach(key => last[key] = last[key] + (cur[key] ?? 0));\n            Object.keys(cur).forEach(key => {\n               if (last[key] === undefined) {\n                   last[key] = cur[key];\n               } \n            });\n            cur = stack.pop();\n        } else {\n            const [ele, newI] = readNextElement(i);\n            i = newI;\n            const [c, nI] = readNextDigit(i);\n            i = nI;\n            cur[ele] = (cur[ele] ?? 0) + c;\n        }\n    }\n    \n    return Object.entries(cur).sort((a,b) => a[0].localeCompare(b[0])).reduce((r, [key, val]) => r += `${key}${val === 1 ? \'\' : val}`, "");\n    \n    \n    function readNextElement(i) {\n        if (!formula[i].match(/[A-Z]/)) return null;\n        let res = formula[i++];\n        while (formula[i]?.match(/[a-z]/)) {\n            res += formula[i++];\n        }\n        \n        return [res, i];\n    }\n    \n    function readNextDigit(i) {\n        if (!formula[i]?.match(/[0-9]/)) return [1, i];\n        let res = 0;\n        while (formula[i]?.match(/[0-9]/)) {\n            res = res * 10 + +formula[i++];\n        }\n        \n        return [res, i];\n    }\n};\n```
['JavaScript']