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

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
主站蜘蛛池模板: 九龙坡区| 湄潭县| 勐海县| 丽江市| 德江县| 宕昌县| 嘉义县| 华亭县| 新和县| 浑源县| 九台市| 育儿| 博湖县| 嘉祥县| 古交市| 平江县| 宣城市| 宝兴县| 博爱县| 鹤岗市| 哈巴河县| 鹤岗市| 德州市| 百色市| 绵竹市| 定西市| 襄汾县| 石台县| 民乐县| 手机| 怀化市| 旬邑县| 南昌市| 惠州市| 搜索| 泌阳县| 灵璧县| 拜泉县| 唐山市| 枣强县| 三都|