Skip to content

Instantly share code, notes, and snippets.

@kevcodez
Created March 18, 2021 20:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevcodez/90e5774f3d0695d1f2b9db78abb87548 to your computer and use it in GitHub Desktop.
Save kevcodez/90e5774f3d0695d1f2b9db78abb87548 to your computer and use it in GitHub Desktop.
function doYourStuff() {
const yourString = "foobar"
const uniqueString = findUniqueString(yourString)
// continue with your logic with unique string
}
function findUniqueString(baseString) {
let uniqueString = baseString
// number of iterations should be super small, probably unnecessary to have a max threshold
// it would be smarter to not have this as unique identifier and have an additional field that
// is an auto-increment and have a composite key or something else
let iteration = 0
while(true) {
if (!existsInDatabase(uniqueString)) {
return uniqueString
} else {
iteration++
uniqueString = `${baseString}_${iteration}`
}
}
}
function existsInDatabase(str) {
return // <some query>
}
@valsopi
Copy link

valsopi commented Mar 18, 2021

Thanks Kevin!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment