Skip to content

Instantly share code, notes, and snippets.

@dionyziz
Created July 14, 2021 21:53
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 dionyziz/4bff651509cf5761a77897331b496c86 to your computer and use it in GitHub Desktop.
Save dionyziz/4bff651509cf5761a77897331b496c86 to your computer and use it in GitHub Desktop.
class List {
static fromArray(arr) {
if (arr.length == 0) {
return new EmptyList()
}
return new FullList(
arr[0],
() => List.fromArray(arr.slice(1))
)
}
forEach(f) {
if (this instanceof EmptyList) {
return
}
f(this.head)
this.tail().forEach(f)
}
take(n) {
if (n == 0) {
return new EmptyList()
}
if (this instanceof EmptyList) {
return this
}
return new FullList(this.head, () => this.tail().take(n - 1))
}
print() {
this.forEach(x => console.log(x))
}
map(f) {
if (this instanceof EmptyList) {
return this
}
return new FullList(f(this.head), () => this.tail().map(f))
}
append(x) {
if (this instanceof EmptyList) {
return new FullList(x, () => new EmptyList())
}
return new FullList(this.head, () => this.tail().append(x))
}
filter(f) {
if (this instanceof EmptyList) {
return new EmptyList()
}
if (!f(this.head)) {
return this.tail()
}
return new FullList(this.head, () => this.tail().filter(f))
}
length() {
return this.reduce((a, _) => a + 1, 0)
}
sum() {
return this.reduce((a, x) => a + x, 0)
}
reduce(f, a) { // this is [b], f is (a, b) -> a
if (this instanceof EmptyList) {
return a
}
return this.tail().reduce(f, f(a, this.head))
}
}
class FullList extends List {
constructor(head, tail) {
super()
this.head = head
this.tail = tail
}
}
class EmptyList extends List {}
function range(start, end) {
if (start > end) {
return new EmptyList()
}
return new FullList(start, () => range(start + 1, end))
}
const naturalNumbers = range(1, Math.infinity)
const evenNumbers = naturalNumbers.map(x => x * 2)
const evenNumbersDivisibleByThree = evenNumbers.filter(x => x % 3 == 0)
evenNumbersDivisibleByThree.take(5).print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment