Data structures and algorithms in JavaScript (2): queue

Source: Internet
Author: User

Data structures and algorithms in JavaScript (2): queue

This article mainly introduces the data structure and algorithm in JavaScript (2): queue is a linear table that allows only one end to be inserted and the other to be deleted, A queue is a First-In-First-Out (FIFO) data structure. For more information, see

A queue is a linear table that only allows insertion at one end and deletion. A queue is a data structure of First-In-First-Out (FIFO ).

The queue is frequently used in programming. Because javascript is a single thread, only one task can be executed in any time period, and asynchronous mechanisms are also involved,

The following problems occur:

1. When the asynchronous operation is executed, the synchronization code continues, so the synchronization code depends on Asynchronization, and errors will naturally occur.

2. Multiple synchronization tasks are called in different time periods

In jQuery animation, we often write a piece of 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 after the first animation ends, the opacity of the element changes to 0.25, the second animation is executed, the opacity of the element changes to 0.5, and so on. But in fact, an essential problem is designed here. animation is called asynchronously, And the animate method is executed synchronously. Therefore, we need to design it to the queue, jQuery also provides a queue method specifically designed for animation.

The queue is also a special 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, shift () you 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

43

44

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 = first;

This. end = end;

This. toString = toString;

This. empty = empty;

}

 

///////////////////////////

// The enqueue () method adds an element to the end of the team ://

///////////////////////////

Function enqueue (element ){

This. dataStore. push (element );

}

 

/////////////////////////

// Dequeue () method ://

/////////////////////////

Function dequeue (){

Return this. dataStore. shift ();

}

 

/////////////////////////

// You can use the following method to read the elements of the first and last teams ://

/////////////////////////

Function first (){

Return this. dataStore [0];

}

 

Function end (){

Return this. dataStore [this. dataStore. length-1];

}

 

/////////////////////////////

// The toString () method displays all elements in the queue //

/////////////////////////////

Function toString (){

Var retStr = "";

For (var I = 0; I <this. dataStore. length; ++ I ){

RetStr + = this. dataStore [I] + "\ n ";

}

Return retStr;

}

 

////////////////////////

// You need a method to determine whether the queue is empty //

////////////////////////

Function empty (){

If (this. dataStore. length = 0 ){

Return true;

} Else {

Return false;

}

}

 

Var q = new Queue ();

Q. enqueue ("python1 ");

Q. enqueue ("python2 ");

Q. enqueue ("python3 ");

 

Console. log ("queue header:" + q. first (); // ("on1 ");

Console. log ("queue tail:" + q. end (); // ("on3 ");

The queue uses linear storage, so there are some drawbacks of sequential storage, such as queuing for tickets. if the first one is purchased, the latter will naturally move forward to a blank space, in this way, every member of the entire queue needs to move forward, but the JavaScript queue is described in arrays, and the underlying layer solves some drawbacks. Of course, there are also search algorithm problems, such as using arrays to implement a single-chain table structure. Here we only discuss the javascript queue

Simulate jQuery and use queues for 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

43

44

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

84

85

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; text-align: center; 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 Queue

Var fireing = false // animation lock

Var first = true; // triggered through the add Interface

 

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

// Encapsulate the specific execution Algorithm

// Css3

// SetTimeout

Element. style. webkitTransitionDuration = '2000ms ';

Element. style. webkitTransform = 'translate3d ('+ width + 'px, 0, 0 )';

 

// Listen to the animation

Element. addEventListener ('webkittransitionend', function (){

Func ()

});

}

 

Var _ fire = function (){

// Adding an animation is being triggered

If (! Fireing ){

Var onceRun = Queue. shift ();

If (onceRun ){

Fireing = true;

// Next

OnceRun (function (){

Fireing = false;

_ Fire ();

});

} Else {

Fireing = true;

}

}

}

 

Return self = {

// Add a queue

Add: function (element, options ){

Queue. push (function (func ){

MakeAnim (element, options, func );

});

 

// If a queue triggers an animation immediately

If (first & Queue. length ){

First = false;

Self. fire ();

}

},

// Trigger

Fire: function (){

_ Fire ();

}

}

}();

 

 

AQuery. fn = aQuery. prototype = {

Run: function (options ){

Animation. add (this. element, options );

Return this;

}

}

 

Var init = aQuery. fn. init = function (selector ){

Var match = rquickExpr.exe c (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': '123'

}). Run ({

'Width': '123'

}). Run ({

'Width': '123'

});

};

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

43

44

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

84

85

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 Queue

Var fireing = false // animation lock

Var first = true; // triggered through the add Interface

 

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

// Encapsulate the specific execution Algorithm

// Css3

// SetTimeout

Element. style. webkitTransitionDuration = '2000ms ';

Element. style. webkitTransform = 'translate3d ('+ width + 'px, 0, 0 )';

 

// Listen to the animation

Element. addEventListener ('webkittransitionend', function (){

Func ()

});

}

 

Var _ fire = function (){

// Adding an animation is being triggered

If (! Fireing ){

Var onceRun = Queue. shift ();

If (onceRun ){

Fireing = true;

// Next

OnceRun (function (){

Fireing = false;

_ Fire ();

});

} Else {

Fireing = true;

}

}

}

 

Return self = {

// Add a queue

Add: function (element, options ){

Queue. push (function (func ){

MakeAnim (element, options, func );

});

 

// If a queue triggers an animation immediately

If (first & Queue. length ){

First = false;

Self. fire ();

}

},

// Trigger

Fire: function (){

_ Fire ();

}

}

}();

 

 

AQuery. fn = aQuery. prototype = {

Run: function (options ){

Animation. add (this. element, options );

Return this;

}

}

 

Var init = aQuery. fn. init = function (selector ){

Var match = rquickExpr.exe c (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': '123'

}). Run ({

'Width': '123'

}). Run ({

'Width': '123'

});

};

 

</Script>

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.