UNPKG

2.13 kBJavaScriptView Raw
1/*
2 * Licensed under the Apache License, Version 2.0 (the "License");
3 * you may not use this file except in compliance with the License.
4 * You may obtain a copy of the License at
5 *
6 * http://www.apache.org/licenses/LICENSE-2.0
7 *
8 * Unless required by applicable law or agreed to in writing, software
9 * distributed under the License is distributed on an "AS IS" BASIS,
10 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 * See the License for the specific language governing permissions and
12 * limitations under the License.
13 */
14'use strict';
15/**
16 * Manages a stack of objects
17 */
18
19class Stack {
20 /**
21 * Constructor
22 */
23 constructor() {
24 this.clear();
25 }
26 /**
27 * Clears the stack
28 */
29
30
31 clear() {
32 this.stack = [];
33 }
34 /**
35 * Returns the top of the stack or null if the stack is empty
36 * @return {*} the top of the stack
37 */
38
39
40 peek() {
41 if (this.stack.length === 0) {
42 return null;
43 }
44
45 return this.stack[this.stack.length - 1];
46 }
47 /**
48 * Pushes a new object to the top of the stack
49 * @param {*} obj the node to push
50 * @param {boolean} appendItem whether the item is also appended as a child to
51 * the item at the top of the stack
52 */
53
54
55 push(obj) {
56 let appendItem = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
57
58 if (appendItem) {
59 this.append(obj);
60 }
61
62 this.stack.push(obj);
63 }
64 /**
65 * Appends an object to the 'nodes' array of the item at the top of the stack
66 * @param {*} obj the item to append to the top node
67 */
68
69
70 append(obj) {
71 const top = this.peek();
72
73 if (top && top.nodes) {
74 top.nodes.push(obj);
75 } else {
76 throw new Error("Cannot append. Invalid stack: ".concat(JSON.stringify(this.stack, null, 4)));
77 }
78 }
79 /**
80 * Pops the top of the stack.
81 * @return {*} the top of the stack
82 */
83
84
85 pop() {
86 return this.stack.pop();
87 }
88 /**
89 * Adds a new text leaf node.
90 * @param {*} leaf the text node
91 */
92
93
94 addTextLeaf(leaf) {
95 this.append({
96 object: 'text',
97 text: leaf.text,
98 marks: leaf.marks
99 });
100 }
101
102}
103
104module.exports = Stack;
\No newline at end of file