LoginSignup
2
1

More than 5 years have passed since last update.

ramda

Last updated at Posted at 2017-09-11

http://qiita.com/akameco/items/e5bbefefd5940dff84d9
上記ramdaのpipeとcomposeの続き。

R.always

const t = R.always('Tee')
t() // => Tee

実装を見ると
https://github.com/ramda/ramda/blob/v0.24.1/src/always.js

module.exports = _curry1(function always(val) {
  return function() {
    return val;
  };
});

なので常に引数を返す関数

a -> (* -> a)

R.T

常にtrueを返す関数

* -> Boolean

R.concat

Array#concatとの違いは、型が違うとエラーを起こす
また、文字列の合成を行う。

R.pipeして最終的にconcatに繋げる。
concatに繋げるときにR.__を使うと合成出来て便利

R.__

{'@@functional/placeholder': true};

ここに引数が挿入される

var hello = R.concat(R.__, ' hello')
hello('world') // => world hello

R.path

オブジェクトの要素を取り出すのに便利
新しいプロポーサルの?と似たようなもの。

どんなときramdaを使うか

一部じゃなくて、ガッツリ全体で使うようにするとよさそうです。


import R from 'ramda';

const API_CORS = 'https://hogehoge.now.sh';
const API_ORIGIN = 'https://hogehgoeorig.now.sh';

const getFetchURL = R.pipe(
  R.path(['location', 'hostname']),
  R.cond([
    [R.test(/mywebsite\.com/), R.always(API_ORIGIN)],
    [R.T, R.always(API_CORS)],
  ]),
  R.concat(R.__, '/graphql'), // eslint-disable-line
);

export default getFetchURL;

上記はwindowsオブジェクトを引数にして、対象のURLを生成する関数です。
R.pipeによって関数を適用した結果を後ろに流し、R.condがif/switchの代わりとなり、R.concatが最終的に文字列を合成します。

まとめ

別に使わなくても書けますが、これを使うと上記のようにifやswitchなどいらずに書けるのは利点と言えるのではないでしょうか?
まあ、個人的にはこれが依存に入っているブラウザ向けライブラリはサイズ的に使おうとも思いませんが。

ともあれ、ライブラリ向けというよりアプリケーション向けのライブラリであることは確かでしょう。関数型言語が得意な人にとってはいいのかもですね。しかし、最近のOSSでは、これが使われている実装が多く、少なくとも代表的な関数は覚えておいて損はないでしょう。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1