arrayToDict function in tRPC source code

Think ThrooThink Throo
2 min read

In this article, we analyze arrayToDict function found in tRPC source code.

// https://github.com/trpc/trpc/pull/669
function arrayToDict(array: unknown[]) {
 const dict: Record<number, unknown> = {};
 for (let index = 0; index < array.length; index++) {
 const element = array[index];
 dict[index] = element;
 }
 return dict;
}

This function is straight forward. dict is an object initialized above the for loop. In this for loop, array[index] is assigned to element and dict is an object that array indices as keys and values being array items based on index.

Although this function is simple, a lot was discussed in PR: https://github.com/trpc/trpc/pull/669 before this solution was presented to KATT (Creator of tRPC).

This pull request was about — fix: batching with zod .optional() input.

PR’s description:
- JSON.stringify([undefined]) === [null]
- this causes issues with .optional() zod schemas as it expects an object or undefined, not null
- fixed by ugly hack that runs validator twice when it fails if the raw input was === null.
- fixed by @simonedelmann’s idea

I would recommend going through this pull request conversation to give you an insight on how decisions are made. This conversation shows how ideas are bounced around and also talk about what could break based on an idea, if it’s just an edge-case and they finally choose to go with arrayToDict idea.

In this pull request, you also find All Contributors Github app that gives
attribution to contributor based on an idea. This is what All Contributors is about — Recognize all contributors, not just the ones who push code. With All Contributes, even if you present an idea without writing any code, you could make them a contributor with a comment:


@all-contributors add @username for reviews

and @all-contributors adds tagged user as a contributor.

About us:

At Thinkthroo, we study large open source projects and provide architectural guides. We have developed resubale Components, built with tailwind, that you can use in your project. We offer Next.js, React and Node development services.

Book a meeting with us to discuss your project.

References:

  1. https://github.com/trpc/trpc/blob/next/packages/client/src/links/internals/httpUtils.ts#L57

  2. https://github.com/trpc/trpc/pull/669

0
Subscribe to my newsletter

Read articles from Think Throo directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Think Throo
Think Throo