Skip to content

Instantly share code, notes, and snippets.

@emmabostian
Created March 28, 2020 12:50
Show Gist options
  • Save emmabostian/b9159bb489dde73b79a436944facce02 to your computer and use it in GitHub Desktop.
Save emmabostian/b9159bb489dde73b79a436944facce02 to your computer and use it in GitHub Desktop.
export default class Stack {
constructor() {
this.stack = [];
}
push(item) {
this.stack.push(item);
}
pop() {
return this.stack.pop();
}
length() {
return this.stack.length;
}
peek() {
return this.stack[this.stack.length - 1];
}
print() {
return this.stack.join(" ");
}
isEmpty() {
return this.length() === 0;
}
}
import Stack from "./stack";
function reverseAString(str) {
let letters = str.split("");
let stack = new Stack();
let reversedLetters = [];
letters.forEach(letter => stack.push(letter));
while (!stack.isEmpty()) {
reversedLetters.push(stack.pop());
}
return reversedLetters.join("");
}
console.log(reverseAString("abcdef"));
OR just return
str.split('').reverse().join('');
@ThiagosLima
Copy link

ThiagosLima commented Mar 28, 2020

I was thinking in other ways. 😊

// Using Array.from
const stringReverse = string =>
  Array.from(string)
    .reverse()
    .join("");
// Using reduce
const stringReverse = string =>
  string
    .split("")
    .reduce((acc, curr) => [curr, ...acc])
    .join("");
// Using a for..of
const stringReverse = string => {
  let reversed = "";

  for (const char of string) {
    reversed = char + reversed;
  }

  return reversed;
};
// Using destructuring
const stringReverse = ([...string]) => string.reverse().join("");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment