public
Last active

Example usecases of JS-CLOS https://github.com/ympbyc/js-clos

  • Download Gist
bump.coffee
CoffeeScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#||||||||||||||||||||||||||||||||||||||||
#||||| example of multiple dispatch |||||
#||||||||||||||||||||||||||||||||||||||||
 
floor = define_class []
carpet = define_class []
ball = define_class []
glass = define_class []
 
bump = define_generic()
 
define_method bump, [ball, floor], -> 'bounce'
define_method bump, [glass, floor], -> 'crash'
define_method bump, [undefined, carpet], -> 'silence'
 
bump ball, floor #bounce
bump (make ball), (make floor) #bounce
 
bump glass, floor #crach
 
bump ball, carpet #silence
bump glass, carpet #silence
clos-fact.coffee
CoffeeScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#|||||||||||||||||||||||||||||||||||
#||||| example of multimethods |||||
#|||||||||||||||||||||||||||||||||||
 
#fact
 
fact = define_generic()
 
define_method fact, [0], -> 1
 
define_method fact, ["number"], (n) ->
n * fact (n - 1)
 
fact 5
#=> 120
import.coffee
CoffeeScript
1 2 3
# import
c = require 'clos'
this[name] = fn for name, fn of c
lion.coffee
CoffeeScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#|||||||||||||||||||||||||||||||||||||||||||
#||||| example of multiple inheritance |||||
#|||||||||||||||||||||||||||||||||||||||||||
 
# domain
animal = define_class [], (x) ->
slot_exists x, 'voice', 'string'
 
cat = define_class [animal]
 
osx = define_class [], (x) ->
slot_exists x, 'hostname', 'string'
 
lion = define_class [cat, osx]
 
# definitions
 
say = define_generic()
define_method say, [animal], (a) -> a.voice
define_method say, [cat], (c) -> c.voice + ' meow'
 
hostname = define_generic()
define_method hostname, [osx], (o) -> o.hostname
 
# main
 
alice = make lion,
voice: 'roar'
hostname: 'example.com'
 
say alice
#=> 'roar meow'
 
hostname alice
#=> 'example.com'

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.