VehiclesFashionRecipesBlogsHuntTravelsSportFunHandmadeITEducation
Mini-Games
x

x
zakruti.com » IT - Software » freeCodeCamp.org
Sets (data structure) - Beau teaches JavaScript

Sets (data structure) - Beau teaches JavaScript

FBTwitterReddit

video description

Rating: 4.0; Vote: 1
See how the set data structure can be implemented. Also learn about the es6 Set object. Code: - http://codepen.io/beaucarnes/pen/dvGeeq?editors=0012 More information: - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set Beau Carnes on
Date: 2022-03-14

Comments and reviews: 6


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)
bindExtensionMethods.call(extendedSet)
return extendedSet
-
const myExtendedSet = new ExtendedSet([1, 2, 3, 4, 5])

reply

this.difference(otherSet)-
let differenceSet = new mySet();
let firstSet = this;
let secondSet = otherSet;
firstSet.values().forEach((e) => -
if(!secondSet.has(e))-
differenceSet.add(e);
firstSet.remove(e);
secondSet.remove(e);
-;
-);
secondSet.values().forEach((e) => -
!firstSet.has(e) && differenceSet.add(e);
-);
return differenceSet;
-;

reply

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);-
-);

reply

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?
reply

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
reply

I was expecting you would discuss some performance metrics. A big part of why sets are useful is their computational complexity
reply
Add a review, comment






Other channel videos