Skip to content

Instantly share code, notes, and snippets.

@abstracthat
Last active March 22, 2018 17:01
Show Gist options
  • Save abstracthat/a2ed1985c67d7893f2ae to your computer and use it in GitHub Desktop.
Save abstracthat/a2ed1985c67d7893f2ae to your computer and use it in GitHub Desktop.
Unspin Spintax with Coffeescript
unspin = (text) ->
# spintax regex: "{" + anything not "{" or "}" + "}"
findSpintax = -> text.match /{[^{}]+?}/g
# while we find spintax keep unspinning it
while findSpintax text
# find spintax chunks and work on the first one
spintax = (findSpintax text)[0]
# put the spintax options in an array
options = spintax.split '|'
# choose a random index based on the array length
randomOption = Math.floor Math.random() * options.length
# choose a random option
choice = options[randomOption]
# the chunk is now unspun so remove the spintax braces from our choice
choice = choice.replace /{|}/g, ''
# put our unspun choice back into text
text = text.replace spintax, choice
# recursively run unspin
text = unspin text
# return the unspun text
text
# Example usage
sample = '{This {is|could be}|Try this} multi-level {spinning|spintax}.'
unspin sample
# sample output
# Try this multi-level spintax.
@abstracthat
Copy link
Author

To Do

  1. check for mismatched spintax braces (a common mistake when writing spintax manually)
  2. remove: optionally removes spintax by taking the first option of each spintax chunk
  3. all: optionally output all possible spintax variations

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