We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
My suggestion for protocols
// polyfill const protocol = (name: string, ...methods: string[]) => (() => { const symbols = Object.fromEntries(methods.map(key => [key, Symbol(`${name}.${key}`)])) return Object.assign( (Class: any, impl: Record<string, Function>) => { for (const [key, val] of Object.entries(impl)) { Class.prototype[symbols[key]] = val } }, symbols ) })() /* const Functor = protocol { fmap } OR protocol Functor { fmap } */ const Functor = protocol("Functor", "fmap") /* String implements Functor { fmap: function(f) { return [...this].map(x => f(x)).join("") } } OR implement Functor for String { fmap: function(f) { return [...this].map(x => f(x)).join("") } } */ Functor(String, { fmap: function (f: (s: string) => string) { return [...this].map(x => f(x)).join("") } }) console.log("Hello World"[Functor.fmap]((x: string) => x.toUpperCase()) // "HELLO WORLD"
The text was updated successfully, but these errors were encountered:
Although, I would want to go more functional (like Clojure):
const getTag = (x: any): string => { const t = typeof x if (t === "function") { return x.name } if (t !== "object") { return t } if (x === null) { return "null" } return x.constructor.name } const protocol = (...fns: string[]) => { const reg: Record<string, Record<string, Function>> = {} return fns.reduce((r, fn) => { r[fn] = (x: any, ...rest: any[]) => reg[getTag(x)][fn](x, ...rest) return r }, (x: any, impl: Record<string, Function>) => { reg[getTag(x)] = impl }) } /* const Functor = protocol { fmap } */ const Functor = protocol("fmap") /* implement null for Functor { fmap: (m, f) => null } */ Functor(null, { fmap: (m, f) => null }) /* implement Array for Functor { fmap: (m, f) => m.map(x => f(x)) } */ Functor(Array, { fmap: (m, f) => m.map(x => f(x)) }) const sq = (x: number) => x * x console.log(Functor.fmap(null, sq), Functor.fmap([2, 3, 5], sq)) // null, [4, 9, 25]
Arguably, this doesn't require new syntax.
Sorry, something went wrong.
No branches or pull requests
My suggestion for protocols
The text was updated successfully, but these errors were encountered: