Skip to content

Instantly share code, notes, and snippets.

@tekerson
Created Nov 30, 2017
Embed
What would you like to do?
Possible implementation of a non-empty collection in TypeScript
class NonEmpty<T> {
readonly head: T
protected tail: Array<T>
constructor(head: T, ...tail: T[]) {
this.head = head
this.tail = tail
}
static fromArray<U>(values: Array<U>): NonEmpty<U> | undefined {
if (values.length === 0) return undefined
const [head, ...tail] = values
return new NonEmpty(head, ...tail)
}
toArray(): Array<T> {
return [this.head, ...this.tail]
}
get(n: number): T | undefined {
return this.tail[n]
}
map<U>(fn: (t: T) => U): NonEmpty<U> {
return new NonEmpty(fn(this.head), ...this.tail.map(fn))
}
reduce<U>(fn: (acc: U, t: T) => U, initialValue: U): U {
return [this.head, ...this.tail].reduce<U>(fn, initialValue)
}
reduce1(fn: (acc: T, t: T) => T): T {
return this.tail.reduce<T>(fn, this.head)
}
concat(other: NonEmpty<T>): NonEmpty<T> {
return new NonEmpty(this.head, ...this.tail, other.head, ...other.tail)
}
}
function sum(nums: NonEmpty<number>): number {
return nums.reduce((a, b) => a + b, 0)
}
const nums = NonEmpty.fromArray([1,2,3])
if (nums != undefined) {
console.log(sum(nums))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment