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 me:
Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.
I am open to work on an interesting project. Send me an email at ramu.narasinga@gmail.com
My Github - https://github.com/ramu-narasinga
My website - https://ramunarasinga.com
My Youtube channel - https://www.youtube.com/@thinkthroo
Learning platform - https://thinkthroo.com
Codebase Architecture - https://app.thinkthroo.com/architecture
Best practices - https://app.thinkthroo.com/best-practices
Production-grade projects - https://app.thinkthroo.com/production-grade-projects
Top comments (0)