Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const products = [
- { name: 'A', group: 'G1', cost: 20.1 },
- { name: 'B', group: 'G2', cost: 98.4 },
- { name: 'C', group: 'G1', cost: 49.7 },
- { name: 'D', group: 'G3', cost: 35.8 },
- { name: 'E', group: 'G3', cost: 105.5 },
- { name: 'F', group: 'G1', cost: 55.2 },
- { name: 'G', group: 'G3', cost: 12.7 },
- { name: 'H', group: 'G1', cost: 88.6 },
- { name: 'I', group: 'G2', cost: 5.2 },
- { name: 'J', group: 'G2', cost: 15.3 },
- ];
- const categories = [
- { name: 'C1', from: 0, to: 25 },
- { name: 'C2', from: 25, to: 50 },
- { name: 'C3', from: 50, to: 75 },
- { name: 'C4', from: 75, to: 100 },
- { name: 'C5', from: 100, to: null },
- ];
- const margins = [
- { name: 'C1', margin: '20%' },
- { name: 'C2', margin: '30%' },
- { name: 'C3', margin: '0.4' },
- { name: 'C4', margin: '50%' },
- { name: 'C5', margin: '0.6' },
- ];
- const averageCalculator = name => {
- // Devuelve la categoría del producto
- const categoryFinder = product => categories.filter(item => product.cost >= item.from && product.cost < item.to);
- // Devuelve el margen de la categoría
- const marginFinder = category => margins.filter(item => category.name == item.name);
- // Filtra o selecciona los productos solicitados ejem: 'G1'
- const grouped = products.filter(item => item.group == name);
- // Crea un array con los precios calculados para el grupo seleccionado
- const costCollection = grouped.map(item => {
- const catValue = categoryFinder(item);
- const marValue = marginFinder(catValue[0]);
- margin = numParser(marValue[0].margin);
- return item.cost * (1 + margin);
- });
- // Suma el total de precios del grupo seleccionado
- const totalSum = costCollection.reduce((sum, value) => sum + value);
- // Retorna el promedio
- return totalSum / grouped.length;
- };
- const numParser = strNumber => {
- let number = strNumber;
- const size = number.length;
- // Expresiones Regulares
- const rxPercent = /%/;
- const rxDot = /\./;
- // Valida el stringNumber con las RegExp
- const withSymbol = rxPercent.test(number);
- const isFloat = rxDot.test(number);
- // Elimina el simbolo porcentaje %
- if (withSymbol) {
- number = number.substr(0, size - 1);
- }
- // retorna float si tiene punto o entero si no.
- return number = isFloat ? parseFloat(number) : parseInt(number);
- };
- console.log(averageCalculator('G1'));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement