Skip to content

Instantly share code, notes, and snippets.

@wereHamster
Created April 20, 2011 07:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wereHamster/930634 to your computer and use it in GitHub Desktop.
Save wereHamster/930634 to your computer and use it in GitHub Desktop.
bash-like brace expansion in coffee-script
{ _ } = require 'underscore'
assert = require 'assert'
expand = (path) ->
tokens = _.compact path.split /({|}|,)/
merge = (array, element) ->
(el + element) for el in array
collect = (tokens) ->
ret = []
current = [ '' ]
while token = tokens.shift()
if token == ','
ret.push current
current = [ '' ]
else if token == '{'
current = _.flatten(merge current, t for t in collect tokens)
else if token == '}'
break
else
current = merge current, token
ret.push current
return _.flatten(ret)
return collect tokens
module.exports =
'a,b': ->
assert.deepEqual ['a', 'b'], expand('a,b')
'{a,b}': ->
assert.deepEqual ['a', 'b'], expand('a,b')
'p{a,b}': ->
assert.deepEqual ['pa', 'pb'], expand('p{a,b}')
'p{a,b}s': ->
assert.deepEqual ['pas', 'pbs'], expand('p{a,b}s')
'a{b,c},d': ->
assert.deepEqual ['ab', 'ac', 'd'], expand('a{b,c},d')
'p{a{b,c},d}s': ->
assert.deepEqual ['pabs', 'pacs', 'pds'], expand('p{a{b,c},d}s')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment