Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save matteo-bombelli/06e88f708e4c945b9c6f648df595a902 to your computer and use it in GitHub Desktop.
Save matteo-bombelli/06e88f708e4c945b9c6f648df595a902 to your computer and use it in GitHub Desktop.

After a simple discussion on twitter I've taken what I've always done to try to improve legibility:

std code:

const data = {
    a: "something",
    b: "something else",
    c: "others"
}

const helperfunction = (input)=>{
    /** do something with the code */
    const result = `${input} to result` 
    return result
}

const resultingData = Object
    .keys(data)
    .map((key)=>({
        key:key, 
        value:helperfunction(data[key])
    }))
    .reduce((acc, {key, value})=>({
        ...acc,
        [key]:value
    }), {})

since seems that reduce is not readable I've tried a better solution

const data = {
    a: "something",
    b: "something else",
    c: "others"
}

const helperfunction = (input)=>{
    /** do something with the code */
    const result = `${input} to result` 
    return result
}

const applyHelperFunctionToPlainObject = (elements)=>{
    var result = {}
    for (key in elements){
        result[key]= helperfunction(elements[key])
    }
    return result;
}

const resultingData = applyHelperFunctionToPlainObject(data)

This seems to be much better faster and simplier) but this has na issue: I need to know how to NAME the function :)

Another way

const data = {
    a: "something",
    b: "something else",
    c: "others"
}

const helperfunction = (input)=>{
    /** do something with the code */
    const result = `${input} to result` 
    return result
}

const resultingData = Object
    .fromEntries(
        Object
            .entries(data)
            .map(([key, value])=>([
                key, 
                helperfunction(value)
            ]))
    )

this way is faster than version 1 but less faster than version 2 but has no issue related to naming things :)

I don't know if it is simplier

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment