Data structures and algorithms in JavaScript (ii): Queues

Source: Internet
Author: User
Tags arrays data structures tostring wrapper

This article mainly introduces the data structure and algorithm in JavaScript (ii): Queues, queues are only allowed at one end of the insert operation, another to delete operations of the linear table, the queue is an advanced first out (FIRST-IN-FIRST-OUT,FIFO) data structure, Need friends can refer to the following

A queue is a linear table that allows insertions only at one end and another for deletion operations, and queues are a first-in, first-out (FIRST-IN-FIRST-OUT,FIFO) data structure

Queues are used very frequently in program programming because JavaScript is single-threaded, causing any one time period to perform only one task, and a mixed asynchronous mechanism

The problem that comes with that:

1. When the asynchronous operation executes, the synchronization code continues, then the synchronization code relies on asynchrony and naturally goes wrong

2. Multiple synchronization tasks are called at different time periods

In the jquery animation, we often write a continuous animation code

?

1 2 3 4 5 6 7 $book. Animate ({opacity:0.25,}). Animate ({opacity:0.5}). Animate ({opacity:1})

The intuitive feeling is that the opacity of the element becomes 0.25 after the first animate ends, and then the second animate begins, the opacity of the element becomes 0.5, and so on. But in fact, there's an essential problem here, the animation is called asynchronously, the Animate method is synchronized, so it needs to be designed to be queued, and jquery also gives a design-specific queue method for animation.

Queues are also a special kind of linear table, in JavaScript we can directly use arrays to implement such a design, the array push () method can add elements at the end of the array, the shift () method can delete the first element of the array.

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26-27--28 29---30 31--32 33 34 35 36 37 38-39 40 41 42 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63-64 function Queue () {this.datastore = []; this.enqueue = enqueue; this.dequeue = dequeue; this.first = i; this.end = en D this.tostring = toString; This.empty = empty; }  /////////////////////////////Enqueue () adds an element to the tail of the team://///////////////////////////function Enqueue (Element) {This.dataStore.push (element);}  ///////////////////////////dequeue () Delete elements from Team head:///////////////////////////function dequeue () {return This.dataStore.shift (); }  ///////////////////////////You can read the elements of the team head and the end of the team using the following methods:///////////////////////////function first () {return this.dat ASTORE[0]; }   function End () {return this.datastore[this.datastore.length-1];}  ///////////////////////////////ToSt The ring () method displays all elements within the queue///////////////////////////////function toString () {var retstr = ""; for (var i = 0; i < this.dataStore.length ++i) {retstr + = This.datastore[i] + "n";} return retstr; }  //////////////////////////requires a method to determine whether the queue is empty//////////////////////////functionEmpty () {if (this.dataStore.length = = 0) {return is true;} else {return false;}}   var q = new Queue (); Q.enqueue ("Aaron1"); Q.enqueue ("Aaron2"); Q.enqueue ("Aaron3");   Console.log ("Queue head:" + Q.first ()); ("Aaron1"); Console.log ("Tail of queue:" + q.end ()); ("Aaron3");

The queues are based on linear storage, then there are some of the drawbacks of sequential storage, such as queuing to buy tickets, if the first bought, the back will naturally move forward a vacancy, so that the entire queue of each member to move forward, but the JavaScript queue is described by the array, The bottom has solved some drawbacks. Of course, there are problems in the search algorithm, such as the use of arrays to implement a single linked list structure, and so on, we only discuss the JavaScript queue

Simulate jquery, using queues to implement an animation

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26-27--28 29---30 31--32 33 34 35 36 37 38-39 40 41 42 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 5 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111-112 <div id= "Div1" style= width:100px;height:50px;background:red;cursor:pointer;color: #fff; line-height:50px; " > Click </div>   (function ($) {  window.$ = $;  }) (function () {  var rquickexpr =/^ (?: #) ([w-]*) )$/;   function Aquery (selector) {return new AQuery.fn.init (selector);}  /** * animation * @return {[type]} [description] */var animation = function () {var self = {}; var queue = [];//animation queues var fireing = false//anime lock var-a = true;//via Add interface triggers   var getstyle = function (obj, attr) {return obj.currentstyle? Obj.currentstyle[attr]: getComputedStyle (obj, FALSE) [attr]; }   var makeanim = function (element, options, func) {var width = options.width//wrapper specific execution algorithm//CSS3//settimeout elem ent.style.webkitTransitionDuration = ' 2000ms '; Element.style.webkitTransform = ' Translate3d (' + width + ' px,0,0 ');  //Monitoring animation completion Element.addeventlistener (' Webkittransitionend ', function () {func ()}); }   var _fire = function () {//Add animation positiveIn the trigger if (!fireing) {var oncerun = Queue.shift (); if (oncerun) {fireing = true;//next Oncerun (function () {fireing = Fals E _fire (); }); else {fireing = true;}} }   Return self = {//Add queue add:function (element, options) {Queue.push (function (func) {Makeanim (element, options, F UNC); });  //If there is a queue that immediately triggers an animation if (A/I && queue.length) {i = false; Self.fire ();}},///Trigger Fire:function () {_fire (); } } }();     Aquery.fn = Aquery.prototype = {run:function (options) {Animation.add (this.element, Options); }   var init = AQuery.fn.init = function (selector) {var match = rquickexpr.exec (selector); var element = document . getElementById (match[1]) this.element = element; return this; }   Init.prototype = Aquery.fn;   return aquery; }());  //dom var odiv = document.getElementById (' Div1 ');  //Call Odiv.onclick = function () {$ (' #div1 '). Run ({' width ': ') '. Run ({' width ': ' 1000 '}) ); };

Test

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26-27--28 29---30 31--32 33 34 35 36 37 38-39 40 41 42 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 5 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114-115 <!doctype html><div id= "Div1 style=" Width:100px;height:50px;background:red;cursor:pointer;color: #fff; text-align:center;line-height:50px; "Data-mce-style=" width:100px; height:50px; background:red; Cursor:pointer; Color: #fff; Text-align:center; line-height:50px; " > Click </div><script type= "Text/javascript" >   (function ($) {  window.$ = $;  }) (function () {   var rquickexpr =/^ (?: # ([w-]*)) $/;   function Aquery (selector) {return new AQuery.fn.init (selector);}  /** * animation * @return {[type]} [description] */var animation = function () {var self = {}; var queue = [];//animation queues var fireing = false//anime lock var-a = true;//via Add interface triggers   var getstyle = function (obj, attr) {return obj.currentstyle? Obj.currentstyle[attr]: getComputedStyle (obj, FALSE) [attr]; }   var makeanim = function (element, options, func) {var width = options.width//wrapper specific execution algorithm//CSS3//settimeout elem ent.style.webkitTransitionDuration = ' 2000ms '; Element.Style.webkittransform = ' Translate3d (' + width + ' px,0,0 ');  //Monitoring animation completion Element.addeventlistener (' Webkittransitionend ', function () {func ()}); }   var _fire = function () {//Join animation is triggering if (!fireing) {var oncerun = Queue.shift (); if (oncerun) {fireing = true; /next Oncerun (function () {fireing = false; _fire ();}); else {fireing = true;}} }   Return self = {//Add queue add:function (element, options) {Queue.push (function (func) {Makeanim (element, options, F UNC); });  //If there is a queue that immediately triggers an animation if (A/I && queue.length) {i = false; Self.fire ();}},///Trigger Fire:function () {_fire (); } } }();     Aquery.fn = Aquery.prototype = {run:function (options) {Animation.add (this.element, Options); }   var init = AQuery.fn.init = function (selector) {var match = rquickexpr.exec (selector); var element = document . getElementById (match[1]) this.element = element; return this; }   Init.prototype = Aquery.fn;   return aquery; }());    //dom var odiv = document.getElementById (' Div1 ');  //Call Odiv.onclick = function () {$ (' #div1 '). Run ({' width ': ') '. Run ({' width ': ' 1000 '}) ); };   </script>

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.