首页  >  文章  >  web前端  >  对象静态方法 - JavaScript 挑战

对象静态方法 - JavaScript 挑战

Susan Sarandon
Susan Sarandon原创
2024-11-04 03:39:01493浏览

Object static methods - JavaScript Challenges

您可以在仓库 Github 上找到本文中的所有代码。


对象静态方法相关的挑战


对象.分配()

/**
 * @param {any} target
 * @param {any[]} sources
 * @return {object}
 */
function myObjectAssign(target, ...sources) {
  if (target == null) {
    throw Error();
  }

  target = Object(target);

  function merge(keys = [], currSource) {
    for (const key of keys) {
      target[key] = currSource[key];

      if (target[key] !== currSource[key]) {
        throw Error();
      }
    }
  }

  for (const source of sources) {
    if (source == null) {
      continue;
    }

    merge(Object.keys(source), source);
    merge(Object.getOwnPropertySymbols(source), source);
  }

  return target;
}

// Usage example
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);

console.log(target); // => Object { a: 1, b: 4, c: 5 }
console.log(returnedTarget === target); // => true

对象.create()

/**
 * @param {any} proto
 * @return {object}
 */
function myObjectCreate(proto) {
  function MyConstructor() {}

  MyConstructor.prototype = proto.prototype ?? proto;

  return new MyConstructor();
}

// Usage example
const person = {
  isHuman: false,
  printIntroduction: function () {
    console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
  },
};
const me = myObjectCreate(person);
me.name = "Matthew"; // => "name" is a property set on "me", but not on "person"
me.isHuman = true; // Inherited properties can be overwritten
me.printIntroduction(); // => "My name is Matthew. Am I human? true"

对象.groupBy()

/**
 * @param {Array} arr
 * @param {Function} iteratee
 * @return {Array}
 */

function groupBy(arr, iteratee) {
  const result = {};
  const iterateeFn =
    typeof iteratee === "function" ? iteratee : (value) => value[iteratee];

  for (const item of arr) {
    const key = iterateeFn(item);

    if (!Object.hasOwn(result, key)) {
      result[key] = [];
    }
    result[key].push(item);
  }

  return result;
}

// Usage example
console.log(groupBy([6.1, 4.2, 6.3], Math.floor)); // => { '4': [4.2], '6': [6.1, 6.3] }

// Group by string length
console.log(groupBy(["one", "two", "three"], "length"));
// => { '3': ['one', 'two'], '5': ['three'] }

const users = [
  { user: "barney", age: 36 },
  { user: "fred", age: 40 },
];

// Group by a property of the objects
console.log(groupBy(users, "age"));
// => { '36': [{'user': 'barney', 'age': 36}], '40': [{'user': 'fred', 'age': 40}] }

对象.is()

/**
 * @param {any} op1
 * @param {any} op2
 * @return {boolean}
 */

function myObjectIs(op1, op2) {
  if (op1 === op2) {
    return a !== 0 || 1 / a === 1 / b;
  } else {
    return a !== a && b !== b;
  }
}

// Usage example
Object.is(+0, -0); // false
Object.is(NaN, NaN); // true

Object.fromEntries()

/**
 * Creates an object from an array of key-value pairs.
 *
 * @param {Array} pairs - An array of key-value pairs.
 * @returns {Object} - The object composed from the key-value pairs.
 */

// One-line solution
function fromPairs(pairs) {
  return Object.fromEntries(pairs);
}

// Iterative solution
function fromPairs(pairs) {
  const result = {};

  for (const [key, value] of pairs) {
    result[key] = value;
  }

  return result;
}

// Usage example
const pairs = [
  ["a", 1],
  ["b", 2],
  ["c", 3],
];

console.log(fromPairs(pairs)); // => { a: 1, b: 2, c: 3 }

参考

  • 伟大的前端
  • 26。实现 Object.assign() - BFE.dev
  • 94。实现你自己的 Object.create - BFE.dev
  • 116。实现 Object.is() - BFE.dev
  • 177。实现 Object.groupBy() - BFE.dev
  • Object.assign() - MDN
  • Object.create() - MDN
  • Object.fromEntries() - MDN
  • Object.groupBy() - MDN
  • Object.is() - MDN

以上是对象静态方法 - JavaScript 挑战的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn