Converting function with logic and ui into higher order functions

Viewed 95

I'm trying to improve my JavaScript skills. I'm learning composability and functional patterns and I'm totally lost.

I have two functions: one mapping an array and the other called from within the previous function to generate the markup.

const names = ['peter', 'paul', 'patrice']

const namesMarkup = name => {
  return `<p>${name}</p>`
}

const showNames = listOfNames => {
  return listOfNames.map(el => {
    return namesMarkup(el)
  })
}

showNames(names)

I have been reading about HOF, which technically are functions that take a function as an argument and/or return a function. How could I compose these functions to have a HOF?

I went through the basic examples like

const square = num => num * num

const plus10 = (num, callback) => {
  return callback(num) + 10
}

console.log(addTwo(7, square))

but I cannot make my mind around the previous example and working with lists. I will appreciate help since the more I research the more confused I get.

1 Answers

Your mistake is to assume an array for showNames. Never do this. Always implement the simplest version of a function. In FP array is a computational effect. Don't implement such an effectful function as default:

const nameMarkup = name => {
  return `<p>${name}</p>`;
}

const nameMarkup2 = name => {
  return `<p>${name.toUpperCase()}!</p>`;
}

const showName = f => name => {
  const r = f(name);
  /* do something useful with r */
  return r;
}

const names = ['peter', 'paul', 'patrice']

console.log(
  showName(nameMarkup) ("peter"));

// lift the HOF if you want to process a non-deterministic number of names:

console.log(
  names.map(showName(nameMarkup2)));

Now swapping the markup just means to pass another function argument. Your showName is more general, because a HOF lets you pass part of the functionality.

If we drop the array requirement, your showNames doesn't do anything useful anymore. It still illustrates the underlying idea, though.

Related