Skip to content

Instantly share code, notes, and snippets.

@maxgherman
Last active March 14, 2018 02:29
Show Gist options
  • Save maxgherman/e54d513074725cd15f693fe4d94a0c7a to your computer and use it in GitHub Desktop.
Save maxgherman/e54d513074725cd15f693fe4d94a0c7a to your computer and use it in GitHub Desktop.
Typed idx
interface IPost {
title: string;
comments?: string[];
}
interface IUser {
posts: IPost[];
}
interface IData {
users: IUser[];
}
const idxf = (o: {}, ...actions: Array<({ }) => {}>) =>
actions
.filter((item) => item)
.reduce((acc, curr) => acc ? curr(acc) : null, o);
const data: IData = {
users: [{
posts: [
{ title: 'One', comments: ['Comment one', 'Comment two'] },
{ title: 'Two' }]
}]
};
const idxf6 = <TData, T1, T2, T3, T4, T5, TResult>(
data: TData,
f1: (a: TData) => T1,
f2: (a: T1) => T2,
f3: (a: T2) => T3,
f4: (a: T3) => T4,
f5: (a: T4) => T5,
f6: (a: T5) => TResult) =>
idxf(data, f1, f2, f3, f4, f5, f6) as TResult;
const idxf5 = <TData, T1, T2, T3, T4, TResult>(
data: TData,
f1: (a: TData) => T1,
f2: (a: T1) => T2,
f3: (a: T2) => T3,
f4: (a: T3) => T4,
f5: (a: T4) => TResult) =>
idxf(data, f1, f2, f3, f4, f5) as TResult;
const idxf4 = <TData, T1, T2, T3, TResult>(
data: TData,
f1: (a: TData) => T1,
f2: (a: T1) => T2,
f3: (a: T2) => T3,
f4: (a: T3) => TResult) =>
idxf(data, f1, f2, f3, f4) as TResult;
const comment1 = idxf6(data,
(d: Pick<IData, 'users'>) => d.users,
(users: IUser[]) => users[0],
(user: Pick<IUser, 'posts'>) => user.posts,
(posts: IPost[]) => posts[0],
(post: Pick<IPost, 'comments'>) => post.comments,
(comments: string[]) => comments[0]);
const comments = idxf5<IData, IUser[], IUser, IPost[], IPost, string[]>(data,
(d) => d.users,
(users) => users[0],
(user) => user.posts,
(posts) => posts[0],
(post) => post.comments);
const noComments = idxf5(data,
(d) => d.users,
(users) => users[3],
(user) => user.posts,
(posts) => posts[0],
(post) => post.comments);
const post = idxf4(data,
(d) => d.users,
(users: IUser[]) => users[0],
(user) => user.posts,
(posts: IPost[]) => posts[0]);
console.log("Comment 1", comment1);
console.log("Comments", comments);
console.log("No comments", noComments);
console.log("Post", post);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment