-
-
Save anodynos/4392626 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# See http://www.traitsjs.org/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment