U
U
Urukhayy2017-08-25 15:43:12
JavaScript
Urukhayy, 2017-08-25 15:43:12

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)
})

Option 2.
function formatData(array) {
   return array.map(/*   formatting  */)
}


console.log(formatData(peoples))

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Strukov, 2017-08-25
@Urukhayy

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));

PS: you can get confused and design more universal functions, but as an example it will do)

A
abberati, 2017-08-25
@abberati

Closest to the OP will be the third option:

function formatData(element) {
  return formattedElement;
}

const formattedData = peoples.map(formatData);
console.log(formattedData)

R
Roman Alexandrovich, 2017-08-25
@RomReed

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 question

Ask a Question

731 491 924 answers to any question