Last active
May 3, 2022 03:07
-
-
Save samkcarlile/419c72b29401983fd07b08afff85d2c4 to your computer and use it in GitHub Desktop.
Weird `join` implementation
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
const dogs = [ | |
{ name: 'Fido', favorites: ['sam', 'mark', 'bob'] }, | |
{ name: 'Happy', favorites: ['mark'] }, | |
{ name: 'Buddy', favorites: ['bob'] }, | |
{ name: 'Oscar', favorites: ['mark', 'sam', 'bob'] }, | |
]; | |
const friends = [ | |
{ name: 'sam', age: 22, toes: 5 }, | |
{ name: 'mark', age: 37, toes: 9 }, | |
{ name: 'bob', age: 28, toes: 3 }, | |
]; | |
join(friends) | |
.onto(dogs) | |
.match(({ name }, { favorites }) => favorites.includes(name)) | |
.object({ | |
key: (friend) => friend.name, | |
value: (dog) => dog.favorites, | |
}); | |
function join<T>($: T[]) { | |
return { | |
onto<U>(onto: U[]) { | |
return { | |
match(match: (e: T, o: U) => boolean) { | |
const entries = $.map( | |
(e) => [e, onto.filter((o) => match(e, o))] as [T, U[]] | |
); | |
const _extras = { | |
object: <R>({ | |
key, | |
value, | |
}: { | |
key: (e: T) => string | number; | |
value: (o: U) => R; | |
}) => | |
Object.fromEntries( | |
entries.map(([e, o]) => [key(e), o.map(value)]) | |
), | |
}; | |
return Object.assign(entries, _extras); | |
}, | |
}; | |
}, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment