Last active
June 27, 2020 18:59
-
-
Save neet/2524424eec11de90bbd45c0554cd9bd2 to your computer and use it in GitHub Desktop.
Arithmetic & geometric sequence written in TypeScript
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
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