官术网_书友最值得收藏!

Creating a stack

Since the code for an Angular application is now in TypeScript, we can further optimize the stack that we created. Using TypeScript makes the code more readable thanks to the private variables that can be created in a TypeScript class.

So, our TypeScript-optimized code would look something like the following:

export class Stack {
private wmkey = {};
private items = new WeakMap();

constructor() {
this.items.set(this.wmkey, []);
}

push(element) {
let stack = this.items.get(this.wmkey);
stack.push(element);
}

pop() {
let stack = this.items.get(this.wmkey);
return stack.pop();
}

peek() {
let stack = this.items.get(this.wmkey);
return stack[stack.length - 1];
}

clear() {
this.items.set(this.wmkey, []);
}

size() {
return this.items.get(this.wmkey).length;
}
}

To use the Stack created previously, you can simply import the stack into any component and then use it. You can see in the following screenshot that as we made the WeakMap() and the key private members of the Stack class, they are no longer accessible from outside the class:

>
Public methods accessible from the Stack class
主站蜘蛛池模板: 嘉义市| 鄄城县| 长子县| 东方市| 柳江县| 宣武区| 怀远县| 夏邑县| 开平市| 河东区| 台东县| 闽清县| 黄石市| 岳阳市| 宜兰县| 沈丘县| 彭山县| 阜康市| 尉氏县| 仙居县| 肃南| 灌阳县| 晋宁县| 汉中市| 玉龙| 额济纳旗| 沈阳市| 健康| 都昌县| 精河县| 邓州市| 永福县| 德保县| 永新县| 梁河县| 江口县| 怀来县| 宜兰县| 获嘉县| 南郑县| 来凤县|