JavaScript 实现高阶函数 combinedFetcher

发布于 2023-03-13 23:11:59 字数 942 浏览 67 评论 0

问题描述

A fetcher is

function fetcher(arg, cb){
    let res = fetch(arg);
    cb(res);
}

Write a higher-order function combinedFetcher, using callback to get all the fetched data.

const fetchFruitsAndDrinks = combinedFetcher("fruits", "drinks");
fetchFruitsAndDrinks(console.log);

参考实现

这其实是一道互联网大厂的面试真题,笔者也碰到过。

function fetch(arg) {
  return `response with: ${arg}`;
}
function fetcher(arg, cb){
    let res = fetch(arg);
    cb(res);
}
function combinedFetcher(...args) {
  const len = args.length;
  let cnt = 0;
  const res  = [];
  function innerCB(r, cb) {
    cnt++;
    res.push(r)
    if(cnt === len) cb(res);
  }

  return cb => args.forEach(arg => fetcher(arg, r => innerCB(r, cb)));
}

const fetchFruitsAndDrinks = combinedFetcher("fruits", "drinks");
fetchFruitsAndDrinks(console.log)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

北方的巷

暂无简介

文章
评论
27 人气
更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文