Skip to content

Instantly share code, notes, and snippets.

@thybzi
Last active February 23, 2016 10:31
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 thybzi/ea19874d7167ef2e738c to your computer and use it in GitHub Desktop.
Save thybzi/ea19874d7167ef2e738c to your computer and use it in GitHub Desktop.
Ostap Bender: The Great Combinator (of Stylus): http://codepen.io/thybzi/pen/PZMPob
// Get both inverse and forward combinated subject and current selector
// Example: .parent > .curr + .subj, .parent > .subj + .curr
// If subj is omitted, get current selector combinated with itself
// Example: .parent > .curr + .curr
// Limitation: Fails if parent selector level contains more that one combinator
// Limitation: Nesting calls cause exception
combinate(comb, subj='^[-1..-1]')
parts = ('&' + pad-combinator(comb) + subj)
if subj != '^[-1..-1]'
push(parts, combinate-inv(comb, subj))
return join(', ', parts)
// Get inverse combinated subject and current selector
// Example: .parent > .subj + .curr
// Limitation: Fails if parent selector level contains more that one combinator
// Limitation: Nesting calls cause exception
combinate-inv(comb, subj='^[-1..-1]')
pcomb = get-combinator('&')
comb = pad-combinator(comb)
return '../' + pcomb + subj + comb + '^[-1..-1]'
// Get last combinator applied
get-combinator(sel)
scurr = selectors(sel)[-1]
combs = ('~' '>' '+')
notcombs = '\s*[^' + join('', combs) + ']+\s*'
for comb in combs
esc = (comb == '+') ? '\\' : ''
if match(esc + comb + notcombs + '$', scurr)
return pad-combinator(comb)
return ' '
// Surround combinator with spaces, if necessary
pad-combinator(comb)
if comb != ' '
comb = ' ' + comb + ' '
return comb
// Let the fun begin!
.wrapper + .parent
& > figure
/*!* Test #0 (inverse combinator pre-check): SUCCESS */
{combinate-inv('+', '*')}
color: #000
& > figure
/*!* Test #1 (single parent combinator, default subj): SUCCESS */
{combinate('+')}
color: #111
/*!* Test #2 (single parent combinator): SUCCESS */
{combinate('~', '*')}
color: #222
& figure
/*!* Test #3 (space parent combinator): SUCCESS */
{combinate('~', '*')}
color: #333
figure
/*!* Test #4 (implicit space parent combinator): SUCCESS */
{combinate('~', '*')}
color: #444
& > figure + p
/*!* Test #5.1 (two parent combinators): FAIL TO GET PARENT COMBINATOR */
{combinate('~', '*')}
color: #515151
/*!* Test #5.2 (two parent combinators, default subj): TOTAL EPIC FAIL */
{combinate('~')}
color: #525252
& > figure
/*!* Test #6 (nested): FAIL WITH EXCEPTION */
// {combinate-inv('+', 'p')}
// color: #616161
// {combinate-inv('~', 'h1')}
// color: #626262
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment