DEV Community

Discussion on: Generating Random Human-Readable Slugs in JavaScript

Collapse
 
nas5w profile image
Nick Scialli (he/him)

It's not included currently, but could pretty easily be adapted:

const adjective = ['blue', 'smiley', 'funny', 'smelly'];
const noun = ['brick', 'kangeroo', 'penguin', 'laptop'];
const words = { adjective, noun };
const order = ['adjective', 'adjective', 'noun'];
const used = new Set();

const selected = order.map(partOfSpeech => {
  const choices = words[partOfSpeech].filter(word => !used.has(word));
  const newWord = choices[Math.floor(Math.random() * choices.length)];
  used.add(newWord);
  return newWord;
});

const slug = selected.join('-');
console.log(slug);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
marcellothearcane profile image
marcellothearcane

That's true, but then if the lists are long it might take a while to filter through. I would use the indexes I think, then you can check much more simply.