const _items = new WeakMap()
class Stack {
constructor() {
_items.set(this, [])
}
push(obj) {
_items.get(this).push(obj)
}
pop() {
const items = _items.get(this)
if (items.length === 0) {
throw new Error('Stack is empty')
}
return items.pop()
}
peek() {
const items = _items.get(this)
if (items.length === 0) {
throw new Error('Stack is empty')
}
return items[items.length -1]
}
get count() {
return _items.get(this).length
}
}


本文介绍了一种使用弱引用实现的栈数据结构。该栈通过new WeakMap()初始化,避免了内存泄漏的风险。构造函数中使用弱引用Map来存储栈元素,提供了push、pop、peek和获取元素数量的方法。
613

被折叠的 条评论
为什么被折叠?



