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

Implementing stack methods

Implementing a stack is a rather easy task. We will follow a series of steps, where we will use the ES6 syntax, as follows:

  1. Define a constructor:
class Stack {
constructor() {

}
}
  1. Create a WeakMap() to store the stack items:
const sKey = {};
const items = new WeakMap();

class Stack {
constructor() {
items.set(sKey, [])
}
}
  1. Implement the methods described in the preceding API  in the Stack class:
const sKey = {};
const items = new WeakMap();

class Stack {
constructor() {
items.set(sKey, []);
}

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

pop() {
let stack = items.get(sKey)
return stack.pop()
}

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

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

size() {
return items.get(sKey).length;
}
}
  1. So, the final implementation of the Stack will look as follows:
var Stack = (() => {
const sKey = {};
const items = new WeakMap();

class Stack {

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

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

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

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

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

size() {
return items.get(sKey).length;
}
}

return Stack;
})();

This is an overarching implementation of a JavaScript stack, which by no means is comprehensive and can be changed based on the application's requirements. However, let's go through some of the principles employed in this implementation.

We have used a WeakMap() here, which as explained in the preceding paragraph, helps with internal memory management based on the reference to the stack items.

Another important thing to notice is that we have wrapped the Stack class inside an IIFE, so the constants items and sKey are available to the Stack class internally but are not exposed to the outside world. This is a well-known and debated feature of the current JS Clasimplementation, which does not allow class-level variables to be declared. TC39 essentially designed the ES6 Class in such a way that it should only define and declare its members, which are prototype methods in ES5. Also, since adding variables to prototypes is not the norm, the ability to create class-level variables has not been provided. However, one can still do the following:

    constructor() {
this.sKey = {};
this.items = new WeakMap();
this.items.set(sKey, []);
}

However, this would make the items accessible also from outside our Stack methods, which is something that we want to avoid.

主站蜘蛛池模板: 河西区| 府谷县| 交城县| 左权县| 长岭县| 潜江市| 西充县| 桦川县| 阳西县| 凤庆县| 昌都县| 勐海县| 武川县| 宁化县| 鹰潭市| 神池县| 尚志市| 鄂尔多斯市| 景洪市| 屯门区| 邹城市| 潞西市| 镶黄旗| 乌审旗| 新疆| 涿州市| 株洲市| 宜川县| 慈溪市| 禹州市| 黄石市| 鲁山县| 嘉兴市| 霍邱县| 伊春市| 甘南县| 柳林县| 丰台区| 凌海市| 墨竹工卡县| 从江县|