JSFiddle - React, Tailwind, and code Playground

by Pritesh Patel

HTML

<html>

  <body>
    <p>
      You are trying to copy a list of files to a directory. You are given two lists of names, one is the list of files you are trying to copy, the other is the list of files within the target directory.
    </p>
    <p>
      Implement a function that will return the list of suggested names for the list of files to copy. If there are duplicates, then the suggested name will contain the original name + "copy" + #. If there are no duplicates, then the suggested name will just be the original name.
    </p>
    <p>
      i.e. duplicate name format
      <ul>
        <li>hello</li>
        <li>hello copy</li>
        <li>hello copy 1</li>
      </ul>
    </p>
    <p>
      <b>Files to copy:</b><br />['hello', 'hello copy', 'world', 'test']
    </p>
    <p>
      <b>Existing files:</b><br />['hello', 'world', 'world copy']
    </p>
    <p>
      <b>Expected result:</b><br />["hello copy", "hello copy 1", "world copy 1", "test"]
    </p>
    <p>
      <b>Actual result:</b><br/><span id="result"></span>
    </p>
  </body>

</html>

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'
];

function suggestNames() {
const newFileNames = [];

	filesToCopy.forEach((file) => {
  console.log("file: ", file);
  // first check exist, ting and not in newFile then add copy
  console.log("==test: ", existingFiles.includes(file))
  console.log("copy word or not:", file.includes("copy"));
  	if(existingFiles.includes(file) && !file.substr("copy")) {
    	newFileNames.push(`${file} copy`)
    } else if(!existingFiles.includes(file) && !newFileNames.includes(file)) {
    	newFileNames.push(file)
    } else if (existingFiles.includes(file)) {
    }
  })
  console.log("newFileNames: ", newFileNames)

	return newFileNames;
}







/** DO NOT MODIFY BELOW THIS LINE **/
let result;
try {
  result = JSON.stringify(suggestNames());
} catch (e) {
  result = 'Render error';
}
document.getElementById('result').innerHTML = result;