Tips from open-source: An Object with Map and Set.
This tip is picked from Next.js source code. In this article, you will learn how to use an Object with Map and Set in Javascript.
I found this unique Object with Map and Set in next/src/export/index.ts.
Skimming through the code around this function, I quickly learnt that it is used for Telemetry tracking purposes.
This just reminds me of usecase where I had to deal with file paths, text replacements with in a file (say .docx, .txt). For example, you have an object like below:
let fileCustomisations = {
paths: new Set(), // Not an array but Set to avoid duplicate paths,
textReplacements: new Map(), // This is where you will have file text replacements
supportedFormats: ['.docx', '.txt'] // I took a step further to include supported formats
}
With this data structure, you have all the variables required to apply text replacements to the content in a file.
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 interesting projects. 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/@ramu-narasinga
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
Conclusion:
Using the right data structure matters. To pick the right data structure, context matters. An Object with Set and Map in Javascript, I found it unique in the wild (well, it’s Next.js source code).
I tend to use separate variables rather than defining an Object to consolidate Map and Set. If I were to mix these data structures in a single object, I would think twice about the context. One example I could think of is shown below: