UNPKG

2.88 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
15'use strict';
16
17const Util = require('../util');
18
19/**
20 * Tracks a stack of typed instances. The type information is used to detect
21 * overflow / underflow bugs by the caller. It also performs basic sanity
22 * checking on push/pop to make detecting bugs easier.
23 * @private
24 * @class
25 * @memberof module:concerto-core
26 */
27class TypedStack {
28
29 /**
30 * Create the Stack with the resource at the head.
31 * @param {Object} resource - the resource to be put at the head of the stack
32 */
33 constructor(resource) {
34 this.stack = [];
35 this.push(resource);
36 }
37
38 /**
39 * Push a new object.
40 * @param {Object} obj - the object being visited
41 * @param {Object} expectedType - the expected type of the object being pushed
42 */
43 push(obj, expectedType) {
44 if(expectedType && !(obj instanceof expectedType)) {
45 throw new Error('Did not find expected type ' + expectedType.constructor.name + ' as argument to push. Found: ' + obj.toString());
46 }
47
48 if(Util.isNull(obj)) {
49 throw new Error('Pushing null data!');
50 }
51
52 this.stack.push(obj);
53 //console.log('Push depth is: ' + this.stack.length + ', contents: ' + this.stack.toString() );
54 }
55
56 /**
57 * Push a new object.
58 * @param {Object} expectedType - the type that should be the result of pop
59 * @return {Object} the result of pop
60 */
61 pop(expectedType) {
62 this.peek(expectedType);
63 return this.stack.pop();
64 }
65
66 /**
67 * Peek the top of the stack
68 * @param {Object} expectedType - the type that should be the result of pop
69 * @return {Object} the result of peek
70 */
71 peek(expectedType) {
72
73 //console.log( 'pop ' );
74
75 if(this.stack.length < 1) {
76 throw new Error('Stack is empty!');
77 }
78
79 const result = this.stack[this.stack.length-1];
80 if(expectedType && !(result instanceof expectedType)) {
81 throw new Error('Did not find expected type ' + expectedType + ' on head of stack. Found: ' + result);
82 }
83
84 if(Util.isNull(result)) {
85 throw new Error('Pop returned invalid data');
86 }
87
88 return result;
89 }
90
91 /**
92 * Clears the stack
93 */
94 clear() {
95 this.stack = [];
96 }
97}
98
99module.exports = TypedStack;