Learning Javascript — File Naming
Jul 30, 2017 · 2 min read
This was challenge 57: File Naming. Close to the end of the intro section!
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 befileNaming(names) = ["doc", "doc(1)", "image", "doc(1)(1)", "doc(2)"].
Here is my solution:
function fileNaming(names) {
function getFileName(fileName, j) {
var slicedNames = names.slice(0, j);
console.log('Checking for Conflicts with the following filenames: ', slicedNames);
var k = 1;
while (slicedNames.includes(filename + '(' + k + ')')) {
console.log('Conflict: ', filename + '(' + k + ')');
k++;
}
console.log('Using: ', filename + '(' + k + ')');
return filename + '(' + k + ')';
}
for (var i = 0; i < names.length; i++) {
var filename = names[i];
console.log('\n');
console.log('Checking Filename: ', filename);
for (var j = i + 1; j < names.length; j++) {
if (names[j] === filename) {
console.log('Found Match! Index: ', j);
names[j] = getFileName(filename, j);
console.log('New Filenames: ', names);
}
}
}
console.log('\n');
console.log('Final Filenames: ', names);
return names;
}Example Output:
Input:
Input:names: ["doc",
"doc",
"image",
"doc(1)",
"doc"]Output:["doc",
"doc(1)",
"image",
"doc(1)(1)",
"doc(2)"]Console Output:Checking Filename: doc
Found Match! Index: 1
Checking for Conflicts with the following filenames: [ 'doc' ]
Using: doc(1)
New Filenames: [ 'doc', 'doc(1)', 'image', 'doc(1)', 'doc' ]
Found Match! Index: 4
Checking for Conflicts with the following filenames: [ 'doc', 'doc(1)', 'image', 'doc(1)' ]
Conflict: doc(1)
Using: doc(2)
New Filenames: [ 'doc', 'doc(1)', 'image', 'doc(1)', 'doc(2)' ]
Checking Filename: doc(1)
Found Match! Index: 3
Checking for Conflicts with the following filenames: [ 'doc', 'doc(1)', 'image' ]
Using: doc(1)(1)
New Filenames: [ 'doc', 'doc(1)', 'image', 'doc(1)(1)', 'doc(2)' ]
Checking Filename: image
Checking Filename: doc(1)(1)
Checking Filename: doc(2)
Final Filenames: [ 'doc', 'doc(1)', 'image', 'doc(1)(1)', 'doc(2)' ]