yamoo9 / likelion-FEQA

질문/답변 — 프론트엔드 스쿨, 멋사
29 stars 9 forks source link

[LAB-3] 자바스크립트 소수점 계산문제 (비교 → 필터링) #267

Closed choinamechoi closed 1 year ago

choinamechoi commented 1 year ago

질문 작성자

최영범

문제 상황

image

image

async function dataFilter(arr1, Centerlongitude) { let filteringData = []; console.log(Centerlongitude - 0.00565, '결과1'); console.log(Centerlongitude + 0.00565, '계산결과2'); await arr1.forEach((item) => { if (Centerlongitude - 0.00565 < item.longitude < Centerlongitude + 0.00565) { filteringData.push(item); console.log(item.longitude, '값'); } }); console.log(filteringData); return filteringData; }

위의 함수와 같이 item.longitude 라는 값이 범위 안에 속하면 배열에 push를 해주려 하였습니다.

그러나 콘솔창을 확인해보면 조건 범위안의 값이 아닌것들도 푸시가 되어 들어옵니다.

저는 저 소수점 자리까지의 정확도가 필요한데 저렇게 소수점을 사용할수있는 방법이 없을까요?

감사합니다.

프로젝트 저장소 URL

환경 정보

yamoo9 commented 1 year ago

문제 분석

소수점 비교가 문제라기 보다는, 잘못된 조건 처리가 문제입니다.

문제 해결

함수 내부 if 조건 부분을 확인해주세요.

const RANGE_VALUE = 0.00565;

function dataFilter(dataArray, centerlongitude) {
  const MIN = centerlongitude - RANGE_VALUE;
  const MAX = centerlongitude + RANGE_VALUE;

  let filteringData = [];

  dataArray.forEach(({ longitude }) => {
    if (MIN < longitude && longitude < MAX) {
      filteringData.push(longitude);
    }
  });

  return filteringData;
}

forEach 대신, filter 메서드를 사용하면 보다 코드가 클린 해집니다.

function dataFilter(dataArray, centerlongitude) {
  const MIN = centerlongitude - RANGE_VALUE;
  const MAX = centerlongitude + RANGE_VALUE;

  return  dataArray.filter(({longitude}) => MIN < longitude && longitude < MAX);
}

매개변수를 함축하면 더 간소해지긴 하지만... 읽기는 어렵죠.

const dataFilter = (d, c) =>
  d.filter(
    ({ longitude }) => c - 0.00565 < longitude && longitude < c + 0.00565,
  );

작성된 로직으로 Console 패널에서 테스트한 결과는 다음과 같습니다. 총 4개의 아이템 중, 조건에 부합되는 2개의 아이템만 포함한 배열이 반환됩니다. 😉