LoginSignup
5
5

More than 5 years have passed since last update.

Underscore.jsに満足できない人向けの拡張ライブラリ

Posted at

Underscore.jsとは

今更Underscore.jsが何かなんてものに興味がある人は少ないと思いますが、一応念の為に

  • 便利なユーティリティ郡
  • 豊富な配列操作関数
  • メソッドチェーンの仕組みの提供
  • 実行エンジンの仕様の差異を吸収した関数群

などなど、JavaScriptでコードを書く上で色々と便利な機能を提供してくれるライブラリです。
SPAフレームワークの『Backbone.js』もUnderscore.jsをバリバリに使って構築されているフレームワークです。
JavaScriptの言語仕様にして欲しいぐらい私好きです。

Underscore.jsのサンプルコード

例えば、1-10の2乗した結果を奇数と偶数に振り分けるプログラムはこんな感じに書くことができます。
んんクールですね。


var _ = require('underscore');
var arr = _.range(1, 11);
console.log(
  _(arr).chain()
        .map(function(x){
          return x * x;
        })
        .groupBy(function(x){
          return x % 2 ? '奇数' : '偶数';
        })
        .value()
);

今回の話のネタ

さて、このUnderscore.jsですが、更にパワーアップさせることができるので今回はどれくらいパワーアップできるのかを調べてみたので、いくつか紹介したいと思います。

Lodash

Underscore.jsとの互換性を保ったまま、新しいFunctionが追加されていたり、Underscore.jsのFunctionにパッチを当てて、柔軟な振る舞いをできるようにしたライブラリです。

例えば、Underscore.jsの.getとLodashの.getを見てみます
Lodashの.getでは『.』で繋いでcontextをたどっていくことができます。


var _ = require('underscore');
var object = { 'a': { 'b': { 'c': 3 } } };
console.log(_.has(object, 'a'));
console.log(_.has(object, 'a.b'));
console.log(_.has(object, 'a.b.c'));
// > true, false, false

var _ = require('lodash');
var object = { 'a': { 'b': { 'c': 3 } } };
console.log(_.has(object, 'a'));
console.log(_.has(object, 'a.b'));
console.log(_.has(object, 'a.b.c'));
// > true, true, true

カリー化した関数を作成するのも簡単にできます


var _ = require('lodash');

var curried = _.curry(function(a, b, c){
  return a * b * c;
});

console.log(curried(1)(2)(3));
console.log(curried(1, 2)(3));
console.log(curried(1)(2, 3));
console.log(curried(1, 2, 3));
console.log(curried(1)(_, 2)(3));

Lodash-math

Lodashに数学的な関数を追加するためのライブラリです。
以下のサンプルではそれぞれの平均値・中央値を出力するサンプルです。


var _ = require('lodash');
require('lodash-math')(_);

console.log(_.median([1, 2, 3, 4, 100]));
console.log(_.average([1, 2, 3, 4, 100]));
// > 3, 22

Lodash-inflection

文字列変換の関数を提供するライブラリ
自前のソースコードジェネレーターみたいな物を作るときに役に立ちそうです。


var _ = require('lodash-inflection');

console.log(_.pluralize('word'));
// -> words

console.log(_.singularize('words'));
// -> word

console.log(_.ordinalize(11));
// -> '11th'
5
5
1

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
5
5