Skip to content

Use traits in an ES6 class? #1

Open
@hackel

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.

Metadata

Metadata

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions