Sets (data structure) - Beau teaches JavaScript

preview_player
Показать описание
See how the set data structure can be implemented. Also learn about the es6 Set object.

Code:
More information:

⭐JavaScript Playlists⭐

-
We're busy people who learn to code, then practice by building projects for nonprofits. Learn Full-stack JavaScript, build a portfolio, and get great references with our open source community.

Рекомендации по теме
Комментарии
Автор

You could've just made an extended version of the ES6 Set.
The Set was implemented optimized looking to the peculiarities of the particular Data Structure.
It is much more performant when maintaining uniqueness and removing items.

Instead of your approach, we can make an ExtendedSet, using Set as the basis for our extra methods.

const union = function(otherSet) {
const _union = new Set(this)

for(const otherSetItem of otherSet) {
_union.add(otherSetItem)
}

return _union
}

const difference = function (otherSet) {
const _difference = new Set(this)

for (const otherItem of otherSet) {
_difference.delete(otherItem)
}

return _difference
}

const intersection = function (otherSet) {
const _intersection = new Set()

for (const item of this) {
if (otherSet.has(item)) {
_intersection.add(item)
}
}

return _intersection
}

const isSuperSet = function (otherSet) {
for (const otherItem of otherSet) {
if (!this.has(otherItem)) {
return false
}
}

return true
}

function bindExtensionMethods() {
this.union = union
this.difference = difference
this.intersection = intersection
this.isSuperSet = isSuperSet
}

function ExtendedSet(...args) {
const extendedSet = new Set(...args)

return extendedSet
}

const myExtendedSet = new ExtendedSet([1, 2, 3, 4, 5])

leonardodiehl
Автор

Your difference method is not full, because if you have two sets, for example: [1, 2, 3] and [1, 5], your method will return only [2, 3] but the full difference should be [2, 3, 5]. Am I right?

andriykuts
Автор

as others have pointed out it looks like the difference method is only half done. But otherwise great tutorial, thanks!

buncha
Автор

Very useful tut. Thank you!
Is there a reason that you are using var instead o const?
Also, I would have used a newer fat arrow syntax:
values1.forEach( (e) => {
unionSet.add(e);
});

MrRight
Автор

Thanks a lot for this! Not a biggy but you forgot to define index in line 25, it will fail silently in codepen if you try to switch to a ES6 Class

Adnoctumz
Автор

Why dont you use prototypes when adding functions (methods)??

quantum-t
Автор

I was expecting you would discuss some performance metrics. A big part of why sets are useful is their computational complexity

visintel
Автор

Why do we use "var collection = []" instead of "this.collection = []"?

tahasaleh
Автор

It seems that "mySet" would have serious performance issues.

yumingui