Skip to content

Instantly share code, notes, and snippets.

@supersym
Last active December 10, 2015 14:38
Show Gist options
  • Save supersym/4448706 to your computer and use it in GitHub Desktop.
Save supersym/4448706 to your computer and use it in GitHub Desktop.
JavaScript

Problem

You want to call a function from within that same function.

Solution

You can use the named function identifier to call from inside. Named functions have as advantage that they keep their purpose more explicit, it's better readible and maintainable this way.

ping = ->
  console.log "Pinged"
	setTimeout ping, 1000

With an unnamed function, using @arguments.callee@ which allows for recursion of anonymous functions. Might also have advantage in memory-intensive application.

delay = 1000

setTimeout((->
  console.log "Pinged"
	setTimeout arguments.callee, delay
	), delay)

Problem

You want to detect if a function exists and create it if it does not (such as an ECMAScript 5 function in Internet Explorer 8).

Solution

Use the :: sign to access prototype methods and to detect the function, also assign to it if non-existent.

unless Array::filter
  Array::filter = (callback) ->
    element for element in this when callback element

array = [1..10]

array.filter (x) -> x > 5
# => [6,7,8,9,10]

Problem

You want to execute a function only once, coalescing multiple sequential calls into a single execution at the beginning or end.

Solution

With a named function

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment