From 5f57155fb7052dd9cadf5e8892fc6141da17eba3 Mon Sep 17 00:00:00 2001 From: Serge Tsepodoy Date: Wed, 25 Sep 2024 15:41:53 +0500 Subject: [PATCH] feat[hexlet-rus#542]: add more flexible logic into duplicate creator function to avoid infinite copy creation --- frontend/src/utils/genDuplicateSnippetName.js | 26 ++++++++++++------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/frontend/src/utils/genDuplicateSnippetName.js b/frontend/src/utils/genDuplicateSnippetName.js index 93ca9e29..91431284 100644 --- a/frontend/src/utils/genDuplicateSnippetName.js +++ b/frontend/src/utils/genDuplicateSnippetName.js @@ -2,19 +2,25 @@ import { SNIPPET_NAME_MAX_LENGTH } from './validationSchemas'; const genDuplicateSnippetName = (fileName) => { const extensionIndex = fileName.lastIndexOf('.'); + const copyTextIndex = fileName.lastIndexOf('-copy'); + const dashIndex = fileName.lastIndexOf('_'); + const existCopyNumber = Number(fileName.slice(dashIndex + 1)); + console.log(copyTextIndex, dashIndex, existCopyNumber, extensionIndex); let finalName = ''; + const extension = extensionIndex !== -1 ? fileName.slice(extensionIndex) : ''; - if (extensionIndex === -1) { - finalName = `${fileName}-copy`; - } else { - const [name, extension] = [ - fileName.slice(0, extensionIndex), - fileName.slice(extensionIndex + 1), - ]; - - finalName = `${name}-copy.${extension}`; - } + if (copyTextIndex !== -1) { + if (dashIndex > copyTextIndex) { + finalName = `${fileName.slice(0, dashIndex)}_${ + existCopyNumber + 1 + }${extension}`; + } else if (extensionIndex !== -1) { + finalName = `${fileName.slice(0, extensionIndex)}_${1}${extension}`; + } else { + finalName = `${fileName}_${1}${extension}`; + } + } else finalName = `${fileName}-copy${extension}`; if (finalName.length >= SNIPPET_NAME_MAX_LENGTH) { return finalName.slice(finalName.length - SNIPPET_NAME_MAX_LENGTH);