Skip to content

Instantly share code, notes, and snippets.

@mohayonao
Last active December 17, 2015 22:29
Show Gist options
  • Save mohayonao/5682428 to your computer and use it in GitHub Desktop.
Save mohayonao/5682428 to your computer and use it in GitHub Desktop.
CoffeeScriptで演算子のオーバーロードっぽいやつ
overloadable = do ->
operator = (op, b)->
a = @value()
b = b.value?() ? b
fn = switch op
when '+' then (a, b)-> a + b
when '-' then (a, b)-> a - b
when '*' then (a, b)-> a * b
when '/' then (a, b)-> a / b
if Array.isArray(a)
if Array.isArray(b)
if a.length > b.length
overloadable a.map (a, i)-> fn a, b[i % b.length]
else
overloadable b.map (b, i)-> fn a[i % a.length], b
else
overloadable a.map (a)-> fn a, b
else if Array.isArray(b)
overloadable b.map (b) -> fn a, b
else
overloadable fn a, b
(value)->
that = operator.bind value: -> value
that.value = -> value
that
a = overloadable [ 1, 2, 3, 4 ]
console.log a.value() # [ 1, 2, 3, 4 ]
b = a "+", [ 100, 200 ] # [ 1, 2, 3, 4 ] + [ 100, 200 ] =
console.log b.value() # [ 101, 202, 103, 204 ]
c = b "*", 2 # [ 101, 202, 103, 204 ] * 2 =
console.log c.value() # [ 202, 404, 206, 408 ]
d = c "-", (a "*", 2) # [ 202, 404, 206, 408 ] - ([ 1, 2, 3, 4 ] * 2) =
console.log d.value() # [ 200, 400, 200, 400 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment