Technical Question from Interview

Technical Question from Interview
0

#1

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.


#2

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

#3

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.


#4

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.


#5

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


#6

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


#7

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.


#8

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


#9

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?


#10

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.


#11

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


#12

#13

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


#14

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


#15

If I make the following two calls to your function, they do not result in the same result. Both calls should result in 19.

callTwice(19)
callTwice(6)

Your function will always return the value sent to it as long as it is >= 0.


#16

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


#17

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.


#18

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.


#19

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;
	};
}

#20
const once = (fn, result, wasCalledBefore = false) => 
  (...args) => wasCalledBefore
  	? result
  	: (wasCalledBefore = true, result = fn(...args))