6

I know that JavaScript now has sets, but I wonder if there is something to realize the function of multiSet, or if there is some framework that has the functions of multiset which I really need a lot.

Or I have to code it by myself to do the research of Red-Black Tree?

Francisco
  • 10,918
  • 6
  • 34
  • 45
hanzichi
  • 609
  • 2
  • 12
  • 22

3 Answers3

3

There are no built-in multiset structure, but there are some libraries that have such:

Feel free to add your favorite library in this question.

diralik
  • 6,391
  • 3
  • 28
  • 52
2

You can build your own multiset using the Builtin map type and numerical values:

class Multiset {
    _backing = new Map();
    add(value) {
        if (this._backing.has(value)) {
            this._backing.set(value, 1 + this._backing.get(value));
        } else {
            this._backing.set(value, 1);
        }
    }

    delete(value) {
        if (this._backing.get(value) > 0) {
            this._backing.set(value, this._backing.get(value) - 1);
        } else {
            //do nothing
        }
    }

    get(value) {
        if (this._backing.get(value) > 0) {
            return this._backing.get(value);
        } else {
            return 0;
        }
    }
}
1

This is an old question, but it came in at the top of my search. I've ended up using lodash (similar to underscore): For example,

_.countBy([1, 2, 1, 4, 4, 1])

gives the result

{ '1': 3, '2': 1, '4': 2 }
whistling_marmot
  • 3,561
  • 3
  • 25
  • 39