Home > Software design >  Javascript: HackerRank function within a function is not a function
Javascript: HackerRank function within a function is not a function

Time:02-11

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?

CodePudding user response:

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.

CodePudding user response:

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}
  })()
}
  • Related