Underscore.jsおさらい6(Utility、Chaining)

noConflict _.noConflict()

underscoreは「_」がデフォルトだが、他のライブラリで使っていると衝突するので衝突防止。

var underscore = _.noConflict();


identity _.identity(value)

引数自身を返す。f(x) = xの処理。underscoreのiterateeデフォルト判定。

var stooge = {name: 'moe'};
stooge === _.identity(stooge);
=> true


constant _.constant(value)

value自身を返す関数を作る。

var stooge = {name: 'moe'};
stooge === _.constant(stooge)();
=> true


noop _.noop()

空の関数 function(){} を返す。

times _.times(n, iteratee, [context])

n回分 iterateeを実行する。各結果の戻り値が詰められた配列を返す。
iterateeの引数はindex。

_.times(5, function(n) { return n * n; });
=> [0, 1, 4, 9, 16]


random _.random(min, max)

min以上、max以下の整数値乱数を返す。

mixin _.mixin(object)

underscore関数を新たに定義する。

_.mixin({
  capitalize: function(string) {
    return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase();
  }
});
_("fabio").capitalize();
=> "Fabio"
_.capitalize("mario");
=> Mario


iteratee _.iteratee(value, [context])

underscoreのiteratee用関数を作成する。
valueがnullなら.identity、オブジェクトなら.matcher、関数ならその関数、それ以外(文字列とか)なら_.propertyを返す。

uniqueId _.uniqueId([prefix])

1から順番にカウントアップした数字を返す。prefixがあれば接頭語として付ける。

_.uniqueId();
=> 1
_.uniqueId('id');
=> id2
_.uniqueId('no_');
=> no_3


escape _.escape(string)

HTMLエスケープする。

unescape _.unescape(string)

HTMLアンエスケープする。

result _.result(object, property, [defaultValue])

オブジェクトのプロパティ値を返す。
指定したプロパティがメソッドならばメソッドの戻り値を返す。 propertyに指定したキー、メソッドが無い場合、defaultValueが指定されていればdefaultValueの値が返る。

_.result(object, 'cheese');
=> "crumpets"
_.result(object, 'stuff');
=> "nonsense"
_.result(object, 'meat', 'ham');
=> "ham"


now _.now()

現在時刻のミリ秒を返す。

template _.template(templateString, [settings])

backboneを使うなら再優先で覚えるべきもの。
文字列テンプレートにオブジェクトの値をマッピングさせる、いわゆるテンプレートエンジン。
JavaならVelocity、PHPならSmartyをイメージすればいい。
<%= %>はそのまま、<%- %>はHTMLエスケープして出力する。<% %>を使えばコードも埋め込める。
_.templateSettingsでテンプレート文字を好きに変更できる。

var compiled = _.template("hello: <%= name %>");
compiled({name: 'moe'});
=> "hello: moe"

var template = _.template("<b><%- value %></b>");
template({value: '<script>'});
=> "<b>&lt;script&gt;</b>"

var compiled = _.template("<% print('Hello ' + epithet); %>");
compiled({epithet: "stooge"});
=> "Hello stooge"

_.templateSettings = {
  interpolate: /\{\{(.+?)\}\}/g
};

var template = _.template("Hello {{ name }}!");
template({name: "Mustache"});
=> "Hello Mustache!"


chaning

underscoreの各関数は関数呼び出し風にも書ける。

_.map([1, 2, 3], function(n){ return n * 2; });
_([1, 2, 3]).map(function(n){ return n * 2; });

そのため、特にコレクション系なんかで複数の処理をまとめてやりたいときに、メソッドチェーンで書ける。
Javaな人はJava8のStream APIと言えば分かる。

chain _.chain(obj)
value _(obj).value()

chainはメソッドチェーン用の関数。引数のobjをラップする。
valueは最終的な値の取り出し用。

_.chain(lyrics)
  .map(function(line) { return line.words.split(' '); })
  .flatten()
  .reduce(function(counts, word) {
    counts[word] = (counts[word] || 0) + 1;
    return counts;
  }, {})
  .value();

=> {lumberjack: 2, all: 4, night: 2 ... }

おさらい、完了!