in JS I have an array of items, every item has this form:
{
id: 'fa4da51',
name: 'product-name',
prettyName: 'Product Name',
price: null,
}
I run map on the array and then return item.price
to display the price of every item.
Some of the items I'm getting from external API have no prices (price
set to null
). The items in API won't change in the future, the ids might, but not names.
I came up with an idea that if !item.price
then let's show the fallback price for given item.
What would be the best approach to get what I want?
I've been thinking about creating a Map for every item (just in case) like so:
var itemPrices = new Map([
['product-name', 100],
['product-name-2', 200],
['product-name-3', 300],
]);
And then doing: item.price ?? item.price || itemPrices[item.name]
.
Is this a good approach for about 5000 items? Out of those roughly 1500 have no prices. Can I tweak it somehow to make it more performant? Does the thing I want to achieve have some kind of standardised name so I could Google it? The man responsible for the API is on a really long sick leave and I have to hotfix this without access to the back-end.
Thank you for any hints.
CodePudding user response:
I would make your code a little bit better, but yes would stick with a hashmap
var fallbackPrices = {
'fa4da51': 100,
'f4f8b1a': 200,
'f9sd41d': 300,
};
function getFallbackPrice(item) {
return fallbackPrices[item.id];
}
function getPrice(item) {
return item.price != null ? item.price : getFallbackPrice(item);
}
// Example usage
var items = [
{
id: 'fa4da51',
name: 'product-name',
prettyName: 'Product Name',
price: null,
},
{
id: 'f4f8b1a',
name: 'product-name-2',
prettyName: 'Product Name 2',
price: null,
},
{
id: 'f9sd41d',
name: 'product-name-3',
prettyName: 'Product Name 3',
price: 50,
},
];
items.map((item) => {
getPrice(item)
});