Set of JavaScript data structures and algorithms _ basic knowledge

Source: Internet
Author: User
Tags hasownproperty
The JavaScript set can store values and objects using the Set object Map, set, and WeakMap. With these objects, you can use keys or values instead of indexes to easily add and retrieve members. Set)

When talking about collections, I think that when I first got into high school, the first class of mathematics was about collections. Therefore, I feel more cordial when learning the data structure of collection.
There is one basic property of a set: Elements in the set are not repeated. Because of this nature, we use an object as a collection container instead of an array.
Although the array can do everything without repetition, it is too cumbersome and not as good as a set.

Set Operations

The basic operations of a set include intersection, union, and difference. Here we will introduce the implementation of intersection, union, and difference sets in the JavaScipt set.

Implementation of JavaScipt Integration

First, create a constructor.

/*** Constructor of the Set */function Set method {/*** container of the collection element, use an Object to represent * @ type {Object} */var items = {};}

The following methods are required for a set:

  1. Has (value): checks whether an element exists in the set.
  2. Add (value): add an element to the set.
  3. Remove (value): removes an element from a collection.
  4. Clear (value): clears the set.
  5. Size (): returns the length of the set.
  6. Values (): returns the array converted from the set.
  7. Union (otherSet): returns the union of two sets.
  8. Intersection (otherSet): returns the intersection of two sets.
  9. Difference (otherSet): returns the difference set of the two sets.
  10. Subset (otherSet): determines whether the set is a subset of the input set.

Has method:

Note: Elements in the set are unique. Therefore, before any other operation, you must use the has method to check whether the set has an element. The hasOwnProperty method is used for detection.
Implementation:

/*** Check whether an element exists in the Set * @ param {Any} value indicates the element to be detected * @ return {Boolean}. If yes, true */this is returned. has = function (value) {// The problem with hasOwnProperty is that // It is a method, so it may be overwritten with return items. hasOwnProperty (value )};

Add method:

Note: add an element to the set.
Implementation:

/*** Add an element to the Set * @ param {Any} value the element to be added * @ return {Boolean} returns True if it is successfully added. */This. add = function (value) {// first checks whether the element exists. If (! This. has (value) {items [value] = value; return true ;}// if the element already exists, false return false ;};

Remove Method:

Removes an element from a collection.
Implementation:

/*** Remove an element from the set * @ param {Any} value the element to be removed * @ return {Boolean} returns True if it is removed successfully. */This. remove = function (value) {// first checks whether the element exists. If (this. has (value) {delete items [value]; return true ;}// if the element does not exist, false return false if deletion fails ;};

Clear method:
Description: clears a set.
Implementation:

/*** Clear the set */this. clear = function () {this. items = {};};

Size Method

Description: return the length of the set. There are two methods. The first method uses the Object. keys Api, but only supports IE9 and later. The second method applies to all browsers.
Implementation:

/*** Return the length of the Set, which can only be used for IE9 and later * @ return {Number} set length */this. size = function () {// Object. the keys method can convert an Object into an array. // it can only be used for IE9 and later, but it is convenient to return an Object. keys (items ). length;}/*** return length of the Set, which can be used in all browsers * @ return {Number} set length */this. sizeLegacy = function () {var count = 0; for (var prop in items) {if (items. hasOwnProperty (prop) {++ count ;}} return count ;}

Values Method

Note: return the array converted from the set. There are two methods here. The reason is the same as above. If Object. keys is used, only IE9 and later are supported.
Implementation:

/*** Returns the Array converted by the set. It can only be used for the Array converted by IE9 or later * @ return {Array} */this. values = function () {return Object. keys (items) ;};/*** returns the Array converted from the set, which can be used by all browsers * @ return {Array} to the converted Array */this. valuesLegacy = function () {var keys = []; for (var key in items) {keys. push (key)}; return keys ;};

Union Method

Returns the union of two sets.
Implementation:

/*** Returns the union of the two sets * @ param {Set} otherSet the union of the two sets * @ return {Set} */this. union = function (otherSet) {// initializes a new set to indicate the union. Var unionSet = new Set (); // convert the current Set to an array and add it to unionSet var values = this. values (); for (var I = 0; I <values. length; I ++) {unionSet. add (values [I]);} // convert other sets into arrays and add them to unionSet in sequence. // The add method in the loop ensures that there are no repeated elements. values = otherSet. values (); for (var I = 0; I <values. length; I ++) {unionSet. add (values [I]);} return unionSet ;};

Intersection method

Returns the intersection of two sets.
Implementation:

/*** Returns the intersection of two sets * @ param {Set} otherSet the intersection of the two sets * @ return {Set} to perform the intersection operation */this. intersection = function (otherSet) {// initialize a new set to indicate the intersection. Var interSectionSet = new Set (); // converts the current Set to an array var values = this. values (); // traverses the array. If another set also has this element, interSectionSet adds this element. For (var I = 0; I <values. length; I ++) {if (otherSet. has (values [I]) {interSectionSet. add (values [I])} return interSectionSet ;};

Difference Method

Returns the difference set of two sets.
Implementation:

/*** Return the difference Set of the Two sets * @ param {Set} otherSet the Set to be operated on by the difference Set * @ return {Set} The difference Set of the Two sets */this. difference = function (otherSet) {// initialize a new set to indicate the difference set. Var differenceSet = new Set (); // convert the current Set to an array var values = this. values (); // traverses the array. If another set does not have this element, differenceSet adds this element. For (var I = 0; I <values. length; I ++) {if (! OtherSet. has (values [I]) {differenceSet. add (values [I]) }}return differenceSet ;};

Subset method

Determines whether the set is a subset of the input set. After writing this code, I compared it with the book and thought I was super low. I wrote three times to traverse the array. The book only needs one time, and the algorithm complexity is far lower than mine.
Implementation:

/*** Determine whether the Set is a subset of the incoming Set * @ param {Set} The Set passed in by otherSet * @ return {Boolean} returns True */this. subset = function (otherSet) {// The first criterion. if the length of the set is greater than the length of the otherSet, the system returns false if (this. size ()> otherSet. size () {return false;} else {// converts the current set to an array var values = this. values (); for (var I = 0; I <values. length; I ++) {if (! OtherSet. has (values [I]) {// second decision. If an element is not in the otherSet, you can directly determine that it is not a subset and return false;} return true ;}};

Set in ES6

ES6 also provides collections, but the collection operations of ES6 have been confused. After implementation, I can see it again, and the concept is much clearer.
I am not very familiar with the specifics. I am still learning, so I won't write it out ~ We recommend that you read the introduction of ES6 Set in ECMAScript 6.
ECMAScript 6-Set and Map data structures

Feelings

At this point, we have mastered some basic data structures. The rest are tough bones (for me ).

Dictionary hash, graphs, trees, and sorting algorithms. It is regarded as the four major Kings, so recent articles on data structures and algorithms may be updated slowly. It is also a hurdle for me. I hope this winter vacation can be crossed.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.