Skip to content

Instantly share code, notes, and snippets.

@lukezhangstudio
Last active August 29, 2015 14:06
Show Gist options
  • Save lukezhangstudio/e14dbd82d6156d6f5390 to your computer and use it in GitHub Desktop.
Save lukezhangstudio/e14dbd82d6156d6f5390 to your computer and use it in GitHub Desktop.
Combining transforms with magic

Mastering when to use & and andThen

CssSel extends (NodeSeq)=>NodeSeq
  • This gives you some really cool things but also introduces a limitation or two.
  • & method ONLY exists on a CssSel
  • With CssSel, you are guarranteed that it will go thru its arguments only once. Not so with plain (NodeSeq) => NodeSeq

What does this mean in practice? If you have a method:

 renderBody = {
    "image [src]" #> someBodyStuff andThen
    "input code *" #> someBodyStuff &
 }

The use of the andThen inside it reduces this method to a (NodeSeq) => NodeSeq. You are no longer able to evaluate its arguments only once, and because of this, you can't combine it with a CssSel using &.

Typically, if you have a large chain of CssSel:

 "header" #> someHeader &
 "image [src]" #> someBodyStuff &
 "input code *" #> someBodyStuff andThen
 "pre code *" #> someBodyStuff &
 "footer [style+]" #> someFooterStyle

you might refactor this into something more readable:

 renderHeader &
 renderBody &
 renderFooter

However, because you've used andThen inside the body transforms, then you can no longer chain renderHeader together with renderBody using &. You must use andThen instead.

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