Skip to content

Instantly share code, notes, and snippets.

@jlescalonap
Created December 1, 2023 12:26
Show Gist options
  • Save jlescalonap/bb15ecfa044d6c1126a08adb8f6ce815 to your computer and use it in GitHub Desktop.
Save jlescalonap/bb15ecfa044d6c1126a08adb8f6ce815 to your computer and use it in GitHub Desktop.
Example of typeguards implementation
class Sorter {
constructor(public collection: number[] | string) {}
sort(): void {
const { length } = this.collection;
for (let i = 0; i < length; i++) {
for (let j = 0; j < length - i - 1; j++) {
if (this.collection instanceof Array) {
if (this.collection[j] > this.collection[j + 1]) {
const leftHand = this.collection[j];
this.collection[j] = this.collection[j + 1];
this.collection[j + 1] = leftHand;
}
}
if (typeof this.collection === 'string') {
}
}
}
}
}
const sorter = new Sorter([10, 3, -5, 0]);
sorter.sort();
console.log(sorter.collection);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment