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

267
Vistas
Javascript: HackerRank function within a function is not a function

This is one of those job interview tests on HackerRank that I am embarrassed to say I didn't complete within the allotted 20 minutes, and it's driving me nuts. Basically, you're given the following:

function myList() {
    // write code here
}

function main() {
    // You can't edit this function. This is just pseudo, from what I can remember
    const obj = myList();
    if (operation === "add")
        obj.add(item);
    else if (operation === "remove")
        obj.remove(item);
    else
        obj.getList();
    // Some more stuff here
}

So my first train of thought was to write the following inside myList():

let objList = [];
function add(item) {
    objList.add(item)
}
// etc., etc.
return {add, remove, getList};

Needless to say, the above didn't work, with the error: obj.add is not a function, in the main function.

I tried experimenting with this and the returns (only returning add, with or without {}), but didn't really get anywhere. What could I have done to get this working?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

For obj, inside myList() you could have run a closure, that is a self invoking function returning, in this case, an object with your k:v exports, but with private access to the context of the now expired anonymous caller. With "const add = function" etc statements you can define values for your exports, while the objList goes in the private context.

about 4 years ago · Juan Pablo Isaza Denunciar

0

As the answer from Attersson already suggested, you could use a closure inside the myList function. This would allow to only expose the three methods add, remove and getList while the original list cannot be accessed. Here is an example:

function myList() {
  return (() => {
    const obj = {itemList: []} 
    const add = (item) => obj.itemList.push(item)
    const remove = (item) => obj.itemList = obj.itemList.filter(i => i !== item)
    const getList = () => obj.itemList
    return {add, remove, getList}
  })()
}
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