Last active
March 6, 2018 22:15
-
-
Save inodaf/98569245fddaf8d1689d87418fc1b4de to your computer and use it in GitHub Desktop.
Simple way to define your functional modules. Just for study purposes.
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
(function simpleFp() { | |
const Utils = { | |
getFunctionArity(fn) { | |
return fn.length | |
}, | |
getFunctionModule(fnName, fnArity) { | |
const fnPath = fnName.split('.') | |
const isOuter = fnPath.length > 1 | |
if (isOuter) { | |
const module = fnPath[0] | |
const name = Utils.getFunctionName(fnPath[1], fnArity) | |
return { isOuter, module, name } | |
} else { | |
const name = Utils.getFunctionName(fnPath[0], fnArity) | |
return { name } | |
} | |
}, | |
getFunctionName(name, arity) { | |
return `${name}/${arity}` | |
}, | |
setRootStore() { | |
window.__module_store__ = {} | |
}, | |
getRootStore() { | |
return window.__module_store__ | |
} | |
} | |
Utils.setRootStore() | |
window.defmodule = (moduleName, module) => { | |
const methods = { | |
def(name, fn) { | |
const rootStore = Utils.getRootStore() | |
const fnArity = Utils.getFunctionArity(fn) | |
const fnName = Utils.getFunctionName(name, fnArity) | |
return rootStore[moduleName] = { | |
...rootStore[moduleName], | |
[fnName]: fn | |
} | |
}, | |
run(nameExp, ...args) { | |
const fnArity = Utils.getFunctionArity(args) | |
const nextCall = Utils.getFunctionModule(nameExp, fnArity) | |
const rootStore = Utils.getRootStore() | |
if (nextCall.isOuter) { | |
return rootStore[nextCall.module][nextCall.name].apply(null, args) | |
} else { | |
return rootStore[moduleName][nextCall.name].apply(null, args) | |
} | |
}, | |
callback(name, fn) { | |
const rootStore = Utils.getRootStore() | |
rootStore[moduleName].callbacks[name] = fn | |
}, | |
init() { | |
const rootStore = Utils.getRootStore() | |
rootStore[moduleName] = { callbacks: null } | |
rootStore[moduleName].callbacks = { | |
start: function () { } | |
} | |
return window.setTimeout(() => rootStore[moduleName].callbacks.start(), 1) | |
} | |
} | |
methods.init() | |
return module({ | |
def: methods.def, | |
run: methods.run, | |
callback: methods.callback | |
}) | |
} | |
}()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: