gist

2012年6月27日水曜日

CoffeeScriptで学ぶ Underscore.js 13(Utility編)

いよいよUtility編。大詰めです。


noConflict

_.noConflict

noConflictは、変数である「_」(アンダースコア)を別の変数に置き換えることができます。Underscoreのオブジェクトを返します。

_ = require 'underscore'

underscore = _.noConflict()

_ = 10

console.log _
console.log underscore
実行結果
$ coffee noConflict.coffee 
10
{ [Function]
  _: [Circular],
  VERSION: '1.3.3',
  forEach: [Function],
  each: [Function],
  collect: [Function],
  map: [Function],
...

identity

_.identity(value)

identityは、valueを与えたとき、返り値としてそのままvalueを返します。underscoreの初期のイテレータに利用されているそうな。

_ = require 'underscore'

moe = {name:'moe'}

console.log moe is _.identity moe
実行結果
$ coffee identity.coffee 
true

times

_.times(n, iterator)

timesは、iteratorをn回実行します。

_ = require 'underscore'

_.times 10, ()->
 console.log 'hello'
実行結果
$ coffee times.coffee 
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello

mixin

_.mixin(object)

mixinは、Underscoreにカスタマイズした関数を追加することができます。{関数名:関数} というオブジェクトを追加することで、Underscoreのオブジェクトとして定義できます。

_ = require 'underscore'

_.mixin {
 capitalize:(string)->
  string.charAt(0).toUpperCase() + string.substring(1).toLowerCase()
}

console.log _.capitalize "underscore"
実行結果
$ coffee mixin.coffee 
Underscore

uniqueId

_.uniqueId([prefix])

uniqueIdは、グローバル域で一意なIDを生成します。引数にプレフィックスを与えることができます。

_ = require 'underscore'

console.log _.uniqueId()
console.log _.uniqueId()
console.log _.uniqueId()
console.log _.uniqueId()
console.log _.uniqueId('CB')
実行結果
$ coffee uniqueId.coffee 
0
1
2
3
CODE4

escape

_.escape(string)

escapeは、HTMLなどの&, <, >, &quat;, ', / をエスケープ処理して返します。

_ = require 'underscore'

console.log _.escape '&,<,>,&quat;,\',/'
実行結果
$ coffee escape.coffee 
&amp;,&lt;,&gt;,&quot;,&#x27;,&#x2F;

result

_.result(object, property)

resultは、指定したobjectのプロパティを返します。プロパティが値の場合はそのまま値が、関数の場合、その関数を実行します。

_ = require 'underscore'

hoge = 
 foo: 'hello'
 bar: ()->
  'good morning'

console.log _.result hoge, 'foo'
console.log _.result hoge, 'bar'
実行結果
$ coffee result.coffee 
hello
good morning

関連ページ

0 件のコメント: