闭包 - 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

以上就是闭包 - JavaScript 挑战的详细内容,更多请关注其它相关文章!