JSFiddle - React, Tailwind, and code Playground
by Pritesh Patel
HTML
<div id="result">
</div>
JavaScript
const filesToCopy = [
'hello', // = hello copy
'hello copy', // = hello copy 1
'world', // = world copy 1
'test',
"hello copy 1"// = test
];
const existingFiles = [
'hello',
'world',
'world copy'
];
// const generateCopyNames = (existingFiles, filesToCopy) => {
// const used = new Set(existingFiles);
// const result = [];
// const isNumeric = (value) => {
// if (value.length === 0) return false;
// for (const char of value) {
// if (char < '0' || char > '9') {
// return false;
// }
// }
// return true;
// };
// const getCopyBase = (fileName) => {
// const parts = fileName.split(' ');
// if (parts.length >= 2 && parts[parts.length - 1] === 'copy') {
// return fileName;
// }
// if (
// parts.length >= 3 &&
// isNumeric(parts[parts.length - 1]) &&
// parts[parts.length - 2] === 'copy'
// ) {
// return parts.slice(0, -1).join(' ');
// }
// return `${fileName} copy`;
// };
// for (const file of filesToCopy) {
// if (!used.has(file)) {
// used.add(file);
// result.push(file);
// continue;
// }
// const copyBase = getCopyBase(file);
// let candidate = copyBase;
// let count = 1;
// while (used.has(candidate)) {
// candidate = `${copyBase} ${count}`;
// count++;
// }
// used.add(candidate);
// result.push(candidate);
// }
// return result;
// };
const generateCopyNames = (existingFiles, filesToCopy) => {
const used = new Set(existingFiles);
const result = [];
for (const file of filesToCopy) {
// If file does not exist, use it directly
if (!used.has(file)) {
used.add(file);
result.push(file);
continue;
}
// Otherwise generate copy names
let count = 0;
let candidate = `${file} copy`;
while (used.has(candidate)) {
...