- Hands-On Data Structures and Algorithms with JavaScript
- Kashyap Mukkamala
- 176字
- 2021-06-30 19:12:09
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
推薦閱讀
- Learning Microsoft Windows Server 2012 Dynamic Access Control
- Vue.js 2 and Bootstrap 4 Web Development
- CentOS 7 Linux Server Cookbook(Second Edition)
- Python數據挖掘與機器學習實戰
- Create React App 2 Quick Start Guide
- JSP程序設計實例教程(第2版)
- C語言程序設計
- Mudbox 2013 Cookbook
- Machine Learning for OpenCV
- Java RESTful Web Service實戰
- PHP+MySQL Web應用開發教程
- 軟件測試技術
- HTML5程序設計基礎教程
- 城市信息模型平臺頂層設計與實踐
- Python深度學習入門:從零構建CNN和RNN