Coverage

100%
46
46
0

queue.js

100%
46
46
0
LineHitsSource
1/* vim: set expandtab tabstop=2 shiftwidth=2 foldmethod=marker: */
2
31"use strict";
4
51var util = require('util');
61var Emitter = require('events').EventEmitter;
7
81exports.create = function (options) {
9
102 var _options = {
11 'timeout' : 0,
12 'maxitem' : -1,
13 };
142 for (var i in options) {
154 _options[i] = options[i];
16 }
17
18 /**
19 * @序列
20 */
212 var _sequence = [];
22
23 /* {{{ private function build() */
24 /**
25 * To build a timeout item into _sequence
26 */
272 var build = function (item, tmout, _self) {
2810 var tmout = ~~(tmout || _options.timeout);
2910 var _item = [item, 0];
3010 if (tmout) {
318 _item[1] = setTimeout(function () {
322 var i = _sequence.indexOf(_item);
332 if (i > -1) {
342 _sequence.splice(i, 1);
352 _self.emit('timeout', item, tmout, i);
36 }
37 }, tmout);
38 }
3910 return _item;
40 };
41 /* }}} */
42
43 /* {{{ private function parse() */
44 /**
45 * To parse and return a build-in item
46 *
47 * @ access private
48 * @ param {Array} item
49 * @ return {Object} or undefined
50 */
512 var parse = function (item) {
524 if (item && Array.isArray(item)) {
533 clearTimeout(item[1]);
543 item = item[0];
55 }
56
574 return item;
58 };
59 /* }}} */
60
612 var Queue = function () {
622 Emitter.call(this);
63 };
642 util.inherits(Queue, Emitter);
65
66 /* {{{ public prototype push() */
67 /**
68 * Push an item into sequence
69 *
70 * @ access public
71 * @ param {Object} item
72 * @ param {Integer} tmout
73 * @ return {Number} length of the sequence
74 */
752 Queue.prototype.push = function (item, tmout) {
7611 if (_options.maxitem > 0 && _sequence.length >= _options.maxitem) {
771 this.emit('full', _sequence.length, _options.maxitem);
781 return -1;
79 }
80
8110 var n = _sequence.push(build(item, tmout, this));
8210 if (1 === n) {
833 this.emit('fill');
84 }
85
8610 return n;
87 };
88 /* }}} */
89
90 /* {{{ public prototype shift() */
91 /**
92 * shift an item from the sequence
93 *
94 * @ access public
95 * @ return {Object} item or undefined
96 */
972 Queue.prototype.shift = function () {
983 return parse(_sequence.shift());
99 };
100 /* }}} */
101
102 /* {{{ public prototype pop() */
103 /**
104 * Pop up an item from the sequence
105 */
1062 Queue.prototype.pop = function () {
1071 return parse(_sequence.pop());
108 };
109 /* }}} */
110
111 /* {{{ public prototype size() */
1122 Queue.prototype.size = function () {
1137 return _sequence.length;
114 };
115 /* }}} */
116
117 /* {{{ public prototype clean() */
118 /**
119 * Clean the sequence up
120 */
1212 Queue.prototype.clean = function () {
1221 _sequence.forEach(function (item) {
1235 if (item[1]) {
1245 clearTimeout(item[1]);
125 }
126 });
1271 _sequence = [];
128 };
129 /* }}} */
130
1312 return new Queue();
132};