Advertisement
AhmetUstun

13. String Builder (CODE)

Jul 4th, 2021
364
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class StringBuilder {
  2.  
  3.     constructor(string) {
  4.         if (string !== undefined) {
  5.             StringBuilder._vrfyParam(string);
  6.             this._stringArray = Array.from(string);
  7.         } else {
  8.             this._stringArray = [];
  9.         }
  10.     }
  11.  
  12.     append(string) {
  13.         StringBuilder._vrfyParam(string);
  14.         for (let i = 0; i < string.length; i++) {
  15.             this._stringArray.push(string[i]);
  16.         }
  17.     }
  18.  
  19.     prepend(string) {
  20.         StringBuilder._vrfyParam(string);
  21.         for (let i = string.length - 1; i >= 0; i--) {
  22.             this._stringArray.unshift(string[i]);
  23.         }
  24.     }
  25.  
  26.     insertAt(string, startIndex) {
  27.         StringBuilder._vrfyParam(string);
  28.         this._stringArray.splice(startIndex, 0, ...string);
  29.     }
  30.  
  31.     remove(startIndex, length) {
  32.         this._stringArray.splice(startIndex, length);
  33.     }
  34.  
  35.     static _vrfyParam(param) {
  36.         if (typeof param !== 'string') throw new TypeError('Argument must be a string');
  37.     }
  38.  
  39.     toString() {
  40.         return this._stringArray.join('');
  41.     }
  42. }
  43.  
  44. module.exports = StringBuilder;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement