Skip to content

Simplifying syntax and implementation #41

@rodinhart

Description

@rodinhart

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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions