DEV Community

Discussion on: Stack Data Structure Using Javascript

Collapse
 
aminnairi profile image
Amin

Hi there and thanks for your article, I also like to train my data algorithm in JavaScript. I tend to try and implement them using only functions and recursion if needed. Here is my attempt I wanted to share with you.

const createStack = () => {
  const state = {
    popped: null,
    data: [],
  };

  const stack = {
    push: item => (state.data = [item, ...state.data], state.head = item, state.size = state.size + 1, stack),
    pop: () => (state.popped = state.data[0] ?? null,  state.data = state.data.slice(1), state.popped),
    peek: () => state.data[0] ?? null,
    size: () => state.data.length
  };

  return stack;
};

const language = createStack();

language
  .push("Typescript")
  .push("Angular")
  .push("JS")
  .push("C++");

console.log(language);        // [object Object]
console.log(language.pop());  // C++
console.log(language);        // [object Object]
console.log(language.pop());  // JS
console.log(language);        // [object Object]
Enter fullscreen mode Exit fullscreen mode

Not the easiest to read given I used the comma operator pretty much for every method but it gets the job done using some one-liners.

Collapse
 
nikhil27b profile image
Nikhil Bobade

Good 👍👍