JSFiddle - React, Tailwind, and code Playground
by Scott Kaye
JavaScript
function CARSCORE(carValues, weights) {
carValues = carValues[0];
weights = weights[0];
const scores = carValues.map((car, i) => {
let rawWeight = weights[i];
let weight = rawWeight;
if (typeof car === "number") {
return {
weight,
score: car
};
}
if (typeof rawWeight === "string") {
if (rawWeight.length === 0) {
return {
weight,
score: 0
};
}
weight = +rawWeight.match(/^(\d+)=/)[1];
}
if (typeof car === "string") {
if (car === "Yes" || car === "No") {
switch (car) {
case "Yes":
return {
weight, score: weight
};
case "No":
return {
weight, score: 0
};
}
}
if (car.length === 0) {
return {
weight,
score: 0
};
}
let possibleScores = rawWeight.match(/(\w+:\d+)/g).reduce((a, c) => ({
...a,
[c.match(/\w+/)[0]]: +c.match(/:(\d+)/)[1]
}), {});
let score = Object.keys(possibleScores).reduce((a, c) => {
if (car.includes(c)) {
return a + possibleScores[c];
}
return a;
}, 0);
return {
weight,
score
};
}
});
let sumOfWeights = scores.reduce((a, c) => a + c.weight, 0);
let sumOfProducts = scores.reduce((a, c) => a + c.weight * c.score, 0);
let score = sumOfProducts / sumOfWeights;
return score;
}
console.log(CARSCORE([[35000,
2017,
210,
258,
'2.0L I4',
'Turbo',
4,
'FWD',
'Yes',
'DSG',
'Luxury',
'Yes',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
''
]], [[-10,
1,
4,
5,
'7=I4:1,V8:5,V6:4,I5:5',
'3=Turbo:2,NA:3,Supercharged:2',
7,
'5=FWD:3,AWD:7,RWD:5',
3,
'6=DSG:5,Manual:3,TC:3,ZF:5',
'4=Luxury:2,Sport:3',
7,
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
''
]]))