일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 포트폴리오
- classList
- 2020
- windowwidth
- chart responsive
- resize
- react-router
- 내배위의고양이
- react
- classList add
- 냥빨이다가온다
- 커스텀훅
- react-router-dom
- chart.js
- 접근성
- classList toggle
- 언젠간가겠지
- 퍼블리싱
- 대표님물리기없기
- 간식금지다!
- 방심은금물
- 클래스 토글
- classList remove
- className
- 안짤렸다
- 리엑트할수있는퍼블리셔라규
- ROUTER 버전6
- 를
Archives
- Today
- Total
틈
[2021-05-04] 두 객체의 value 비교 본문
Question :
available의 재료가 준비되어 있다. recipe대로 만드려면 얼마나 만들 수 있을까?
Anwer :
function cakes(recipe, available) {
var recipeKey = Object.getOwnPropertyNames(recipe);
var availableKey = Object.getOwnPropertyNames(available);
var recipeCheck = recipeKey.filter(function(val){
return availableKey.indexOf(val) == -1;
});
var result = Infinity;
if(recipeCheck.length){
return 0;
} else {
for(var i = 0;i < recipeKey.length;i++){
for(var j = 0;j < availableKey.length;j++){
if(recipeKey[i] === availableKey[j]){
var key = recipeKey[i];
result = Math.min(result,parseInt(available[key] / recipe[key]));
}
}
}
}
return result;
}
anotherAnswer1 :
function cakes(recipe, available) {
return Object.keys(recipe).reduce(function(val, ingredient) {
return Math.min(Math.floor(available[ingredient] / recipe[ingredient] || 0), val)
}, Infinity)
}
anotherAnswer2 :
const cakes = (needs, has) => Math.min(
...Object.keys(needs).map(key => Math.floor(has[key] / needs[key] || 0))
)
anotherAnswer3 :
function cakes(recipe, initial){
return Math.floor(Object.keys(recipe).reduce(function(min, key){
return Math.min(initial[key] / recipe[key] || 0, min);
}, Infinity));
}
객체의 키값을 얻어서 키값에 대응하는 value 값을 연산하는 것으로 작업했습니다.
해당하는 key값을 얻는 것도 어려웠고, value를 얻는 것도 많은 고민이 필요했습니다. 객체에 대한 공부가 많이 필요하다고 생각되는 예제였습니다.
- Object.getOwnPropertyNames() : 객체의 키값을 배열로 리턴
- object.indexOf(val) == -1; : 배열에서 indexOf의 값을 지움
- Math.min() : 2가지 인자를 받아서 더 작은 값을 리턴
'code > Daily Side Project' 카테고리의 다른 글
[2021-05-05] 인자에서 글자 추출 가능 여부 (0) | 2021.05.05 |
---|---|
[2021-05-05] 여러 자릿수의 숫자를 한자리로 만들기 (0) | 2021.05.05 |
[2021-05-03]괄호 닫힘 확인 예제 (0) | 2021.05.03 |
[2021-05-03] 짝수/홀수 분별하기 (0) | 2021.04.30 |
[2021-04-29] 빠진 알파벳 찾기 (0) | 2021.04.29 |
Comments