Higher order functions

Functional Programming is powered by Higher-Order Functions in JavaScript.

// callback function
function x() {
	console.log('Hi everyone')
}

function y(x) {
	x();
}

For example, here is a way to DRY (Don´t repeat yourself) thanks to abstract the logic.

const radius = [3, 1, 2, 4];

const area = function(radius) {
	return Math.PI * radius * radius;
}

const circumference = function(radius) {
	return 2 * Math.PI * radius;
}

const calculate = function (radius, logic) {
	const output = [];
	for(let i = 0; i < radius.lenght; i++) {
		output.push(logic(radius[i]));
	}
	return output;
}

calculate() function is exactly similar to map() function and can give us the same result.

radius.map(area);

Another example to generate hexadecimal colors

function getRandomHex(min, max) {
  const range = max - min + 1;
  return (Math.floor(Math.random() * range) + min).toString(16).padStart(2, '0');
}

function generateHex(color) {
  if (color === 'red') {
    return getRandomHex(128, 255) + getRandomHex(0, 127) + getRandomHex(0, 127);
  } else if (color === 'green') {
    return getRandomHex(0, 127) + getRandomHex(128, 255) + getRandomHex(0, 127);
  } else if (color === 'blue') {
    return getRandomHex(0, 127) + getRandomHex(0, 127) + getRandomHex(128, 255);
  } else {
    return 'Invalid color';
  }
}
Powered by Forestry.md