Skip to content

Instantly share code, notes, and snippets.

@ivankisyov
Last active December 1, 2018 10:55
Show Gist options
  • Save ivankisyov/ebb5930e367ac17783b769c3e214b744 to your computer and use it in GitHub Desktop.
Save ivankisyov/ebb5930e367ac17783b769c3e214b744 to your computer and use it in GitHub Desktop.
[JS] Useful Snippets

[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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment