Technical Question from Interview

During a phone screen I had with a company, I was asked a technical question. The technical question was…
Write a function that has a callback function that gets called only once. If it gets called again, the same result will return. I couldn’t solve it and failed the interview.

let myAdd = once(function(a,b) {
 return a + b;
}

myAdd(5,6); //11
myAdd(3,4); //11

I will share this question with everyone but I was wondering where online can I go to study coding challenges that are different from solving data structures, algorithms and etc.
I have used HackerRank, leetcode, and codewars but I havent seen anything similar to this question.

1 Like

I dd a quick good search.
REF: Function in javascript that can be called only once

My repl.it solution: https://repl.it/GPM4/0

var Once = function(a,b){
    var sum= a + b;

    Once = function(){};
    
    return sum;
}

console.log(Once(5,6));
// output: 11

console.log(Once(3,4));
// output: undefined
1 Like

would something simple like this be ok? James your solution doesn’t seem to meet the requirements…

var myAdd = function(a, b) {
    if(localStorage.hasOwnProperty("mySum")) {
        return parseInt( localSorage["mySum"] );
    }
    localStorage.setItem("mySum", a + b);
    return a + b;
}

edit: maybe mine doesn’t either… I think yours is good so long as the inner Once function just returns sum rather than being blank.

On a scale of 1-10, 10 being an expert at JS, how would you rate this question? I felt like it was basic but I had conceptual issues. I thought I understood callbacks but didn’t know how to answer this.

I dunno I feel like it’s kinda a gotcha question. Was the job advertised as a junior position?

1 Like

JavaScript Software Engineer at a top level company such as Google, Facebook, and Amazon.

lol what do you mean such as…which one was it?

That makes sense to me. If the title is ‘Javascript Software Engineer’, that means you should be a master of Javascript. This question seems to be Javascript specific… I don’t believe that most languages allow you to redefine functions within themselves.

2 Likes

I was hesitant to say but it was with Yahoo. Going back to my original question: Is there a site where I can take these kind of concepts into more practice. Mozilla documentation, youtube videos, hackerank, codewars, and a few udemy courses only took me so far. When it comes to these (tricky) basic concepts, I think I need to work on it more

Well practice doesn’t hurt, but I believe that Hackerrank has it’s problems designed for all languages. I’m also getting to the point of realizing that I’m no expert in JS… have you read YDKJS?

I think the answer is something like

function once( cb ) {
              var ans;
              return function() {
                
                if( ans === undefined ) {
                  if( arguments.length === 0 ) {
                    ans = cb();
                  } else {
                    var args = [].slice.apply( arguments );
                    ans = cb.apply(Object.create( null ), args );  // You can replace this line with cb(...args);
                  }
                }
                return ans;
              }
}
myadd = once( function( a, b ) { return a + b; } );
myadd( 5, 6 ); // 11
myadd( 3, 4 ); // 11

I think they were testing your understanding of closures and arguments objects. The closure keeps state of your answer from the first time the callback is invoked. The arguments object is interesting because you don’t know what parameters, if any will be passed to function. So you have to know

  1. how to get the arguments from the arguments object
  2. how to spread out the arguments to the callback parameters.

I think reading YDKJS series will help with fundamentals of JS. The YDKJS “scope and closures” has a section on closures.
Lastly, I think there may be a similar problem to this on codewars. I can’t remember now. Maybe it’s a 6 kyu problem.

6 Likes

i have read it but will review those books until its forever embedded into my mind.

2 Likes

Wow thanks for finding this. I guess I’ll need to level up to 6 since I am only around 7-8

I found this very interesting!
this would be my solution:
var value = 0;
function callTwice(value) {
if (value >= 1) {
return value;
}
value++;
callTwice(value);
}

you’re right… I think I just wanted to believe this was easier than it was hah thanks for your reply :slight_smile:

Hi folks,

IMHO there is a simple solution, just creating a container variable for the first sum and we meet the requirements:

let myAdd = function(a,b){
	if (myAdd.once === undefined){
		myAdd.once = a+b;
	}
	return myAdd.once;
};

In other words, I think the interviewer wanted to check about programming and design patterns skills; in this case, singleton pattern.

Well, in a second reading I have seen that I was looking at just for the singleton part and not to the whole question; so, this is my second, and now global, approach:

let once = function(callback, a, b){
	if (once.result === undefined){
		once.result = callback(a,b);
	}
	return once.result;
};

let myAdd = function(a,b) {
	console.log("myAdd called!")
	return a + b;
};

once(myAdd, 5, 6); //"myAdd called!" & 11
once(myAdd, 3, 4); //11

The console.log function is just to show that there is only one call to the function, next times is just returned the result.

Reggie01 your function works for the given tests. What would happen if the passed in function returns undefined but is changing a global variable? The function would then be allowed to be called multiple times. Below is my solution to the problem.


function once(func) {
	var executed = false;
	var result;
	return function() {
		if(!executed) {
			result = func.apply(this, arguments);
			executed = true;
		}
		return result;
	};
}
1 Like
const once = (fn, result, wasCalledBefore = false) => 
  (...args) => wasCalledBefore
  	? result
  	: (wasCalledBefore = true, result = fn(...args))
1 Like
var sum = 0;
var called = false;

var once = function(a, b) {

if(called == false) {
sum = a + b
called = true;
}

var result = sum;

return result;
}

This is how I would have done it off the top of my head. I have two global variables, “called” and “sum”. The function takes the two numbers passed to it, you could parseInt(); if you wanted, and adds them together. It then sets the global variable sum to that and changes the boolean to true. After this if statement, the local variable “result” is created which in turn is set equal to the sum. That means that after the first running, it will give you the correct sum and every other time after that it will just give you that original computation.