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.
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: