登录
首页 >  文章 >  前端

闭包 - JavaScript 挑战

来源:dev.to

时间:2024-11-10 11:54:42 251浏览 收藏

来到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删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>