Last active
March 22, 2018 17:01
-
-
Save abstracthat/a2ed1985c67d7893f2ae to your computer and use it in GitHub Desktop.
Unspin Spintax with Coffeescript
This file contains 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
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. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To Do