You are given an array of desired filenames in the order of their creation. Since two files cannot have equal names, the one which comes later will have an addition to its name in a form of (k), where k is the smallest positive integer such that the obtained name is not used yet.
Return an array of names that will be given to the files.
Example
For names = ["doc", "doc", "image", "doc(1)", "doc"], the output should be fileNaming(names) = ["doc", "doc(1)", "image", "doc(1)(1)", "doc(2)"].
One person posted this solution:
const fileNaming = names => {
const used = {};
return names.map(name => {
let newName = name;
while (used[newName]) {
newName = `${name}(${used[name]++})`;
}
used[newName] = 1;
return newName;
});
};
I'm having a hard time understanding the while block's condition.
used is an empty object.
newName is a new variable that is equal to the current item in the names array.
How does used[newName] resolve to a number? used is never set to anything other then an empty object.
This is the console output for console.log(used[newName])
Using this input:
["dd",
"dd(1)",
"dd(2)",
"dd",
"dd(1)",
"dd(1)(2)",
"dd(1)(1)",
"dd",
"dd(1)"]

One person posted this solutionis alarming. Did you come up with your own solution yet?console.log()also the values fornameandnewName. I have a feeling that you might understand the loop after seeing what's there.used is never set to anything other then an empty object.. But in the sample code, there's this line:used[newName] = 1;. It contradicts your statement. ;-) Perhaps that's the key for you to understand the loop?