Given an array of desired file names in the order of their creation, where two files cannot have the same name. If a file has a duplicate name, it will be appended with (k), where k is the smallest positive integer that creates a unique name.
Output an array of names for the files.
Example:
For names = ["doc", "doc", "image", "doc(1)", "doc"], the result should be fileNaming(names) = ["doc", "doc(1)", "image", "doc(1)(1)", "doc(2)"].
A solution provided by a user:
const fileNaming = names => {
const used = {};
return names.map(name => {
let newName = name;
while (used[newName]) {
newName = `${name}(${used[name]++})`;
}
used[newName] = 1;
return newName;
});
};
There seems to be confusion regarding the condition in the while
block.
The used
object is initially empty.
The variable newName
is set to the current item in the array.
How does used[newName]
return a number if used
is always an empty object?
Here is the console output for console.log(used[newName])
:
https://i.sstatic.net/nCvwm.png
Using this input:
["dd", "dd(1)", "dd(2)", "dd", "dd(1)", "dd(1)(2)", "dd(1)(1)", "dd", "dd(1)"]