[JS] Useful functons and snippets
Find average product price
const products = [
{
id: "id1",
year: 2017
},
{
id: "id2",
year: 2018
},
{
id: "id3",
year: 2019
}
];
const accountActions = [
{
productId: "id1",
costPerProduct: 3.5
},
{
productId: "id1",
costPerProduct: 6.5
},
{
productId: "id1",
costPerProduct: 16.5
},
{
id: "id3",
costPerProduct: 6.5
}
];
const result = products.map(product => {
let actionsArr = accountActions.filter(action => {
return action.productId === product.id;
});
if (actionsArr.length > 0) {
let costPerProductArr = actionsArr.map(action => action.costPerProduct);
let sum = costPerProductArr.reduce((a, b) => a + b);
let averagePrice = sum / costPerProductArr.length;
product.averagePrice = parseFloat(averagePrice.toFixed(2));
} else {
product.averagePrice = 0;
}
return product;
});
console.log(JSON.stringify(result, null, 2));
Check if a value is an integer
function isInteger(num) {
if (!Number.isInteger(Number(num))) {
throw new Error(`${num} is not an integer`);
}
return true;
}