input: ["doc", "doc", "image", "doc(1)", "doc"]
output: ["doc", "doc(1)", "image", "doc(1)(1)", "doc(2)"]
The issue:
{used[name] }
this part of the code is tricking me.
I don't understand line and how I'm not assigning 1 to the first thing
the code is working the way it should from trial and error; but I'm having a hard to wrapping my brain around this loop.
my understanding:
we loop through the names, then each name that starts with docs; we assign newName to doc1
What I tried:
used[newName] = 6;
results: [doc, doc(6), image, doc(1), doc(7)]
this ended up confusing me more. it's late and I might just need some sleep.
const solution = names => {
const used = {};
return names.map(name => {
let newName = name;
while (used[newName]) {
newName = `${name}(${used[name] })`;
}
used[newName] = 1;
return newName;
});
};
CodePudding user response:
The first time a name is encountered used[newName]
is undefined
, so the while
loop doesn't even start, and newName
is returned. In the next time it's encountered, you already have user[newName]=1
, so (1)
is appended to the name, and so on.