Skip to content

Instantly share code, notes, and snippets.

@rstuven
Last active September 30, 2015 20:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rstuven/1855308 to your computer and use it in GitHub Desktop.
Save rstuven/1855308 to your computer and use it in GitHub Desktop.
traits.js tutorial in CoffeeScript
# See http://soft.vub.ac.be/~tvcutsem/traitsjs/tutorial.html
Trait = require('traits').Trait
EnumerableTrait = Trait
# the trait requires these properties
forEach: Trait.required
# the trait provides these properties:
map: (fun) ->
seq = []
@forEach (e,i) ->
seq.push fun e,i
seq
filter: (pred) ->
seq = []
@forEach (e,i) ->
if pred(e,i)
seq.push e
seq
reduce: (init, fun) ->
result = init
@forEach (e,i) ->
result = fun result, e, i
result
contains: (e) ->
result = @filter elt -> elt == e
result.length > 0
ComparableTrait = Trait
'<': Trait.required # @['<'](other) -> boolean
'==': Trait.required # @['=='](other) -> boolean
'<=': (other) ->
@['<'](other) or @['=='](other)
'>': (other) ->
other['<'](@)
'>=': (other) ->
other['<'](@) or @['=='](other)
'!=': (other) ->
not (@['=='](other))
makeInterval = (min, max) ->
Trait.create(
Object.prototype,
Trait.compose(
Trait.resolve(contains: undefined, EnumerableTrait),
ComparableTrait,
Trait
start: min,
end: max,
size: max - min - 1
toString: () -> "#{min}..!#{max}"
contains: (e) -> (min <= e < max)
'<': (ival) -> max <= ival.start
'==': (ival) -> min == ival.start and max == ival.end
forEach: (consumer) ->
for i in [min...max]
consumer i, i-min
)
)
i1 = makeInterval 0, 5
console.log i1.start # 0
console.log i1.end # 5
console.log i1.reduce 0, (a,b) -> a+b # 0+1+2+3+4 = 10
i2 = makeInterval 7, 12
console.log i1['=='] i2 # false
console.log i1['<'] i2 # true
@anodynos
Copy link

Hi thanks for the tutorial

Can you assess if traitjs is safe to use along with Coffeescript, without having weirdness and side effects ?

Are you aware if it has been used in practice in non trivial project ?

I just read http://howtonode.org/traitsjs and really prefer it to extend(), but then I saw this comment and made me cautious jashkenas/coffeescript#636

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment