JavaScript Kata: Writing Higher Order Functions or Callbacks in JavaScript.


 
BY indefiniteloop


A great kata on getting to understand higher order functions or callbacks in JavaScript. Callbacks are really simple to understand, and implement.

Problem Statement: Write a higher order function that will take in another function, and an integer ‘n’ as an argument. This function will return a function that would run the function supplied as argument, ‘n’ number of times on the returned result(s).

This kata may seem simple at first, but does take some understanding of callbacks to solve.

Test Cases & Kata.

Python Kata: Finding The Next Perfect Square, Given A Previous One.
JavaScript Kata: Writing Higher Order Functions or Callbacks in JavaScript.

View Kata & Test Cases

Here’s how I solved it

var createIterator = function (func, n) {
    return (j)=>{for(i=n;i>0;i--) j = func(j);return j;};
};

var getDouble = function (n) {
      return n + n;};

var doubleIterator = createIterator(getDouble, 3);
console.log(doubleIterator(4));

Read about Higher order functions in JavaScript, and Arrow Functions.

Other Solution(s)

This one’s by Azuaron (and other people).

var createIterator = function (func, n) {
  return function(v) {
    for(var i = 0; i < n; i++) v = func(v);
    return v;
  };
};

Here’s another interesting solution by nabi

var createIterator = function (func, n) {
  var it=function(v){
    [...Array(n)].forEach(()=>v=func(v));
    return v;
  };
  return it;
};

Higher Order Functions

Higher Order Functions or callbacks are relatively easy to understand, once you have firm foundation of functions in general. Using them correctly reduces the size of code dramatically, and in some cases reduces complexity. A simple, small program is good for debugging, and for building up upon. They also provide abstractions where necessary. Read more about Higher order functions in javascript.

Solve This Kata




About The Author:

Home Full Bio