I went with RegExp solution. I created a regexp for all the reactions and delete everyting, then iterate until no more matches
constpolymer=readFileSync('./data',{encoding:'utf8'}).trim()// A-ZconstupperLetters=[...Array(26)].map((_,i)=>String.fromCharCode(65+i))// A RegExp of the form Aa|...|Zz|aA|...|zZconstregexp=newRegExp(upperLetters.map(upper=>`${upper}${upper.toLocaleLowerCase()}`).concat(upperLetters.map(upper=>`${upper.toLocaleLowerCase()}${upper}`)).join("|"),"g")// while there is a match for the regexp replace all and retry. returns the legnthconstreactToPolymer=polymerToReact=>{while(regexp.test(polymerToReact)){polymerToReact=polymerToReact.replace(regexp,"")}returnpolymerToReact.length}console.log(reactToPolymer(polymer))
I went with RegExp solution. I created a regexp for all the reactions and delete everyting, then iterate until no more matches
Time: 0.265s
For part b y reuse all the code but add this
Time: 3.693s
I find the part b is a little slow using this approach