Skip to content

Use traits in an ES6 class? #1

Description

@hackel

I'm wondering how traits.js should be used in a class, in order to achieve the equivalent of:
class Range(from, to) extends Object uses Enumerable
In the example from the documentation, I am guessing something like this would work:

class EnumerableTrait
{
    constructor()
    {
        return Trait(EnumerableTrait);
    }

    each()
    {
        return Trait.required(); // should be provided by the composite
    }

    map(fun)
    {
        var r = [];
        this.each(function (e) {
            r.push(fun(e));
        });
        return r;
    }

    inject(init, accum)
    {
        var r = init;
        this.each(function (e) {
            r = accum(r, e);
        });
        return r;
    }
}

class Range
{
    constructor(from, to)
    {
        return Trait.create(
            Range,
            Trait.compose(
                EnumerableTrait,
                Trait({
                    each: function(fun) { for (var i = from; i < to; i++) { fun(i); } }
                }
            ))
        );
    }
}

Please let me know if I'm on the right track with this. Would love to use traits in my ES6 projects.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions