Mimicking sets in JavaScript?

前端 未结 7 2052
栀梦
栀梦 2020-11-22 13:01

I\'m working in JavaScript. I\'d like to store a list of unique, unordered string values, with the following properties:

  1. a fast way to ask \'is A in t
7条回答
  •  逝去的感伤
    2020-11-22 13:25

    I just noticed that d3.js library has implementation of sets, maps and other data structures. I can't argue about their efficiency but judging by the fact that it is a popular library it must be what you need.

    The documentation is here

    For convenience I copy from the link (the first 3 functions are those of interest)


    • d3.set([array])

    Constructs a new set. If array is specified, adds the given array of string values to the returned set.

    • set.has(value)

    Returns true if and only if this set has an entry for the specified value string.

    • set.add(value)

    Adds the specified value string to this set.

    • set.remove(value)

    If the set contains the specified value string, removes it and returns true. Otherwise, this method does nothing and returns false.

    • set.values()

    Returns an array of the string values in this set. The order of the returned values is arbitrary. Can be used as a convenient way of computing the unique values for a set of strings. For example:

    d3.set(["foo", "bar", "foo", "baz"]).values(); // "foo", "bar", "baz"

    • set.forEach(function)

    Calls the specified function for each value in this set, passing the value as an argument. The this context of the function is this set. Returns undefined. The iteration order is arbitrary.

    • set.empty()

    Returns true if and only if this set has zero values.

    • set.size()

    Returns the number of values in this set.

提交回复
热议问题