Last active
June 27, 2021 13:50
-
-
Save moatorres/2f5b54879cde8a1194d8f33cf2c3c9ae to your computer and use it in GitHub Desktop.
List type in JS/Node (without classes)
This file contains hidden or 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
import { List } from './List' | |
let firstList = List.of([2, 3, 4]) | |
console.log('emit:', firstList.emit()) // => [ 2, 3, 4 ] | |
console.log('head:', firstList.head()) // => 2 | |
console.log('last:', firstList.last()) // => 4 | |
console.log('tail:', firstList.tail().emit()) // => [ 3, 4 ] | |
let secondList = List.of([10, 20, 30]) | |
console.log('inspect:', secondList.inspect()) // => 'List(10,20,30)' | |
console.log('concat:', secondList.concat(40).emit()) // => [ 10, 20, 30, 40 ] | |
console.log('map:', secondList.map(v => v * 3).map(v => v * 3).emit()) // => [ 90, 180, 270 ] | |
console.log('chain:', secondList.chain(a => a * 200)) // => [ 2000, 4000, 6000 ] |
This file contains hidden or 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
export const List = (x) => ({ | |
emit: () => x, | |
head: () => x[0], | |
tail: () => List.of(x.splice(1)), | |
last: () => x[x.length - 1], | |
chain: (f) => x.map(f), | |
map: (f) => List.of(x.map(f)), | |
inspect: () => `List(${x})`, | |
concat: (a) => List.of(x.concat(a)) | |
}) | |
const ListOf = (x) => (Array.isArray(x) ? List(x) : List([x])) | |
List.of = ListOf |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment