-
Notifications
You must be signed in to change notification settings - Fork 9
Open
Description
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"
Metadata
Metadata
Assignees
Labels
No labels