简体   繁体   中英

Creating and filling an object in two separate functions or in a single one?

I've encountered this problem many times. The problem is that I have an array of elements that consist of a key and a value and I need to reduce the array to an object with the keys and the sum of values for each key (eg ["foo", 1], ["bar", 1], ["foo", 1] becomes {foo: 2, bar: 1} ). Is it better to first initialize the object with all the keys set to 0 and then use that object or use an empty object and check if the property exists every time?

function juiceMapFromFormat(format) {
    return format
        .map(juiceString=>{
            const [juiceName, quantityString] = juiceString.split(/\s*=>\s*/gim);
            const quantity = +quantityString;

            return [juiceName, quantity];
        })
        .reduce((juiceMap, juiceArr)=>{
            const [juiceName, quantity] = juiceArr;
            const previousQuantity = juiceMap.get(juiceName) || 0;

            if (previousQuantity < 1000) {
                juiceMap.delete(juiceName);
            }
            juiceMap.set(juiceName, previousQuantity + quantity);

            return juiceMap;
        }, new Map());
}

This is my current function. My example uses a map, but it's because of the problem. My question is for both maps and objects. I have two conditions - does the property exist and is the quantity smaller than 1000. The second condition is because of the problem I'm solving. My question is whether it's better to leave it like that or to save the array of juice arrays in a constant and use it to initialize a Map with every single juice name and give that map to the reduce method as initial value, this way removing the need for || 0 after juiceMap.get(juiceName). Which would be better?

Edit: The function takes a array of strings, which are mapped correctly. I need to return a map. My question is if I should keep the 2 conditions or remove the one checking for the existence of the property and make sure that every property exists by initializing every property to 0 beforehand.

Edit 2: If I initialize all properties beforehand, I will reduce the cyclomatic complexity as the condition will be removed. That's at least how I understand it.

I would take a single loop ad reduce the data directly.

function juiceMapFromFormat(format) {
    return format.reduce((juiceMap, juiceString) => {
        const [juiceName, quantityString] = juiceString.split(/\s*=>\s*/gim);
        return juiceMap.set(juiceName, (juiceMap.get(juiceName) || 0) + +quantityString);
    }, new Map());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM