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 = {
// 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'\]
}
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'\]
}
Get free courses inspired by the best practices used in open source.
About me:
Website: https://ramunarasinga.com/
Linkedin: https://www.linkedin.com/in/ramu-narasinga-189361128/
Github: https://github.com/Ramu-Narasinga
Email: ramu.narasinga@gmail.com
Top comments (0)