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.

Object with Map and Set

Skimming through the code around this function, I quickly learnt that it is used for Telemetry tracking purposes.

Learn the best practices used in open source

telemetry usage

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 = { // Not an array but Set to avoid duplicate paths paths: new Set(), // This is where you will have file text replacements textReplacements: new Map(), // I took a step further to include supported formats supportedFormats: \['.docx', '.txt'\] }
Enter fullscreen mode
Exit fullscreen mode

With this data structure, you have all the variables required to apply text replacements to the content in a file.

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:

let fileCustomisations = { // Not an array but Set to avoid duplicate paths paths: new Set(), // This is where you will have file text replacements textReplacements: new Map(), // I took a step further to include supported formats supportedFormats: \['.docx', '.txt'\] }
Enter fullscreen mode
Exit fullscreen mode

Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top