Last active
August 11, 2024 14:42
-
-
Save cizordj/897f5b53f485ef75dfb7bc7136945861 to your computer and use it in GitHub Desktop.
A <non-generic & strictly-typed> collection of numbers in pure Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class NumberCollection { | |
#numbers; | |
constructor(numbers) { | |
if ( | |
!Array.isArray(numbers) || | |
!numbers.every((str) => typeof str === "number") | |
) { | |
throw new Error( | |
"NumberCollection should be initialized with an array of numbers" | |
); | |
} | |
this.#numbers = numbers; | |
} | |
[Symbol.iterator]() { | |
let index = 0; | |
let numbers = this.#numbers; | |
return { | |
next: function () { | |
if (index < strings.length) { | |
return { value: numbers[index++], done: false }; | |
} else { | |
return { done: true }; | |
} | |
}, | |
}; | |
} | |
toJSON() { | |
return this.#numbers; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment