2021-10-27 Javascript悟道

2021-10-27  本文已影响0人  rub1cky

reduce

当你传入一个初始值的时候,reduce函数会为你遍历数组中的每一个元素;而当你不传初始值的时候,reduce则会拿第零个元素作为初始值,从第一个元素开始遍历

sort

function refine(collection, path) {
  return path.reduce(function (refinement, element) {
    try {
      return refinement[element];
    } catch (error) {}
  }, collection);
}

const by = (...keys) => {
  const paths = keys.map((item) => item.toString().split("."));

  return (first, second) => {
    let first_value, second_value;

    if (
      paths.every(function (path) {
        first_value = refine(first, path);
        second_value = refine(second, path);
        return first_value === second_value;
      })
    ) {
      return 0;
    }

    return (
      typeof first_value === typeof second_value
        ? first_value < second_value
        : typeof first_value < typeof second_value
    )
      ? -1
      : 1;
  };
};

let people = [
  { first: "Frank", last: "Farkel" },
  { first: "Fanny", last: "Farkel" },
  { first: "Sparkle", last: "Farkel" },
  { first: "Charcoal", last: "Farkel" },
  { first: "Mark", last: "Farkel" },
  { first: "Simon", last: "Farkel" },
  { first: "Gar", last: "Farkel" },
  { first: "Ferd", last: "Berfel" },
];

people.sort(by("first", "second"));

console.log(people);

WeakMap

function factory() {
    const map = new WeakMap()
    return {
        seal: (object) => {
            const box = Object.freeze(Object.create(null))

            map.set(box, object)
            return map
        },
        unseal: (box) => {
            return map.get(box)
        }
    }
}

Object.freeze && const

Object.freeze是作用于值的,而const则作用于变量

函数对象

generate

尾调用函数

当一个函数返回另一个函数的返回值时,我们就称其是一个尾调用。

function continuize(any) {
    return function hero(fn2, ...args) {
        return fn2(any(...args)); // 尾调用函数
    }
}

promise && async / await

那就是将逻辑与控制流强耦合在了一起。这就必然导致低内聚。

上一篇 下一篇

猜你喜欢

热点阅读