JavaScript data structure and algorithm collection (set) _ Basics

Source: Internet
Author: User
Tags new set hasownproperty

Collection (SET)

Talking about the collection, I remember just entered high school, the first lesson of mathematics is set. So when you learn to assemble this data structure, you feel more cordial.
The basic nature of a set is one: The elements in the collection are not duplicated. Because of this nature, we chose objects as containers for collections, not arrays.
Although arrays can do all without repetition, they are too cumbersome to assemble.

Operation of the collection

The basic operation of the set has intersection, set, difference set and so on. Here we introduce the implementation of the intersection, the set and the difference set in the Javascipt set.

The implementation of the set in Javascipt

First, create a constructor.

/**
 * Set constructor/function
Set method {
 /**
  * Container of the element of the collection, representing the
  * @type {object}
 */var Items = {};
}

The following methods are required for a collection:

    1. Has (value): Detects if there is an element in the collection
    2. Add (Value): Adds an element to the collection
    3. Remove (value): Remove an element from the collection
    4. Clear (value): Emptying the collection
    5. Size (): Returns the collection length
    6. VALUES (): Returns an array of collection conversions
    7. Union (Otherset): Returns the set of two sets
    8. Intersection (OTHERSET): Returns the intersection of two sets
    9. Difference (Otherset): Returns the difference set of two sets
    10. Subset (Otherset): Determines whether the collection is a subset of incoming collections

Has method:

Description: The elements in the collection are not duplicates. So before any other operation, you must use the has method to confirm that the collection has an element. Here the hasOwnProperty method is used to detect.
Realize:

/**
 * Detect if there is an element in
 the collection * @param {any} value  to detect the element
 * @return {Boolean}    If there is, return true
*/ The problem with This.has = function (value) {
 //hasOwnProperty is that
 //It is a method, so it is possible to write a return
 Items.hasownproperty ( Value)
};

Add Method:

Description: Adds an element to the collection.
Realize:

/**
 * Add an element to the collection *
 @param {Any} value to be added the element
 * @return {Boolean}    added successfully returns TRUE.
 */
This.add = function (value) {
 //to detect whether an element exists first.
 if (!this.has (value)) {
  Items[value] = value;
  return true;
 }
 Returns false return False if the element already exists;

Remove method:

Description: Remove an element from the collection
Realize:

/**
 * Remove an element in the collection *
 @param {Any} value to remove the element
 * @return {Boolean} to remove the    successful return true.
 */
This.remove = function (value) {
 //to detect whether an element exists first.
 if (This.has (value)) {
  delete items[value];
  return true;
 }
 If the element does not exist, the delete failure returns false return False
 ;

Clear method:
Description: Empty the collection
Realize:

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

Size method

Description: Returns the collection length, here are two methods. The first method uses the Object.keys API, but only supports IE9 and above. The second applies to all browsers.
Realize:

/**
 * Returns the set length and can only be used for IE9 and above
 * @return {number} set length
/this.size = function () {
 // The Object.keys method converts an object to an array
 //can only be used for IE9 and above, but is convenient for return
 Object.keys (items). length;

/**
 * Returns the collection length, available for all browser
 * @return {number} set
 length
/this.sizelegacy = function () {
 var count = 0;< C15/>for (var prop in items) {
  if (Items.hasownproperty (prop)) {
   ++count;
  }
 }
 return count;
}

Values method

Description: Returns an array of collection conversions, and there are two ways to do this. The reason is ditto. The use of Object.keys can only support IE9 and above.
Realize:

/**
 * Returns an array of collection conversions, available only for IE9 and above
 * @return {array} converted Arrays *
 /
this.values = function () {
 return Object.keys (items);

/**
 * Returns an array of collection conversions that can be used for all browser
 * @return {array} converted
 Arrays
/this.valueslegacy = function () {
 var Keys = [];
 for (var key in items) {
  Keys.push (key)
 };
 return keys;
};

Union method

Description: Returns the set of two sets
Realize:

/**
 * Returns the set of two sets *
 @param {Set} Otherset the set of the collection
 * @return {Set} two sets/
this.union = function (otherset) {
 //Initializes a new collection that is used to represent the set.
 var unionset = new Set ();
 Converts the current collection to an array, and then adds the Unionset
 var values = this.values ();
 for (var i = 0; i < values.length i++) {
  unionset.add (values[i]);

 Converts the other collection into an array, which is added to the unionset in turn.
 //The Add method in the loop guarantees that there will be no duplicate elements appearing
 values = Otherset.values ();
 for (var i = 0; i < values.length i++) {
  unionset.add (values[i]);

 return unionset;
};

Intersection method

Description: Returns the intersection of two sets
Realize:

/**
 * Returns the intersection of two sets *
 @param {set} otherset the
 intersection
of Set * @return {set} two sets for intersection action * * * This.intersection = function (otherset) {
 //Initializes a new collection that represents the intersection.
 var intersectionset = new Set ();
 Converts the current collection to an array of
 var values = this.values ();
 Iterates through the array, and if another collection has that element, Intersectionset adds the element. For
 (var i = 0; i < values.length i++) {

  if (Otherset.has (values[i))) {
   Intersectionset.add (values[i) )
  }
 return

 intersectionset;


Difference method

Description: Returns the difference set of two sets
Realize:

/**
 * Returns the difference set of two sets
 * @param {set} Otherset the set of the difference set
 * @return {set}     two
sets/this.difference = function (otherset) {
 //Initialize a new collection to represent the difference set.
 var differenceset = new Set ();
 Converts the current collection to an array of
 var values = this.values ();
 Iterates through the array, and if another collection does not have that element, Differenceset adds the element. For
 (var i = 0; i < values.length i++) {

  if (!otherset.has (values[i))) {
   differenceset.add (values[i))
  }
 }

 return differenceset;
};

Subset method

Description: Determines whether the collection is a subset of the incoming collection. This piece of code after I wrote the book with a pair of books, I feel super low. I write to enumerate the group three times, the book only need once, the algorithm complexity is far lower than mine.
Realize:

/**
 * Determines whether the collection is a subset of the incoming collection
 * @param {set} Otherset incoming Collection
 * @return {Boolean}   is return True
* * This.subset = function (otherset) {
 //The first decision, if the set length is greater than the length of Otherset,
 returns False if
 (This.size () > Otherset.size ()) {
  return false;
 } else {
  //convert the current collection to an array of
  var values = this.values ();

  for (var i = 0; i < values.length i++) {

   if (!otherset.has (values[i)) {
    //second decision. As long as one element is not in Otherset
    //Then you can directly determine that it is not a subset, return false to False
    ;
   }

  return true;
 }
;

The collection in the ES6

ES6 also provides a collection, but the previous ES6 set operation has been blurred. Realize it again and then go to see, feel a lot clearer concept.
The specific I master is not very good, still in the study, do not write out ~ recommended to see Nanyi Teacher's "ECMAScript 6" in the introduction of the ES6 set.
"ECMAScript 6" –set and map data structures

Feelings

Here, we have mastered some basic data structures. The rest is hard to chew (for me).

The hash table, graph, tree and sorting algorithm of the dictionary. Is the four Great Kong, so the recent article on data structure and algorithm series, may be updated very slowly. For me, it's a hurdle. Hope this winter vacation, can cross this ridge.

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.