Skip to content

Instantly share code, notes, and snippets.

@exbotanical
Created July 2, 2021 23:00
Show Gist options
  • Save exbotanical/b056e042ee3b190931781072378949f9 to your computer and use it in GitHub Desktop.
Save exbotanical/b056e042ee3b190931781072378949f9 to your computer and use it in GitHub Desktop.
An implementation of the Windows 10 "duplicate filename" algorithm
// the following is an exact implementation of the algorithm Windows 10 uses when
// duplicating filenames
// dummy data
const allFiles = [
'test',
'test - Copy (2)',
'test - Copy',
'name',
'othername'
];
// our test case
let filename = 'test';
// does the name end with '- Copy (n)'?
const isNthCopy = name => /- Copy \([\d]+\)$/.test(name);
// does the name end with '- Copy'?
const isSecondCopy = name => /- Copy$/.test(name);
// the Windows 'duplicate file' naming algorithm
// we append '- Copy' to the name of the file we are copying
// but if this new name would be a duplicate of yet another file's name, we add a (2)
// if (2) is similarly taken, we increment until we get the nest lowest number that does not result in a duplicate
// this is all contingent on the name of the file we are duplicating: copying 'a - Copy (2)' would result in 'a - Copy (2) - Copy'
// incrementer - we always start at 1 and use prefix notation (so 1 is never used)
let i = 1;
// was the file using a duplicate name before we started iterating?
const isOriginalCopy = isSecondCopy(filename) || isNthCopy(filename);
do {
// if this is true, `isSecondCopy` only became true after an iteration
if (isSecondCopy(filename) && !isOriginalCopy) {
filename = filename += ' (2)';
// likewise, `isNthCopy` only became true after iterating
} else if (isNthCopy(filename) && !isOriginalCopy) {
// increment the numeric suffix
filename = filename.substring(0, filename.length - 2) + ++i + ')';
} else {
filename += ' - Copy';
}
var duplicateExtant = allFiles.find(f => f === filename);
} while (duplicateExtant);
console.log(filename); // test - Copy (3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment