Skip to content

Instantly share code, notes, and snippets.

@MikeDigitize
Last active April 9, 2017 21:19
Show Gist options
  • Save MikeDigitize/b8c1fcd572031d1ac98453db993796b2 to your computer and use it in GitHub Desktop.
Save MikeDigitize/b8c1fcd572031d1ac98453db993796b2 to your computer and use it in GitHub Desktop.
/* Create a Stack constructor that
- creates an object that stores strings within a single string
- that has a way of delimiting strings
- has a push, pop, concat method that works exactly like their array counterparts
- has an indexesOf method that behaves just like Array.prototype.indexOf but will also find all indexes if more than one exist
- does your constructor initialise with a single string or an array of strings?
- does it have to be called as a constructor / class - could it just be an object / function?
*/
function Stack(values) {
if(!(this instanceof Stack)) {
return new Stack(values);
}
this.storage = '';
this.concat.apply(this, values);
}
Stack.prototype.push = function(item) {
const delimiter = '***';
const index = this.storage.length;
this.storage = this.storage.concat(`${delimiter}${item}`);
return index;
};
Stack.prototype.concat = function(...items) {
const delimiter = '***';
items.forEach(item => this.storage = this.storage.concat(`${delimiter}${item}`));
return this;
};
Stack.prototype.pop = function(item) {
const delimiter = '***';
const lastDelimterPosition = this.storage.lastIndexOf(delimiter);
const lastItem = this.storage.substr(lastDelimterPosition, this.storage.length);
this.storage = this.storage.substr(0, lastDelimterPosition);
return lastItem;
};
Stack.prototype.indexesOf = function(value) {
let storage = this.storage;
let position = 0;
const indexes = [];
while(storage.length) {
let index = storage.indexOf(value);
if(index > -1) {
position += index;
indexes.push(position);
storage = storage.substr(index + value.length, storage.length);
position = this.storage.length - storage.length;
}
else {
storage = '';
}
}
return indexes.length > 1 ? indexes : indexes.length ? indexes[0] : -1;
}
var stack = Stack(['another!', 'newitem!', 'another!']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment