실패율

2020.07.29

const reduceHelper1 = (acc, current, idx, origin) => {
  if (acc.hasOwnProperty(current)) {
    acc[current]++;
  }
  if (idx == origin.length - 1) {
    return Object.entries(acc).map(([stage, count]) => [
      parseInt(stage),
      count,
    ]);
  }
  return acc;
};

const reduceHelper2 = (acc, current, idx, origin) => {
  const subtract = current[1];
  current[1] /= acc;
  if (idx == origin.length - 1) {
    return origin;
    // 이렇게 원본 배열을 건드리는 게 좋은 방법인지는 잘...
  }
  acc -= subtract;
  return acc;
};

const initHash = (num) => {
  const hash = {};
  for (let i = 1; i <= num; i++) {
    hash[i] = 0;
  }
  return hash;
};
const sortByFailureRate = (a, b) => {
  if (a[1] > b[1]) {
    return -1;
  }
  if (a[1] < b[1]) {
    return 1;
  }
  if (a[0] > b[0]) {
    return 1;
  }
  if (a[0] < b[0]) {
    return -1;
  }
};
const solution = (N, stages) => {
  const hash = initHash(N);
  return stages
    .reduce(reduceHelper1, hash)
    .reduce(reduceHelper2, stages.length)
    .sort(sortByFailureRate)
    .map(([stage, failureRate]) => stage);
};
  • reduceHelper2함수에서 원본 배열을 수정해서 반환했는데 이게 좋은 방법인지 잘 모르겠다.
    (불변성이 중요하다고 어디서 본 것 같은데...)

0개의 댓글