技術探し

JavaScriptを中心に記事を書いていきます :;(∩´﹏`∩);:

Pipeline Operatorがstage-1へ

github.com

先月のTC39のMTGでstage-1になりました。

F#, OCaml, Elixir, Elm, Julia, Hack, LiveScriptなどと似たような機能を提供します。

function doubleSay (str) {
  return str + ", " + str;
}

function capitalize (str) {
  return str[0].toUpperCase() + str.substring(1);
}

function exclaim (str) {
  return str + '!';
}

let result = exclaim(capitalize(doubleSay("hello"))); // "Hello, hello!"

let result = "hello"
  |> doubleSay // ここの引数が `hello`になる
  |> capitalize
  |> exclaim; // "Hello, hello!"

上記のコードを読めばわかりますが、ネストされた関数を読みやすくします。

例えば、引数を複数持つ関数でPipeline operatorを使いたい場合は以下のようになります。

function double (x) { return x + x; }
function add (x, y) { return x + y; }

function boundScore (min, max, score) {
  return Math.max(min, Math.min(max, score));
}

let newScore = boundScore(0, 100, add(7, double(person.score)));

let person = { score: 25 };
let newScore = person.score
  |> double // ここの引数が25
  |> _ => add(7, _) // `_`はdoubleの戻り値
  |> _ => boundScore(0, 100, _); // 57 // `_`はaddの戻り値