ramda中的map适用于数组对象和字符串

Ramda’s map function is great for arrays.

  1. import { map, multiply } from 'ramda';
  2. const functor = [1, 2, 3];
  3. const result = map(multiply(2), functor);
  4. console.log({ result });
  5. { result: [ 2, 4, 6 ] }

But did you know it also works for objects?

  1. import { map, multiply } from 'ramda';
  2. const functor = { x: 1, y: 2, z: 3 };
  3. const result = map(multiply(2), functor);
  4. console.log({ result });
  5. { result: { x: 2, y: 4, z: 6 } }

And strings!

  1. import { concat, map } from 'ramda';
  2. const functor = 'Hello';
  3. const result = map(concat('yay'), functor);
  4. console.log({ result });
  5. { result: [ 'yayH', 'yaye', 'yayl', 'yayl', 'yayo' ] }

They can all be looped over and transformed, so map supports them!

带有“fantasy-land/map”方法的函子会覆盖Ramda的map方法并且可以返回任何值

You can even override map by defining a special method.

  1. import { map, multiply } from 'ramda';
  2. const functor = {
  3. value: 10,
  4. 'fantasy-land/map': () => 'You have been overridden!'
  5. };
  6. const result = map(multiply(2), functor);
  7. console.log({ result });

Notice map ignored multiply(2) and went straight to the override function. This is because it looks out for functors with the fantasy-land/map method.
Defining this method means “Give me full control of the mapping function”. Whatever it returns will be used.

Fantasy Land…? #

Yep. This is a specification for using functors and their friends in JavaScript. Definitely beyond the scope of this course, but useful background info.

Summary #

  • Ramda’s map works with arrays, objects, and strings.
  • Functors with a fantasy-land/map method can override map and return whatever.

    Who Cares? #

    The next topic, lenses, employ this strategy to a great extent. Without map’s override capabilities, lenses would need a big refactoring.