-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathStack.js
More file actions
77 lines (64 loc) · 1.74 KB
/
Stack.js
File metadata and controls
77 lines (64 loc) · 1.74 KB
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
/*
* STACK.JS (MODULE)
*
* Version: 1.0.0
* Author: VideoPlayerCode
* URL: https://github.com/VideoPlayerCode/mpv-tools
* License: Apache License, Version 2.0
*/
/* jshint -W097 */
/* global mp, module, require, setInterval, clearInterval, setTimeout, clearTimeout */
'use strict';
var Utils = require('MicroUtils');
var Stack = function(maxSize)
{
if (!Utils.isInt(maxSize) || maxSize === 0)
throw 'Max stack size must be either -1 (unlimited), or 1 or higher';
this.stack = [];
this.position = -1;
this.maxSize = maxSize;
};
Stack.prototype.push = function(elem)
{
// Add to end of stack.
this.stack.push(elem);
if (this.maxSize !== -1)
while (this.stack.length > this.maxSize) // Normally only triggers once.
this.stack.shift(); // Remove 1st and reindex.
this.position = this.stack.length - 1;
};
Stack.prototype.pop = function()
{
// Pop from end of stack.
if (this.position < 0)
return undefined; // Stack is empty.
var popped = this.stack.pop();
this.position = this.stack.length - 1;
return popped;
};
Stack.prototype.clearStack = function()
{
// NOTE: We use splice rather than `= []` to ensure old references retrieved
// via `getStack()` will still point to the active stack after clearing it.
this.stack.splice(0, this.stack.length);
this.position = -1;
};
Stack.prototype.getStack = function()
{
return this.stack;
};
Stack.prototype.getLast = function()
{
return this.position >= 0 ?
this.stack[this.position] :
undefined;
};
Stack.prototype.getCount = function()
{
return this.position + 1;
};
Stack.prototype.isEmpty = function()
{
return this.position < 0;
};
module.exports = Stack;