Skip to content

Commit

Permalink
Add some more utility functions, min, max, throttle, debounce
Browse files Browse the repository at this point in the history
  • Loading branch information
koenbok committed Dec 26, 2012
1 parent 075b827 commit 3c2d257
Showing 1 changed file with 41 additions and 23 deletions.
64 changes: 41 additions & 23 deletions src/utils.coffee
Expand Up @@ -33,16 +33,6 @@ exports.filter = (a, f) ->
exports.union = -> exports.union = ->
Array.prototype.concat.apply Array.prototype, arguments Array.prototype.concat.apply Array.prototype, arguments


# exports.extend = (a, b) ->
# for key of b
# a[key] = b[key]
# return a
#
# exports.update = (a, b) ->
# for key of a
# a[key] = b[key] if b[key]
# return a
#
exports.toggle = -> exports.toggle = ->
args = Array.prototype.slice.call arguments args = Array.prototype.slice.call arguments
curr = -1 curr = -1
Expand All @@ -62,11 +52,39 @@ exports.delay = (time, f) ->
window._delayTimers.push timer window._delayTimers.push timer
return timer return timer


exports.interval = (time, f) ->
timer = setInterval f, time
window._delayIntervals ?= []
window._delayIntervals.push timer
return timer

exports.remove = (a, e) -> exports.remove = (a, e) ->
a.splice(t,1)[0] if (t = a.indexOf(e)) > -1 a.splice(t,1)[0] if (t = a.indexOf(e)) > -1
a a




exports.debounce = (func, threshold, execAsap) ->
timeout = null
(args...) ->
obj = this
delayed = ->
func.apply(obj, args) unless execAsap
timeout = null
if timeout
clearTimeout(timeout)
else if (execAsap)
func.apply(obj, args)
timeout = setTimeout delayed, threshold || 100

exports.throttle = (fn, delay) ->
return fn if delay is 0
timer = false
return ->
return if timer
timer = true
setTimeout (-> timer = false), delay unless delay is -1
fn arguments...



# exports.copy = (a, propertyList) -> # exports.copy = (a, propertyList) ->
# b = {} # b = {}
Expand All @@ -91,21 +109,21 @@ exports.remove = (a, e) ->
# console.log exports.filter a, (k, v) -> k in ["x"] # console.log exports.filter a, (k, v) -> k in ["x"]




# Array::max = -> exports.max = (obj) ->
# for n in @ for n in obj
# if !max or n > max then max = n if !max or n > max then max = n
# max max


# Array::min = -> exports.min = (obj) ->
# for n in @ for n in obj
# if !min or n < min then min = n if !min or n < min then min = n
# min min


# Array::sum = -> exports.sum = (a) ->
# if @length > 0 if a.length > 0
# @reduce (x, y) -> x + y a.reduce (x, y) -> x + y
# else else
# 0 0


# exports.clone = (obj) -> # exports.clone = (obj) ->
# if not obj? or typeof obj isnt 'object' # if not obj? or typeof obj isnt 'object'
Expand Down

0 comments on commit 3c2d257

Please sign in to comment.