Created
January 20, 2022 19:16
-
-
Save th3terrorist/ea8374bb4e9145b5f926f9f550b5d0d2 to your computer and use it in GitHub Desktop.
Generate file names like a file manager
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const generateNameInContext = (name, defaultName, namesContext) => { | |
if (!defaultName) { | |
defaultName = "Item"; | |
} | |
if (!name) { | |
name = defaultName; | |
} | |
const fmtName = (number) => `${name}(${number})`; | |
let pattern = /\((.*?)\)$/; //used to find clone number in "<Name>(idx)" | |
if (namesContext.includes(name) === false) { | |
return name; | |
} | |
let cloneNumbers = namesContext | |
.map(n => [n, pattern.exec(n)]) | |
.filter(([_, match]) => match) | |
.filter(([n, match]) => name === n.substring(0, match.index)) | |
.map(([_, match]) => parseInt(match[1])); | |
if (cloneNumbers.length === 0) { | |
return fmtName(1); | |
} | |
let max = Math.max(...cloneNumbers); | |
return fmtName(max + 1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment