Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

手写Array.prototype.* #225

Open
FrankKai opened this issue Jun 2, 2020 · 3 comments
Open

手写Array.prototype.* #225

FrankKai opened this issue Jun 2, 2020 · 3 comments

Comments

@FrankKai
Copy link
Owner

FrankKai commented Jun 2, 2020

主要手写一些常用的Array.prototype上的函数。

  • 手写filter
  • 手写map
  • 手写every
@FrankKai FrankKai changed the title 手写Array.prototype.filter 手写Array.prototype.* Jun 2, 2020
@FrankKai
Copy link
Owner Author

FrankKai commented Jun 2, 2020

手写filter

  • 实现
  • 测试

实现

const filter = (arr, callback) => {
  const result = [];
  for (let i = 0; i < arr.length; i++) {
    const validate = callback(arr[i], i, arr);
    if (validate) {
      result.push(arr[i]);
    }
  }
  return result;
};

测试

const arr = [1, 2, 3, 4];

/**
 * 1.测试callback入参
 */
filter(arr, (item, index, arr) => console.log(item, index, arr));
/**
 * 2.测试callback断言
 */
let filterArr = filter(arr, (item) => item > 1);
console.log(filterArr);

@FrankKai
Copy link
Owner Author

FrankKai commented Jun 2, 2020

手写map

  • 实现
  • 测试

实现

const map = (arr, callback) => {
  const result = [];
  for (let i = 0; i < arr.length; i++) {
    result.push(callback(arr[i], i, arr));
  }
  return result;
};

测试

const arr = [1, 2, 3, 4];

/**
 * 1.测试callback入参
 */
map(arr, (item, index, arr) => console.log(item, index, arr));
/**
 * 2.测试callback映射
 */
let mapArr = map(arr, (item, index) => ({ value: item, index }));
console.log(mapArr);

@FrankKai
Copy link
Owner Author

FrankKai commented Jun 2, 2020

手写every

  • 实现
  • 测试

实现

const every = (arr, callback) => {
  let result = true;
  for (let i = 0; i < arr.length; i++) {
    if (!callback(arr[i], i, arr)) {
      result = false;
      break;
    }
  }
  return result;
};

测试

const arr = [1, 2, 3, 4];

/**
 * 1.测试callback入参
 */
every(arr, (item, index, arr) => console.log(item, index, arr));
/**
 * 2.测试callback断言
 */
let everyTruthy = every(arr, (item) => item > 0);
let everyFalsy = every(arr, (item) => item > 2);
console.log(everyTruthy, everyFalsy); // true, false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant