From 817fce8e6c0f5e8e336248ebbe5640298bef4a42 Mon Sep 17 00:00:00 2001 From: Nir Parisian Date: Sat, 3 Nov 2018 09:45:28 +0200 Subject: [PATCH 1/2] Stack implementation using array --- Stack.js | 14 +++++--------- Stack.test.js | 13 ++++++++----- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/Stack.js b/Stack.js index 525dfcf..cecbee1 100644 --- a/Stack.js +++ b/Stack.js @@ -1,15 +1,11 @@ const Stack = (() => { - const elementsKey = {}; - const items = new WeakMap(); + const items = new Array(); class Stack { - constructor() { - items.set(elementsKey, []); - } - get _stack() { - return items.get(elementsKey); + return items; } + push(element) { this._stack.push(element); } @@ -23,11 +19,11 @@ const Stack = (() => { } clear() { - items.set(elementsKey, []); + items.length = 0; } size() { - return items.get(elementsKey).length; + return items.length; } } diff --git a/Stack.test.js b/Stack.test.js index bb76a74..bc8826d 100644 --- a/Stack.test.js +++ b/Stack.test.js @@ -1,16 +1,19 @@ const Stack = require("./Stack"); const stack = new Stack(); -stack.push(10); -stack.push(20); +stack.push(1); +stack.push(5); +stack.push(100); console.log(stack.items); // prints undefined -> cannot be accessed directly -console.log(stack.size()); // prints 2 +console.log(stack.size()); // prints 3 -console.log(stack.peek()); // prints 20 +console.log(stack.peek()); // prints 100 -console.log(stack.pop()); // prints 20 +console.log(stack.pop()); // prints 100 + +console.log(stack.pop()); // prints 5 console.log(stack.size()); // prints 1 From 3f77f35657762bbde67b4a35a6756d53ad3b48fa Mon Sep 17 00:00:00 2001 From: Nir Parisian Date: Sat, 3 Nov 2018 11:54:53 +0200 Subject: [PATCH 2/2] add readme to the branch --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..25f69ad --- /dev/null +++ b/README.md @@ -0,0 +1,6 @@ +# JavaScript Stack + +In this repository you can find simple implementions of the stack data structure. + +- Branch "WeakMap" contains a stack implementation using JS WeakMap data structure. +- Branch "Array" contains a stack implementation using JS Array data structure.