Created
May 24, 2015 19:11
-
-
Save mklishevych/928dddc0afa51a7e7d04 to your computer and use it in GitHub Desktop.
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
'use strict'; | |
function multi(pred) { | |
var methods = Map(); | |
var fn = function fn() { | |
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { | |
args[_key] = arguments[_key]; | |
} | |
var methodFn = methods.get(pred.apply(undefined, args)); | |
return methodFn ? methodFn.apply(undefined, args) : null; | |
}; | |
fn.method = function (predKey, methodFn) { | |
methods.set(predKey, methodFn); | |
return this; | |
}; | |
return fn; | |
} | |
var hello = multi(function (data) { | |
return data.type; | |
}).method('user', function (data) { | |
return 'Hello, ' + data.name; | |
}).method('guest', function () { | |
return 'Hello, stranger'; | |
}); | |
console.log(hello({ | |
type: 'user', | |
name: 'Andrey' | |
})); | |
console.log(hello({ | |
type: 'guest' | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment