Skip to content

Instantly share code, notes, and snippets.

@joyrexus
Last active December 15, 2015 11:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joyrexus/5250576 to your computer and use it in GitHub Desktop.
Save joyrexus/5250576 to your computer and use it in GitHub Desktop.
Little hack for callable classes.

Callable Classes

A quick little hack to make a class callable.

Note that this is generally inadvisable and can be avoided altogether by assigning the target class method to a function.

Hack

class Counter

    constructor: (@name, @total) ->
        alias = -> alias.inc(arguments...)
        alias[k] = v for k, v of @
        return alias

    inc: (value) => 
      @total[value] or= 0
      @total[value] += 1


{ok} = require 'assert'

x = new Counter 'x', {a: 1}
x('a')
x('b')
x('c')
x('b')

ok x.total.a is 2
ok x.total.b is 2
ok x.total.c is 1

Better

Define your class in the standard way.

class Counter

    constructor: (@name, @total) ->

    inc: (value) => 
      @total[value] or= 0
      @total[value] += 1

After instantiating, assign the class method to your preferred abbreviation.

Y = new Counter 'y', {a: 1}
y = Y.inc
y('a')
y('b')
y('c')
y('b')

ok Y.total.a is 2
ok Y.total.b is 2
ok Y.total.c is 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment