Created
November 10, 2015 17:25
-
-
Save jsteinbeck/d40ea5fb7b4bb7c6aea3 to your computer and use it in GitHub Desktop.
Example for using ENJOY.js multimethods
This file contains hidden or 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
var method = require("enjoy-js").method; | |
var specialize = require("enjoy-js").specialize; | |
var is_object = require("enjoy-js").is_object; | |
var is_string = require("enjoy-js").is_string; | |
// Defining a multimethod with a default implementation: | |
var hello = method(function () { | |
return "Hello!"; | |
}); | |
// Adding some implementations to the multimethod: | |
specialize(hello, is_person, is_english, function (person) { | |
return "Hello " + person.name + "!"; | |
}); | |
specialize(hello, is_person, is_german, function (person) { | |
return "Guten Tag, " + person.name + "!"; | |
}); | |
specialize(hello, is_person, "ja_JP", function (person) { | |
return "今日は, " + person.name + "さん!"; | |
}); | |
// Calling the multimethod: | |
console.log(hello()); // "Hello!" | |
console.log(hello(person("Pete"), "en_US")); // "Hello Pete!" | |
console.log(hello(person("Douglas"), "en_GB")); // "Hello Douglas!" | |
console.log(hello(person("Jonathan"), "de_DE")); // "Guten Tag, Jonathan!" | |
/* ------------------------- | |
Little helpers | |
------------------------- */ | |
// Some predicate functions: | |
function is_person (thing) { | |
return is_object(thing) && thing.type === "person"; | |
} | |
function is_english (code) { | |
return is_string(code) && code.match(/^en/); | |
} | |
function is_german (code) { | |
return is_string(code) && code.match(/^de/); | |
} | |
// Function that creates persons: | |
function person (name) { | |
return { | |
type: "person", | |
name: name | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment