| 1 | | // |
| 2 | | // This is only a SKELETON file for the 'Series' exercise. It's been provided as a |
| 3 | | // convenience to get you started writing code faster. |
| 4 | | // |
| 5 | | |
| 6 | 1 | export class Series { |
| 7 | 2 | /** |
| 8 | | * @param {string} numberString |
| 3 | * Creates a new Series instance from a string of digits |
| 4 | * @param {string} numberString - A string containing only digits |
| 5 | * @throws {Error} If the input string is empty |
| 9 | 6 | */ |
| 10 | 7 | constructor(numberString) { |
| 11 | | throw new Error('Remove this line and implement the function'); |
| 8 | // Edge Case: Empty series input |
| 9 | if (numberString === '') { |
| 10 | throw new Error('series cannot be empty'); |
| 11 | } |
| 12 | |
| 13 | this.digits = numberString.split('').map(Number); |
| 14 | |
| 15 | // Handled Edge Cases: Empty series input |
| 12 | 16 | } |
| 13 | 17 | |
| 14 | 18 | /** |
| 15 | | * @param {number} sliceSize |
| 16 | | * @returns {number[][]} |
| 19 | * Returns all contiguous substrings of the specified length from the series |
| 20 | * @param {number} sliceSize - The length of each substring to extract |
| 21 | * @returns {number[][]} An array of arrays, each containing digits of a substring |
| 22 | * @throws {Error} If sliceSize is invalid (negative, zero, or greater than series length) |
| 17 | 23 | */ |
| 18 | 24 | slices(sliceSize) { |
| 19 | | throw new Error('Remove this line and implement the function'); |
| 25 | // Edge Case: Negative slice length |
| 26 | if (sliceSize < 0) { |
| 27 | throw new Error('slice length cannot be negative'); |
| 28 | } |
| 29 | |
| 30 | // Edge Case: Zero slice length |
| 31 | if (sliceSize === 0) { |
| 32 | throw new Error('slice length cannot be zero'); |
| 33 | } |
| 34 | |
| 35 | // Edge Case: Slice length greater than series length |
| 36 | if (sliceSize > this.digits.length) { |
| 37 | throw new Error('slice length cannot be greater than series length'); |
| 38 | } |
| 39 | |
| 40 | const result = []; |
| 41 | |
| 42 | // Edge Case: Valid slice size equal to series length |
| 43 | if (sliceSize === this.digits.length) { |
| 44 | result.push([...this.digits]); |
| 45 | return result; |
| 46 | } |
| 47 | |
| 48 | // Sliding window approach to extract all contiguous substrings |
| 49 | for (let i = 0; i <= this.digits.length - sliceSize; i++) { |
| 50 | result.push(this.digits.slice(i, i + sliceSize)); |
| 51 | } |
| 52 | |
| 53 | // Handled Edge Cases: Negative slice length, Zero slice length, Slice length greater than series length, Valid slice size equal to series length |
| 54 | return result; |
| 20 | 55 | } |
| 21 | 56 | } |