[2021-05-04] 두 객체의 value 비교 본문

code/Daily Side Project

[2021-05-04] 두 객체의 value 비교

남우p 2021. 5. 4. 18:00

 

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가지 인자를 받아서 더 작은 값을 리턴

Comments