Guest User

Untitled

a guest
Dec 18th, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. import checkIfArray from './checkIfArray';
  2.  
  3. function checkIfString(x) {
  4. x.forEach(function(el) {
  5. if (typeof el !== 'string') {
  6. throw new Error('Array can only contain strings');
  7. }
  8. });
  9. }
  10.  
  11. var StackConstructor = {
  12. init: function(delimiter = '||', input = '') {
  13. this.input = input;
  14. this.delimiter = delimiter;
  15.  
  16. if (typeof input !== 'string' && !Array.isArray(input)) {
  17. throw new Error('Please enter a string or an array');
  18. }
  19.  
  20. if(Array.isArray(input)) {
  21. checkIfString(input);
  22. this.input = input.join("||");
  23. }
  24.  
  25. while(this.input.indexOf(this.delimiter) !== -1) {
  26. this.input = this.input.replace(this.delimiter, "[*-delimiter-*]");
  27. }
  28. },
  29. push: function(newString) {
  30. if (typeof newString !== 'string' && !Array.isArray(newString)) {
  31. throw new Error('Please enter a string or an array');
  32. }
  33.  
  34. if(Array.isArray(newString)) {
  35. checkIfString(input);
  36. newString = newString.join("||");
  37. }
  38.  
  39. while(newString.indexOf(this.delimiter) !== -1) {
  40. newString = newString.replace(this.delimiter, "[*-delimiter-*]");
  41. }
  42.  
  43. this.input = this.input ? this.input + this.delimiter + newString : newString;
  44. },
  45. pop: function() {
  46. const LAST_INDEX = this.input.lastIndexOf(this.delimiter);
  47.  
  48. if(!this.input) {
  49. throw new Error('Cannot execute push as current string is empty');
  50. }
  51.  
  52. this.input = (LAST_INDEX !== -1) ? this.input.substring(0, LAST_INDEX) : '';
  53. },
  54. concat: function(newString) {
  55. if (typeof newString !== 'string') {
  56. throw new Error('Please enter a string');
  57. }
  58.  
  59. return this.input ? this.input + this.delimiter + newString : newString;
  60. },
  61. indexesOf(n) {
  62. let indexesString = '';
  63. for(let i = 0; i < this.input.length; i++) {
  64. if(n === this.input[i]) {
  65. indexesString += i + ', ';
  66. }
  67. }
  68.  
  69. let lastIndexofComma = indexesString.lastIndexOf(',');
  70. return indexesString.substring(0, lastIndexofComma);
  71. }
  72. }
  73.  
  74. // To use:
  75. // var stackConstructorExample = Object.create(StackConstructor);
  76. // stackConstructorExample.init("||", "example test case");
Add Comment
Please, Sign In to add comment