Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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");
Add Comment
Please, Sign In to add comment