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

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
主站蜘蛛池模板: 延寿县| 收藏| 张家港市| 雷山县| 彭山县| 磐石市| 汝城县| 平陆县| 兰考县| 尼勒克县| 汉阴县| 寿宁县| 西青区| 赣榆县| 尉氏县| 禹城市| 田林县| 松桃| 开原市| 汉源县| 右玉县| 灵宝市| 馆陶县| 尉犁县| 彰化县| 南昌市| 乌兰察布市| 读书| 满洲里市| 多伦县| 神农架林区| 陕西省| 康乐县| 普格县| 雅江县| 钟祥市| 涞源县| 洱源县| 嘉禾县| 连州市| 阜宁县|