Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

205
Visualizações
Creating an object from arrays

I am trying to create a function that tracks how many hours are spent on hobbies. The input is an array of hobbies. I am trying to create a cache object with each hobby as a key and hours spent as the values. I am trying to use a return function that takes a string representing the hobby and an integer representing how many hours practiced as parameters.

I am trying to make the return function inside update the cache object by adding the value of the passed integer to the cache at the key corresponding with the passed in 'hobby'. I want the returned function to reset all values in the cache object to zero if there are no arguments passed into the return function.

Here is what I have tried so far...

function hobbyTracker(hobbies) {
  const cache = {};
  return function(hobbies, hours) {
    if (hobbies) {
      cache[hobbies] += hours;
      return cache;
    } else {
      for (let key in cache) {
        cache[key] = 0;
      }
      return 'tracker has been reset!';
    }
  }
  return cache;
}

I am unsure how to write the 'if' statement to check whether or not arguments have been passed in. I don't think the .hasOwnProptery() would work here, would it? My line of thinking is because it works on keys as I understand it plus the object is not yet populated!

I am also unsure where I should initialize the cache object! Is that a part of the problem with my code?

I also know that my return function isn't properly updating the hours. I need it to accumulate the total hours spent but instead, my code just overwrites it upon new input. I tried using += on cache[hobbies] = hours, but then I get an object populated by NaNs.

Any help would be greatly appreciated!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use the special object arguments. It's an array-like object that contains all the arguments. If no arguments were passed, its length will be 0.

if (arguments.length = 2) {
    // use hobbies and hours
} else {
    // reset cache
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Your if statement is just fine. If hobby is provided do something, else clear cache. You missed adding a check for the hobby missing from cache (1st time), so you don't have to add, but create the key in cache and assign the hours.

The final code could be something like below:

function hobbyTracker() {
  const cache = {};
  return function(hobby, hours) {
    if (hobby) {
      if (cache[hobby]) {
        cache[hobby] += hours;
      } else {
        cache[hobby] = hours;
      }
    } else {
      Object.keys(cache).forEach((key) => { cache[key] = 0 })
    }
    return cache;
  }
}


const myHobbyTracker = hobbyTracker();

console.log(myHobbyTracker('ski', 8))
console.log(myHobbyTracker('basket', 5))
console.log(myHobbyTracker('ski', 3))
console.log(myHobbyTracker())

  • This code always returns the cache.
  • I also changed the way the cache is cleared, although your for loop works just fine (i'm just not a big fan).
  • Renamed hobbies argument to hobby since you provide one at a time.

I am also unsure where I should initialize the cache object!

Using hobbyTracker function scope to initialize the cache object seems reasonable, so you can make it private and accesible from the returned function.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda