JSFiddle - React, Tailwind, and code Playground

by Jon-Carlos Rivera

JavaScript

// Temp cap
function sum (a, b) { return a + b; }

function sumProperty (arrayOfObjects, property){
	return _.reduce(_.pluck(arrayOfObjects, property), sum, 0);
}

function sumPropertyMap (propertyMap, arrayOfObjects) {
    var o = {};
    
    _.each(propertyMap, function(srcKey, dstKey) {
       o[dstKey] = sumProperty(arrayOfObjects, srcKey);
    });
    
    return o;
}

// Usage:

function test1(dates, deviceModel, sortKey) {
    // What I was using in the original function
    var propertyMap = {
        totalInchesPrinted: 'inchesPrinted'
    };
    var object = sumPropertyMap(propertyMap, deviceModel.devices);
    object.date = dates.datetime;
    object.deviceModel = deviceModel[sortKey];
    
    return object;
}
// versus

function test2(dates, deviceModel, sortKey){
    // Then on the duplicated function, I just removed totalInchesPrinted and added the 2 lines below
    var propertyMap = {
        totalRfidValid: 'odometerRfidValid',
        totalRfidVoid: 'odometerRfidVoid'
    };
    
    var object = sumPropertyMap(propertyMap, deviceModel.devices);
    object.date = dates.datetime;
    object.deviceModel = deviceModel[sortKey];
    
    return object;
}

var sampleData = {
    'bar': 'baz',
    devices:[
        {
            inchesPrinted: 10,
            odometerRfidValid: 2,
            odometerRfidVoid: 5
        },
        {
            inchesPrinted: 5,
            odometerRfidValid: 1,
            odometerRfidVoid: 8
        },
        {
            inchesPrinted: 8,
            odometerRfidValid: 3,
            odometerRfidVoid: 3
        }
    ]
};

console.log(test1({datetime: 'foo'}, sampleData, 'bar'));
console.log(test2({datetime: 'foo'}, sampleData, 'bar'));