me
const spellProcessor = (spellsArr) => spellsArr.reduce( (acc,el) => { let spellBase = [] el.split("").forEach(elm => spellBase.slice(-1) != elm ? spellBase.push(elm): 0) spellBase = spellBase.join("") let sameSpell = acc.find(el2 => el2.base == spellBase) ?? {} JSON.stringify(sameSpell) === "{}" ? acc.push(sameSpell) : 0 sameSpell.base = spellBase sameSpell.power = (sameSpell.power ?? 0) + el.length sameSpell.count = (sameSpell.count ?? 0) + 1 return acc }, [] ) const unProcessedSpells = [ "fiiire", "fire", "fiiree", "water", "waater", "earth", "air", "aiir" ] spellResultCheck = [ { base: "fire", power: 15, count: 3 }, { base: "water", power: 11, count: 2 }, { base: "air", power: 7, count: 2 }, { base: "earth", power: 5, count: 1 } ] const result = spellProcessor(unProcessedSpells) console.log(result)
vs
gpt
const spellProcessor = (spellsArr) =>
spellsArr.reduce((acc, spell) => {
// 1. Normalize: collapse consecutive duplicates
let base = "";
for (const ch of spell) {
if (base.at(-1) !== ch) {
base += ch;
}
}
// 2. Look up existing spell
let entry = acc.find(e => e.base === base);
// 3. Create if missing
if (!entry) {
entry = { base, power: 0, count: 0 };
acc.push(entry);
}
// 4. Update existing entry
entry.power += spell.length;
entry.count += 1;
return acc;
}, []);