Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

189
Vistas
Underscore "defaults" from scratch

I've been trying to rewrite the _.defaults method from underscore.js and I keep getting this error:

should copy source properties to undefined properties in the destination object‣ AssertionError: expected { a: 'existing' } to deeply equal { a: 'existing', b: 2, c: 3, d: 4 }

Here's the missing conditions:

-should copy source properties to undefined properties in the destination object and should return the destination object

and my code:

_.defaults = function (destination, source) {
  Object.keys(destination).forEach(key => {
    if (destination[key] === undefined || destination[key] === null) {
      destination[key] = source[key];
    }
  })
  return destination;

};
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The idea in _.defaults is that keys from the source object might be missing entirely in the destination object. So you need to iterate the keys of the source object instead of those of the destination object:

_.defaults = function (destination, source) {
  Object.keys(source).forEach(key => {
    if (destination[key] === undefined || destination[key] === null) {
      destination[key] = source[key];
    }
  })
  return destination;

};

Side note: you can write x == null instead of x === null || x === undefined. Saves some precious keystrokes.

_.defaults = function (destination, source) {
  Object.keys(source).forEach(key => {
    if (destination[key] == null) {
      destination[key] = source[key];
    }
  })
  return destination;

};
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda