Last active
December 15, 2017 22:38
-
-
Save fdjones/21d313cb708fa7628c01137d7fe6dad3 to your computer and use it in GitHub Desktop.
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
import checkIfArray from './checkIfArray'; | |
function checkIfString(x) { | |
x.forEach(function(el) { | |
if (typeof el !== 'string') { | |
throw new Error('Array can only contain strings'); | |
} | |
}); | |
} | |
var StackConstructor = { | |
init: function(delimiter = '||', input = '') { | |
this.input = input; | |
this.delimiter = delimiter; | |
if (typeof input !== 'string' && !Array.isArray(input)) { | |
throw new Error('Please enter a string or an array'); | |
} | |
if(Array.isArray(input)) { | |
checkIfString(input); | |
this.input = input.join("||"); | |
} | |
while(this.input.indexOf(this.delimiter) !== -1) { | |
this.input = this.input.replace(this.delimiter, "[*-delimiter-*]"); | |
} | |
}, | |
push: function(newString) { | |
if (typeof newString !== 'string' && !Array.isArray(newString)) { | |
throw new Error('Please enter a string or an array'); | |
} | |
if(Array.isArray(newString)) { | |
checkIfString(input); | |
newString = newString.join("||"); | |
} | |
while(newString.indexOf(this.delimiter) !== -1) { | |
newString = newString.replace(this.delimiter, "[*-delimiter-*]"); | |
} | |
this.input = this.input ? this.input + this.delimiter + newString : newString; | |
}, | |
pop: function() { | |
const LAST_INDEX = this.input.lastIndexOf(this.delimiter); | |
if(!this.input) { | |
throw new Error('Cannot execute push as current string is empty'); | |
} | |
this.input = (LAST_INDEX !== -1) ? this.input.substring(0, LAST_INDEX) : ''; | |
}, | |
concat: function(newString) { | |
if (typeof newString !== 'string') { | |
throw new Error('Please enter a string'); | |
} | |
return this.input ? this.input + this.delimiter + newString : newString; | |
}, | |
indexesOf(n) { | |
let indexesString = ''; | |
for(let i = 0; i < this.input.length; i++) { | |
if(n === this.input[i]) { | |
indexesString += i + ', '; | |
} | |
} | |
let lastIndexofComma = indexesString.lastIndexOf(','); | |
return indexesString.substring(0, lastIndexofComma); | |
} | |
} | |
// To use: | |
// var stackConstructorExample = Object.create(StackConstructor); | |
// stackConstructorExample.init("||", "example test case"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment