lundi 15 juillet 2019

refactoring if else statement to use Ramda.js & breaking down key value pairs into object records

I would like to transform the below reducer function to use ramda. instead of using the JS if else statement, how could I do this using R.ifElse()

var groupAndSumBy = (objKey) => 
    R.reduce(function(acc, val){
                var accKey = val[objKey]
                acc = Object.assign({}, acc)
                if ( acc.hasOwnProperty(accKey) ){
                    acc[accKey] = acc[accKey] + totalInvoice(val)
                } else {
                    acc[accKey] = totalInvoice(val)
                }
                return acc
}, {})

var sumByCountry = groupAndSumBy("MARKET")

var vals =[
    {
        "COUNTRY": "AUSTRIA",
        "TYPE": "SERVICES",
        "AMT1": 2555.05,
        "AMT2": 2686.48,
        "AMT3": 2805.1,
        "AMT4": 2732.23
    },
    {
        "COUNTRY": "GERMANY",
        "TYPE": "SERVICES",
        "AMT1": 2555.05,
        "AMT2": 2686.48,
        "AMT3": 2805.1,
        "AMT4": 2732.23
    },
    {
        "COUNTRY": "UK",
        "TYPE": "SERVICES",
        "AMT1": 2555.05,
        "AMT2": 2686.48,
        "AMT3": 2805.1,
        "AMT4": 2732.23
    },
]

the function in its current form is more imperative with the if else statement. I would like to replace this with ramda.ifElse()

the desired output is as follows

sumByCountry(vals)

{
    'AUSTRIA': 10778.86,
    'GERMANY': 10777.86,
    'UK': 10777.86,
}

additionally, I would like to break the desired output above into separate records, which I haven't been able to achieve with ramda.

[
    {index:'AUSTRIA', value: 10777.86},
    {index:'GERMANY', value: 10777.86},
    {index:'UK', value: 10777.86}
]

Aucun commentaire:

Enregistrer un commentaire