当前位置:首页 > 文章列表 > 文章 > 前端 > 闭包 - JavaScript 挑战

闭包 - JavaScript 挑战

来源:dev.to 2024-11-10 11:54:42 0浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习文章相关编程知识。下面本篇文章就来带大家聊聊《闭包 - JavaScript 挑战》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!

闭包 - JavaScript 挑战

您可以在 repo github 上找到这篇文章中的所有代码。


关闭相关的挑战


你好世界

/**
 * @return {function}
 */

function createhelloworld() {
  return function (...args) {
    return "hello world";
  };
}

// usage example
const output = createhelloworld();
console.log(output()); // => "hello world"

添加

/**
 * @param  {...any} args
 * @return {function | number}
 */

function add(...args) {
  let sum = args.reduce((acc, val) => acc + val, 0);

  function inneradd(...moreargs) {
    sum += moreargs.reduce((acc, val) => acc + val, 0);
    return inneradd;
  }
  inneradd.getvalue = function () {
    return sum;
  };

  return inneradd;
}

// usage example
console.log(add(1).getvalue()); // => 1
console.log(add(1)(2).getvalue()); // => 3
console.log(add(1)(2)(3).getvalue()); // => 6
console.log(add(1)(2, 3).getvalue()); // => 6
console.log(add(1, 2)(3).getvalue()); // => 6
console.log(add(1, 2, 3).getvalue()); // => 6

/**
 * @param {number} num
 */

function sum(num) {
  const func = function (num2) {
    return num2 ? sum(num + num2) : num;
  };

  func.valueof = () => num;
  return func;
}

// usage example
const sum1 = sum(1);
console.log(sum1(2) == 3); // => true
console.log(sum1(3) == 4); // => true
console.log(sum(1)(2)(3) == 6); // => true
console.log(sum(5)(-1)(2) == 6); // => true


柜台

/**
 * @param {number} initialvalue
 * @return {function}
 */

function makecounter(initialvalue = 0) {
  let count = initialvalue - 1;

  return function (...args) {
    count += 1;
    return count;
  };
}

// usage example
const counter = makecounter(0);
console.log(counter()); // => 0
console.log(counter()); // => 1
console.log(counter()); // => 2

//------------------------------
// return an object
/**
 * @param {number} initialvalue
 * @return {{get: function, increment: function, decrement: function, reset: function }}
 */
function makecounter(initialvalue = 0) {
  let count = initialvalue;

  return {
    get: () => count,
    increment: () => ++count,
    decrement: () => --count,
    reset: () => (count = initialvalue),
  };
}

// usage example
const counterobj = makecounter(0);
console.log(counterobj.get()); // => 0
counterobj.increment();
console.log(counterobj.get()); // => 1
counterobj.decrement();
counterobj.reset();
console.log(counterobj.get()); // => 0

循环

/**
 * @template t
 * @param  {...t} values
 * @returns () => t
 */

function cycle(...values) {
  let index = -1;

  return function (...args) {
    index = (index + 1) % values.length;
    return values[index];
  };
}

// usage example
const hellofn = cycle("hello");
console.log(hellofn()); // => "hello"
console.log(hellofn()); // => "hello"

const onofffn = cycle("on", "off");
console.log(onofffn()); // => "on"
console.log(onofffn()); // => "off"
console.log(onofffn()); // => "on"

限制

/**
 * @param {function} func
 * @param {number} count
 * @return {function}
 */

function limit(fn, max) {
  let count = 0;
  let value;

  return function (...args) {
    if (count < max) {
      value = fn.call(this, ...args);
      count++;
    }

    return value;
  };
}

// usage example
let i = 1;
function incrementby(value) {
  i += value;
  return i;
}

const incrementbyatmostthrice = limit(incrementby, 3);
console.log(incrementbyatmostthrice(2)); // i is now 3; the function returns 3.
console.log(incrementbyatmostthrice(3)); // i is now 6; the function returns 6.
console.log(incrementbyatmostthrice(4)); // i is now 10; the function returns 10.
console.log(incrementbyatmostthrice(5)); // i is still 10 as this is the 4th invocation; the function returns 10 as it's the result of the last invocation.
i = 4;
console.log(incrementbyatmostthrice(2)); // i is still 4 as it is not modified. the function still returns 10.

