Skip to content

Instantly share code, notes, and snippets.

@neet
Last active June 27, 2020 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neet/2524424eec11de90bbd45c0554cd9bd2 to your computer and use it in GitHub Desktop.
Save neet/2524424eec11de90bbd45c0554cd9bd2 to your computer and use it in GitHub Desktop.
Arithmetic & geometric sequence written in TypeScript
interface Sequence {
first: number;
last: number;
length: number;
getNth(n: number): number;
getSum(n: number): number;
toArray(): number[];
[Symbol.iterator](): Iterator<number>;
}
abstract class BaseSequence {
abstract length: number;
abstract getNth(n: number): number;
get last() {
return this.getNth(this.length - 1);
}
toArray() {
return Array.from({ length: this.length }, (_, i) => this.getNth(i));
}
[Symbol.iterator]() {
let i = 0;
return {
next() {
const value = this.getNth(i);
const done = i + 1 >= this.length;
i++;
return { value, done };
},
return(value: number) {
return { value, done: true };
},
throw(error: Error) {
throw error;
}
}
}
}
class ArithmeticSequence extends BaseSequence implements Sequence {
constructor(
readonly first: number,
readonly diff: number,
readonly length = Number.POSITIVE_INFINITY
) {
super();
}
getNth(n: number) {
if (n + 1 > this.length) {
throw new RangeError(
`N value ${n} is greater than the length of the sequence ${this.length}`
);
}
return this.first + this.diff * n;
}
getSum() {
return ((this.first + this.last) * this.length) / 2;
}
}
class GeometricSequence extends BaseSequence implements Sequence {
constructor(
readonly first: number,
readonly ratio: number,
readonly length: number = Number.POSITIVE_INFINITY
) {
super();
}
getNth(n: number) {
if (n + 1 > this.length) {
throw new RangeError(
`N value ${n} is greater than the length of the sequence ${this.length}`
);
}
return this.first * (this.ratio ** n);
}
getSum() {
if (this.length === 1) {
return this.length * this.first;
}
return (
(this.first * ((this.ratio ** this.length) - 1)) /
//-------------------------------
(this.ratio - 1)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment