Jared's answer is concise, but if the sets to compare were reasonably large, it is not an efficient algorithm.
Consider this short-circuiting program -
const isSubsetOf = (super, sub) => {
for (const s of sub)
if (!super.has(s))
return false
return true
}
In another Q&A, How to map/reduce/filter a Set in JavaScript?, we explore how to add functional methods to the Set.prototype
. One in particular that would be useful to us, is Set.prototype.every
-
Set.prototype.every = function every(f) {
for (const v of this) if (!f(v)) return false
return true
}
This would allow you to rewrite your program as -
const isSubsetOf = (super, sub) =>
sub.every(s => super.has(s))
Modifying native prototypes is not recommended if you're writing shared software like a library, framework, or tool. However if this is your program and you don't expect it to become a dependency in someone else's project, there is nothing wrong with modifying any prototype (native or otherwise) to suit your needs.
If you cannot modify Set.prototype
, a functional API is still possible -
const setEvery = (set, f) => {
for (const v of this) if (!f(v)) return false
return true
}
const isSubsetOf = (super, sub) =>
setEvery(sub, s => super.has(s))