Created
July 14, 2011 01:28
-
-
Save aseemk/1081702 to your computer and use it in GitHub Desktop.
CoffeeScript's awesome inheritance model lets you strip boilerplate type checking.
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
# WARNING: This will no longer work with CoffeeScript 1.3.2 in IE: | |
# http://coffeescript.org/#changelog | |
class Animal | |
@is: (node) -> | |
if not @TYPE then return true | |
node.type is @TYPE | |
@isnt: (node) -> | |
not @is node | |
class Cat extends Animal | |
@TYPE: @name | |
class Dog extends Animal | |
@TYPE: @name | |
constructor: -> | |
super | |
@kind = @constructor.KIND | |
@is: (node) -> | |
node.type is @TYPE and ( | |
if not @KIND then true else node.kind is @KIND | |
) | |
class Corgi extends Dog | |
@KIND: @name | |
class Poodle extends Dog | |
@KIND: @name | |
test = (msg, cond) -> | |
alert "#{msg}: #{if cond then 'pass' else 'FAIL'}" | |
bob = new Cat() | |
test 'bob SHOULD be an animal', Animal.is bob | |
test 'bob SHOULD be a cat', Cat.is bob | |
test 'bob should NOT be a dog', Dog.isnt bob | |
ein = new Corgi() | |
test 'ein SHOULD be an animal', Animal.is ein | |
test 'ein should NOT be a cat', Cat.isnt ein | |
test 'ein SHOULD be a dog', Dog.is ein | |
test 'ein SHOULD be a corgi', Corgi.is ein | |
test 'ein should NOT be a poodle', Poodle.isnt ein |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
what's that have to do with CS? Ideally JS wouldn't have instanceof or typeof, but I dont think CS has anything to do with that. protos > classes