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)"]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…