一次

/**
 * @param {function} fn
 * @return {function}
 */

function once(fn) {
  let ranonce = false;
  let value;

  return function (...args) {
    if (!ranonce) {
      value = fn.call(this, ...args);
      ranonce = true;
    }

    return value;
  };
}

// usage example
function func(num) {
  return num;
}

const onced = once(func);
console.log(onced(1)); // => 1, func called with 1
console.log(onced(2)); // => 1, even 2 is passed, previous result is returned

存在或不存在

/**
 * @param {any} val
 * @return {true | Error}
 */

function expect(val) {
  return {
    toBe: function (arg) {
      if (val === arg) {
        return true;
      } else {
        throw new Error("Not Equal");
      }
    },
    notToBe: function (arg) {
      if (val !== arg) {
        return true;
      } else {
        throw new Error("Equal");
      }
    },
  };
}

// Usage example
expect(5).toBe(5); // Passes
expect(5).notToBe(6); // Passes

try {
  expect(5).toBe(6); // Throws an error
} catch (error) {
  console.log(error.message); // Not Equal
}

参考

  • 148。创建一个计数器对象 - bfe.dev
  • 2620。计数器 - leetcode
  • 2665。计数器 ii - leetcode
  • 2665。计数器 ii - leetcode
  • 伟大的前端
  • 2667。创建 hello world 函数 - leetcode
  • 23。创建 sum() - bfe.dev
  • 46。实现 _.once() - bfe.dev
  • 2704。生存还是毁灭 - bfe.dev
  • 161。 tobe() 或 not.tobe() - bfe.dev
  • “你好世界!”程序 - wikipedia.org

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于文章的相关知识,也可关注golang学习网公众号。

版本声明
本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
通过记忆化提高 React 应用程序的性能:探索 useMemo、useCallback 和 Reactmemo通过记忆化提高 React 应用程序的性能:探索 useMemo、useCallback 和 Reactmemo
上一篇
通过记忆化提高 React 应用程序的性能:探索 useMemo、useCallback 和 Reactmemo
如何选择适合你的4K显示器
下一篇
如何选择适合你的4K显示器
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    542次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    511次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    498次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    484次学习
查看更多
AI推荐
  • AI边界平台:智能对话、写作、画图,一站式解决方案
    边界AI平台
    探索AI边界平台,领先的智能AI对话、写作与画图生成工具。高效便捷,满足多样化需求。立即体验!
    418次使用
  • 讯飞AI大学堂免费AI认证证书:大模型工程师认证,提升您的职场竞争力
    免费AI认证证书
    科大讯飞AI大学堂推出免费大模型工程师认证,助力您掌握AI技能,提升职场竞争力。体系化学习,实战项目,权威认证,助您成为企业级大模型应用人才。
    424次使用
  • 茅茅虫AIGC检测:精准识别AI生成内容,保障学术诚信
    茅茅虫AIGC检测
    茅茅虫AIGC检测,湖南茅茅虫科技有限公司倾力打造,运用NLP技术精准识别AI生成文本,提供论文、专著等学术文本的AIGC检测服务。支持多种格式,生成可视化报告,保障您的学术诚信和内容质量。
    561次使用
  • 赛林匹克平台:科技赛事聚合,赋能AI、算力、量子计算创新
    赛林匹克平台(Challympics)
    探索赛林匹克平台Challympics,一个聚焦人工智能、算力算法、量子计算等前沿技术的赛事聚合平台。连接产学研用,助力科技创新与产业升级。
    662次使用
  • SEO  笔格AIPPT:AI智能PPT制作,免费生成,高效演示
    笔格AIPPT
    SEO 笔格AIPPT是135编辑器推出的AI智能PPT制作平台,依托DeepSeek大模型,实现智能大纲生成、一键PPT生成、AI文字优化、图像生成等功能。免费试用,提升PPT制作效率,适用于商务演示、教育培训等多种场景。
    569次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码