I have been shifting towards functional programming over imperative programming recently.
Imagine I have a nested array data structure and my goal is to update the values of the innermost arrays. What approach would be most effective?
Here is the imperative code for transformation:
for (let i = 0; i < dataSheet.length; i++) {
for (let j = 0; j < dataSheet[i].questions.length; j++) {
for (let k = 0; k < dataSheet[i].questions[j].answers.length; k++) {
dataSheet[i].questions[j].answers[k].name += ' (edited name)';
dataSheet[i].questions[j].answers[k].value = 1 + dataSheet[i].questions[j].answers[k].value / 10;
}
}
}
I've devised two methods for achieving this:
Using map():
dataSheet
.map(section => section.questions
.map(question => question.answers
.map(answer => (
{
...answer,
name: answer.name + ' (edited name)',
value: 1 + (answer.y / 10),
}),
),
),
);
Using forEach():
dataSheet.forEach(section => section.questions
.forEach(question => question.answers
.forEach(answer => (
{
...answer,
name: answer.name + ' (edited name)',
value: 1 + (answer.y / 10),
}),
),
),
);
All three achieve the same result, but none of them seem significantly better. The pyramid-like structure in both functional approaches doesn't enhance readability. The situation could worsen with additional levels of nesting.
Transitioning from imperative to functional programming does not offer clarity or maintainability improvement in this case. Moreover, performance might suffer as each object modification creates a new copy.
In this scenario, do you believe sticking with imperative coding is preferable? Or is there an alternative method that could work better?