gist

2012年6月18日月曜日

CoffeeScriptで学ぶ Underscore.js 10(Function編)

Underscore.js、10回目。Function編です。


throttle

_.throttle(function, wait)

throttleは、waitで指定したミリ秒に1回だけfunctionを実行します。

_ = require 'underscore'

hello = ()->
 console.log 'Hello!'

throttled = _.throttle hello, 1000

for x in [1..100000]
 do ()->
  throttled()

実行結果
$ coffee throttle.coffee 
Hello!
Hello!

Hello!が1秒ごとに表示されます。


debounce

_.debounce(function, wait, [immediate])

debounceは、waitで指定したミリ秒が経過するまでfunctionを繰り返し呼ばれないようにします。

_ = require 'underscore'

hello = ()->
 console.log 'Hello!'

lazyFunc = _.debounce hello, 1000

lazyFunc()

実行結果
$ coffee debounce.coffee 
Hello!

once

_.once(function)

onceは、関数を1回しか呼ばれないようにすることができます。

_ = require 'underscore'

createApplication = ()->
 console.log 'Initialize!'

initialize = _.once createApplication

initialize()
initialize()
実行結果
$ coffee once.coffee 
Initialize!

after

_.after(count, function)

afterは、countで指定された回数だけfunctionが呼ばれると初めて実行されます。

_ = require 'underscore'

hello = ()->
 console.log 'Hello!'

after = _.after(5, hello);

after()
after()
after()
after()
after()

実行結果
$ coffee after.coffee 
Hello!

wrap

_.wrap(function, wrapper)

wrapは、functionで指定した関数をwrapperの中で使うことができます。

_ = require 'underscore'

hello = (name)->
 'Hello, ' + name

wrapped = _.wrap hello, (func)->
 "before: " + func('World') + " : after"

console.log wrapped()
実行結果
$ coffee wrap.coffee 
before: Hello, World : after

compose

_.compose(*functions)

composeは、複数の関数を与えると合成関数として返します。f(), g(), h()を合成すると、f(g(h())) を返します。

_ = require 'underscore'

hello = (name)->
 'Are you ' + name

question = (statement)->
 statement + '?'

who = _.compose hello, question


console.log who('moe')
実行結果
$ coffee compose.coffee 
Are you moe?

関連ページ

0 件のコメント: