码迷,mamicode.com
首页 > 编程语言 > 详细

ES6的JavaScript数据结构的实现

时间:2019-09-25 19:53:27      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:string   javascrip   result   map   cto   output   ensure   efi   turn   

目的:ES6标准下的JS数据结构的一些实现代码。(作为记录和启发)

内容:栈。(未完成,待继续)

一、数据结构

1、栈(先入后出)

// @ts-check

class Stack {
constructor() {
this.count = 0;
this.items = {};
}

push(element) {
this.items[this.count] = element;
this.count++;
}

pop() {
if (this.isEmpty()) {
return undefined;
}
this.count--;
const result = this.items[this.count];
delete this.items[this.count];
return result;
}

peek() {
if (this.isEmpty()) {
return undefined;
}
return this.items[this.count - 1];
}

isEmpty() {
return this.count === 0;
}

size() {
return this.count;
}

clear() {
/* while (!this.isEmpty()) {
this.pop();
} */
this.items = {};
this.count = 0;
}

toString() {
if (this.isEmpty()) {
return ‘‘;
}
let objString = `${this.items[0]}`;
for (let i = 1; i < this.count; i++) {
objString = `${objString},${this.items[i]}`;
}
return objString;
}
}
const stack = new Stack(); // new StackArray();

// using WeakMap to store Stack items we ensure true privacy
// console.log(Object.getOwnPropertyNames(stack));
// console.log(Object.keys(stack));
// console.log(stack.items);

console.log(‘stack.isEmpty() => ‘, stack.isEmpty()); // outputs true

stack.push(6);
stack.push(8);

console.log(‘stack after push 5 and 8 => ‘, stack.toString());

console.log(‘stack.peek() => ‘, stack.peek()); // outputs 8

stack.push(11);

console.log(‘stack.size() after push 11 => ‘, stack.size()); // outputs 3
console.log(‘stack.isEmpty() => ‘, stack.isEmpty()); // outputs false

stack.push(15);

stack.pop();
stack.pop();

console.log(‘stack.size() after push 15 and pop twice => ‘, stack.size());

 

2、队列

 

ES6的JavaScript数据结构的实现

标签:string   javascrip   result   map   cto   output   ensure   efi   turn   

原文地址:https://www.cnblogs.com/xinkuiwu/p/11586955.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!