DEV Community

Cover image for JS Sets: The Missing Methods
Jon Randy ๐ŸŽ–๏ธ
Jon Randy ๐ŸŽ–๏ธ

Posted on

JS Sets: The Missing Methods

So, whilst Sets were a great addition to JavaScript, there did seem to be some glaring omissions. The most obvious of these were the basic set operations: union, intersection, and difference.

We can easily add these with Metho:

import * as metho from "metho"

const target = Set.prototype

export const union = Metho.add(
  target,
  function(set) {
    return new Set([...this, ...set])
  }
)

export const intersect = Metho.add(
  target,
  function(set) {
    return new Set([...this].filter(i=>set.has(i)))
  }
)

export const difference = Metho.add(
  target,
  function(set) {
    return new Set([...this].filter(i=>!set.has(i)))
  }
)

const a = new Set([1, 2, 3])
const b = new Set([3, 4, 5])

// everything from both sets
console.log( a[union(b)] )       // Set(5)[ 1, 2, 3, 4, 5 ]

// everything that exists in both set a and set b
console.log( a[intersect(b)] )   // Set [ 3 ]

// everything that exists in set a, but not in set b
console.log( a[difference(b)] )  // Set [ 1, 2 ]


Enter fullscreen mode Exit fullscreen mode

I have made these extensions available in the metho-set library

GitHub logo jonrandy / metho

A new method for methods

GitHub logo jonrandy / metho-set

Set prototype extensions

Top comments (0)