Answer the question
In order to leave comments, you need to log in
Which one is better for functional JS programming?
Which one is better for functional JavaScript programming?
Option 1.
function formatData(array, callBack) {
let formatted = array.map(/* formatting */)
callBack(formatted)
}
formatData(peoples, (result) => {
console.log(result)
})
function formatData(array) {
return array.map(/* formatting */)
}
console.log(formatData(peoples))
Answer the question
In order to leave comments, you need to log in
To see the benefits of a functional approach, it's better to write the example in a slightly different way. Now you generally don’t have anything functional there (the presence of functions !== FP):
function formatter(item) {
return "0" + item.toString();
}
function validator(number) {
if (typeof number !== "number") {
throw new Error("invalid argument: Number expected");
}
return number;
}
function formatData(array, formatter, validator) {
return array.map(item => formatter(validator(item)));
}
alert(formatData([1, 2, 3], formatter, validator));
Closest to the OP will be the third option:
function formatData(element) {
return formattedElement;
}
const formattedData = peoples.map(formatData);
console.log(formattedData)
Second option. It's called the interesting word currying. And it looks nice and there is less code.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question