[] JavaScript |
function doSomething() {
const a = doSomethingElse()
const b = doSomethingWithA(a)
const otherResults = { c: '', d: '' }
return { a, b, ...otherResults } // equivalent to { a: a, b: b }
}
const { a, c, ...rest } = doSomething() // Also works with arrays!
// `rest` looks like { b: ..., d: '' }
// Please try to write the same code with classic promises ;)
async function doSomething() {
const a = await getValueForA()
const b = await getValueForBFromA(a)
const [c, d] = await Promise.all([
// parallel execution
getValueForC(), getValueForDFromB(b)
])
const total = await calculateTotal(a, b, c, d)
return total / 1000
}
const arr = [{ name: 'first', value: 13 }, { name: 'second', value: 7 }]
// Instead of:
const res = {}
for (let i = 0; i < arr.length; i++) {
const calculatedValue = arr[i].value * 10
if (calculatedValue > 100) {
res[arr[i].name] = calculatedValue
}
}
// Prefer:
const res = arr
.map(elem => ({ name: elem.name, calculatedValue: elem.value * 10 }))
.filter(elem => elem.calculatedValue > 100)
.reduce((acc, elem) => ({
[elem.name]: calculatedValue,
...acc
}), {})
const enrichElementWithCalculatedValue =
elem => ({ name: elem.name, calculatedValue: elem.value * 10 })
const filterElementsByValue = value =>
elem => elem.calculatedValue > value
const aggregateElementInObject = (acc, elem) => ({
[elem.name]: calculatedValue,
...acc
})
const res = arr
.map(enrichElementWithCalculatedValue)
.filter(filterElementsByValue(100))
.reduce(aggregateElementInObject, {})