No one likes those big articles - that’s why we’re creating Quick Tips - short tips to change your developer's life from the moment you read them.
Those may be some patterns explained in JS code on real-life examples or some techniques for better code.
Imagine you have input like in Google Maps where you can enter some value about a location.
This value can be:
- City/Country/State... (Google API)
- Coordinates in different formats (https://www.npmjs.com/package/coordinate-parser)
How to unify different interfaces?
We can create a scalable solution using the Adapter pattern and create an abstraction layer over every parser to unify interfaces.
Note: Please have in mind the presented code is only for presentation purposes, so it may be "unfinished" (e.g. input without debounce).
We can create parsers where each function takes a value as a string and returns the same lat/lon object.
As we can see, we've created 2 adapters for each parser. No matter what interface the parser has, we always unify the end result to the same lat/lon object.
Now we can just run through each parser and see.
This way we could scale up our solution to add as many parsers as we would like without complicating our code. We can also easily swap or remove parsers.
When to use it?
Whenever you'd like to combine different interfaces.
This would also be relevant if you would like to integrate some old module with a new interface.
Imagine a scenario where you’re refactoring your code to a new interface and you have several modules that you don't want to touch, but you want them to work with your new pure module.
You can just create an adapter for your old module to fit your new module interface.
Check out this website: