Created
June 21, 2020 05:27
-
-
Save amorfati0310/02c57786b9c6210e11ad54b883adcb2a to your computer and use it in GitHub Desktop.
05-mini-project
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 상품 데이터 | |
const data = [ | |
{ name: '초콜렛', price: 2000 }, | |
{ name: '아이스크림', price: 1000 }, | |
{ name: '컵라면', price: 1600 }, | |
{ name: '볼펜', price: 2500 }, | |
{ name: '아메리카노', price: 4000 }, | |
{ name: '과자', price: 3000 }, | |
{ name: '탄산수', price: 1200 }, | |
{ name: '떡볶이', price: 3500 }, | |
{ name: '노트', price: 1500 }, | |
{ name: '껌', price: 500 } | |
]; | |
// 사용자 입력 받기 | |
const line = prompt('최대 금액을 입력해주세요.'); | |
const amount = +line; | |
// 주어진 금액으로 살 수 있는 가장 비싼 상품을 구함 | |
const item = getItemByAmount(data, amount); | |
const msg = item ? | |
`${amount}원으로 살 수 있는 가장 비싼 상품은 [${item.name}]이고, 가격은 ${item.price}원입니다.` : | |
'살 수 있는 상품이 없습니다.'; | |
// 결과 출력 | |
alert(msg); | |
// 아 래에getItemByAmount 함수를 작성하세요. | |
//1. jsdoc이라는 것을 한 번 알아보셔도 좋을 것 같아요 | |
// 참고문서: -> https://jsdoc.app/about-getting-started.html | |
/** -> 를 입력하면 jsDoc comment 자동완성이 되는데 | |
* 함수 위에 받는 parameter에 대한 정보를 적어줄 수가 있어요 | |
* 이러면 협업하는 입장에서 어떤 함수를 적었는지 더 잘 파악이 가능하죠 :) | |
/** | |
* ex) | |
* @param {Array<Product>} data | |
* @param {number} amount | |
*/ | |
//2. 만약 사용자가 상품 가격으로 반환이 불가능한 문자를 입력하면 어떻게 될까요? | |
// 에러 처리에 대한 부분을 상위에서 처리해주면 더 좋을 것 같습니다 | |
// ex) if(typeof amount !== 'number') {return null} | |
// msg 처리도 null 일 경우 -> 상품 가격이 아닌 다른 정보를 입력하였습니다 다시 입력해주세요 | |
// 이런 부분 처리가 들어가면 더 좋겠죠 | |
// 3. 배열을 돌면서 순회하므로 Array.prototype methods들을 활용하면 더 좋았었을 것 같아요 | |
// 특히 forEach, map, filter, reduce는 정말 많이 쓰이고 | |
// 각 메소드 별로 새로운 배열을 반환하는지 기존 배열을 변형시키는지도 알아두실 필요가 있어요 ! | |
// 적용하신 부분을 Array.prototype methods들을 활용해서 고쳐볼게요 | |
// ex) 저는 map을 활용한 예를 들어 볼게요 | |
// const availablePriceList = data.map(item => { | |
// if(item.price < amount) { | |
// return null | |
// } | |
// return item.price | |
// }) | |
// const mostExpensive = Math.max.apply(null, availablePriceList); | |
// | |
// return data.find(item => { | |
// return item.price === mostExpensive | |
// }) | |
// 4. *참고 forEach로 돌면서 상품 정보 저장하는 방식도 살펴보세요 | |
// 차이값을 가장 큰 수인 무한대로 설정 | |
// let amountDiff = Infinity; | |
// // 조건에 부합하는 상품을 찾지 못했을 경우의 리턴값인 null을 초기값으로 설정 | |
// let selectedItem = null; | |
// data.forEach(item => { | |
// // amount - item.price가 여러 곳에 쓰이므로 변수에 할당 | |
// const diff = amount - item.price; | |
// // 사용자의 금액이 물건의 값보다 크고, 현재까지의 차이값보다 작을 경우 선택된 상품을 변경 | |
// if (diff >= 0 && diff < amountDiff) { | |
// selectedItem = item; | |
// amountDiff = diff; | |
// } | |
// }); | |
// return selectedItem; | |
// | |
// 5. 참고 일반 for문 말고 index가 필요한 경우가 아니라면 | |
// for of 도 살펴보세요 | |
// for (i = 0; i < data.length; i++) { | |
// if (data[i].price <= amount) { | |
// availablePrice.push(data[i].price); | |
// } | |
// } | |
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of | |
// for (const item of data) { | |
// if (item.price <= amount) { | |
// availablePrice.push(item.price); | |
// } | |
// } | |
function getItemByAmount(data, amount) { | |
// 주어진 금액보다 비싼 상품 걸러내기 | |
const availablePrice = []; | |
for (i = 0; i < data.length; i++) { | |
if (data[i].price <= amount) { | |
availablePrice.push(data[i].price); | |
} | |
} | |
// 걸러진 상품 중 가장 비싼 가격을 Math.max 함수를 이용하여 구하기 | |
const mostExpensive = Math.max.apply(null, availablePrice); | |
// 그 가격에 맞는 객체를 찾아서 return | |
for (i = 0; i < data.length; i++) { | |
if (data[i].price === mostExpensive) { | |
return data[i]; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment