【30秒一个知识点】Adapter(二)

时间:2022-06-21
本文章向大家介绍【30秒一个知识点】Adapter(二),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

本系列翻译自开源项目 30-seconds-of-code 这是一个非常优秀的系列,不是说真的三十秒就能理解,也需要你认真的思考,其中有一些点非常精妙,很值得一读。 本文在我的github同步更新,点击文章末尾阅读全文你可以看到当前翻译的全部系列。

overArgs

创建一个函数,它可以调用提供的被转换参数的函数。

使用 Array.prototype.map()transforms应用于 args,并结合扩展运算符( )将转换后的参数传递给 fn

const overArgs = (fn, transforms) => (...args) => fn(...args.map((val, i) => transforms[i](val)));

示例

const square = n => n * n;
const double = n => n * 2;
const fn = overArgs((x, y) => [x, y], [square, double]);
fn(9, 3); // [81, 6]

pipeAsyncFunctions

为异步函数执行从左到右的函数组合。

在扩展操作符( )中使用 Array.prototype.reduce()来使用 Promise.then()执行从左到右的函数组合。 这些函数可以返回简单值、 Promise的组合,也可以定义为通过 await返回的 async值。 所有函数必须是一元的。

const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg));

示例

const sum = pipeAsyncFunctions(
  x => x + 1,
  x => new Promise(resolve => setTimeout(() => resolve(x + 2), 1000)),
  x => x + 3,
  async x => (await x) + 4
);
(async() => {
  console.log(await sum(5)); // 15 (after one second)
})();

pipeFunctions

执行从左到右的函数组合。

在展开操作符( )中使用 Array.prototype.reduce()来执行从左到右的函数组合。 第一个(最左边的)函数可以接受一个或多个参数; 其余的函数必须是一元的。

const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));

示例

const add5 = x => x + 5;
const multiply = (x, y) => x * y;
const multiplyAndAdd5 = pipeFunctions(multiply, add5);
multiplyAndAdd5(5, 2); // 15

promisify

把一个异步函数转换成返回promise的。

使用局部套用返回一个函数,该函数返回一个调用原始函数的 Promise。 使用的 ...操作符来传入所有参数。

const promisify = func => (...args) =>
  new Promise((resolve, reject) =>
    func(...args, (err, result) => (err ? reject(err) : resolve(result)))
  );

示例

const delay = promisify((d, cb) => setTimeout(cb, d));
delay(2000).then(() => console.log('Hi!')); // Promise resolves after 2s

rearg

创建一个调用提供的函数的函数,该函数的参数按照指定的索引排列。

利用 Array.prototype.map() 根据 indexes 和展开操作符 ( ...) 对参数进行重新排序,将转换后的参数传递给 fn.

const rearg = (fn, indexes) => (...args) => fn(...indexes.map(i => args[i]));

示例

var rearged = rearg(
  function(a, b, c) {
    return [a, b, c];
  },
  [2, 0, 1]
);
rearged('b', 'c', 'a'); // ['a', 'b', 'c']