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

값을 비교해보자(String, Array, Object 등등) #27

Open
SeonHyungJo opened this issue Jul 3, 2019 · 1 comment
Open

값을 비교해보자(String, Array, Object 등등) #27

SeonHyungJo opened this issue Jul 3, 2019 · 1 comment
Labels
💌 JavaScript 공부를 해도해도 어려운 JavaScript 😎 type:Concept 이런 개념도 알아두면 좋아

Comments

@SeonHyungJo
Copy link
Owner

나도 구현할 수 있겠는데?

value-equal이라는 라이브러리가 있다.
react-router-dom내부를 살펴보다가 history라는 npm 라이브러리에서 사용을 하고 있어서 열어보니 어느 타입이든 값이 같은지 비교를 해주는 라이브러리가 있었다. 하물며 Array의 값들이 같은지 Object안에 있는 값들이 같은지를 비교를 해준다.

실제로 내부는?

실질적으로 코드의 양은 엄청나게 적다는 것을 확인했다.

function valueOf(obj) {
  return obj.valueOf ? obj.valueOf() : Object.prototype.valueOf.call(obj);
}

function valueEqual(a, b) {
  // Test for strict equality first.
  if (a === b) return true;

  // Otherwise, if either of them == null they are not equal.
  if (a == null || b == null) return false;

  if (Array.isArray(a)) {
    return (
      Array.isArray(b) &&
      a.length === b.length &&
      a.every(function(item, index) {
        return valueEqual(item, b[index]);
      })
    );
  }

  if (typeof a === 'object' || typeof b === 'object') {
    var aValue = valueOf(a);
    var bValue = valueOf(b);

    if (aValue !== a || bValue !== b) return valueEqual(aValue, bValue);

    return Object.keys(Object.assign({}, a, b)).every(function(key) {
      return valueEqual(a[key], b[key]);
    });
  }

  return false;
}
@SeonHyungJo SeonHyungJo added 💌 JavaScript 공부를 해도해도 어려운 JavaScript 😎 type:Concept 이런 개념도 알아두면 좋아 labels Jul 3, 2019
@BKJang
Copy link

BKJang commented Jul 8, 2019

좋은 참고가 되었습니다 감사합니다 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
💌 JavaScript 공부를 해도해도 어려운 JavaScript 😎 type:Concept 이런 개념도 알아두면 좋아
Projects
None yet
Development

No branches or pull requests

2 participants