gkz / LiveScript

LiveScript is a language which compiles to JavaScript. It has a straightforward mapping to JavaScript and allows you to write expressive code devoid of repetitive boilerplate. While LiveScript adds many features to assist in functional style programming, it also has many improvements for object oriented and imperative programming.
http://livescript.net
MIT License
2.31k stars 156 forks source link

Feature request: Conditional function chaining #1109

Open ceremcem opened 3 years ago

ceremcem commented 3 years ago

I think it would be nice to have conditional function chaining, like the following:

a
  .x!
  .y! if foo
  .z!

...which will be compiled to:

var x$;
x$ = a;
x$ = x$.x();
if (foo) {
  x$ = x$.y();
}
x$ = x$.z();

This feature will be useful when we need a conditional middle step on a long function chain.

anko commented 3 years ago

For comparison, currently possible patterns:

  1. Cascade with conditional:

    a
      ..x!
        (if foo then ..y! else ..)
          ..z!
    var x$, y$, z$;
    x$ = a;
    y$ = x$.x();
    z$ = foo ? y$.y() : y$;
    z$.z();
  2. Pipe-chaining accessor functions:

    a
      |> (.x!)
      |> -> if foo then it.y! else it
      |> (.z!)
    (function(it){
      return it.z();
    })(
    function(it){
      if (foo) {
        return it.y();
      } else {
        return it;
      }
    }(
    function(it){
      return it.x();
    }(
    a)));

The suggested syntax would be clearer.