DEV Community

Discussion on: Human Readable JavaScript

Collapse
 
puiutucutu profile image
puiu • Edited

The default behaviour of Array.map is unintuitive given that it returns the index and the original array as the second and third arguments to the callback function respectively.

I would approach the parseInt problem by writing a map function that takes two args, supplied one at a time (to facilitate partial application).

  • the first arg, a function f that will be supplied only one value at a time, that is, the current iterated value
  • the second arg, a 1-dimensional array of values to apply the function f on

It may appear complicated seeing it for the first time, but come back to the example and mull it over and it will start to click.

/* 
// alternative map implementation
const mapAlt = f => xs => Array.prototype.map.call(xs, currentValue => f (currentValue));


// unterse
function map(f) {
  return function(xs) {
    return xs.map(function(currentValue, index, originalArray) {
      return f(currentValue);
    });
  };
}
*/

const map = f => xs => xs.map(function(currentValue, index, originalArray) {
  return f (currentValue);
});


const xs = [1, 2, 3, 4];
const multiplier = x => x * 6;
const multiplied = map (multiplier) (xs);

const ys = ["1", "2", "3", "4"];
const parser = x => parseInt(x);
const parsed = map (parser) (ys);

console.log("xs:", xs); //=> [1, 2, 3, 4]
console.log("xs multiplied:", multiplied); //=> [6, 12, 18, 24]
console.log("ys:", ys); //=> ["1", "2", "3", "4"]
console.log("ys parsed:", parsed); //=> [1, 2, 3, 4]
Thread Thread
 
crosseye profile image
Scott Sauyet

But why include index and originalArray parameters when you don't use them?

For that matter, why not make this point-free?

const map = (f) => (xs) => xs .map ((x) => f(x))

(... and around in circles we go!)

Thread Thread
 
puiutucutu profile image
puiu

That's true, they are superfluous - I left those other args there to make it clearer how the args are moving around.