Created
June 12, 2018 06:56
-
-
Save 197291/ef731b6bbc96fbc73112e0573c0c316c to your computer and use it in GitHub Desktop.
Stack
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Stacks! */ | |
// functions: push, pop, peek, length | |
var letters = []; // this is our stack | |
var word = "freeCodeCamp" | |
var rword = ""; | |
// put letters of word into stack | |
for (var i = 0; i < word.length; i++) { | |
letters.push(word[i]); | |
} | |
// pop off the stack in reverse order | |
for (var i = 0; i < word.length; i++) { | |
rword += letters.pop(); | |
} | |
if (rword === word) { | |
console.log(word + " is a palindrome."); | |
} | |
else { | |
console.log(word + " is not a palindrome."); | |
} | |
// Creates a stack | |
var Stack = function() { | |
this.count = 0; | |
this.storage = {}; | |
// Adds a value onto the end of the stack | |
this.push = function(value) { | |
this.storage[this.count] = value; | |
this.count++; | |
} | |
// Removes and returns the value at the end of the stack | |
this.pop = function() { | |
if (this.count === 0) { | |
return undefined; | |
} | |
this.count--; | |
var result = this.storage[this.count]; | |
delete this.storage[this.count]; | |
return result; | |
} | |
this.size = function() { | |
return this.count; | |
} | |
// Returns the value at the end of the stack | |
this.peek = function() { | |
return this.storage[this.count-1]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment