Skip to content

Instantly share code, notes, and snippets.

@samkcarlile
Last active May 3, 2022 03:07
Show Gist options
  • Save samkcarlile/419c72b29401983fd07b08afff85d2c4 to your computer and use it in GitHub Desktop.
Save samkcarlile/419c72b29401983fd07b08afff85d2c4 to your computer and use it in GitHub Desktop.
Weird `join` implementation
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