Interview questions
one,
The code copy is as follows:
Please define such a function
function repeat (func, times, wait) {
}
This function can return a new function, for example
var repeatedFun = repeat(alert, 10, 5000)
Call this repeatedFun ("hellworld")
Will alert helloworld ten times, each time interval is 5 seconds
two,
The code copy is as follows:
Write a function stringconcat, which requires
var result1 = stringconcat("a", "b") result1 = "a+b"
var stringconcatWithPrefix = stringconcat.prefix("hellworld");
var result2 = stringconcatWithPrefix("a", "b") result2 = "hellworld+a+b"
Side dishes solution
These two questions test closures. Without saying much nonsense, just enter the code.
The code copy is as follows:
/**
* Question 1
* @param func
* @param times
* @param wait
* @returns {repeatImpl}
*/
function repeat (func, times, wait) {
//No anonymous functions are used to facilitate debugging
function repeatImpl(){
var handle,
_arguments = arguments,
i = 0;
handle = setInterval(function(){
i = i + 1;
//Cancel timer when the specified number of times
if(i === times){
clearInterval(handle);
return;
}
func.apply(null, _arguments);
},wait);
}
return repeatImpl;
}
//Test cases
var repeatFun = repeat(alert, 4, 3000);
repeatFun("hellworld");
/**
* Question 2
* @returns {string}
*/
function stringconcat(){
var result = [];
stringconcat.merge.call(null, result, arguments);
return result.join("+");
}
stringconcat.prefix = function(){
var _arguments = [],
_this = this;
_this.merge.call(null, _arguments, arguments);
return function(){
var _args = _arguments.slice(0);
_this.merge.call(null, _args, arguments);
return _this.apply(null, _args);
};
};
stringconcat.merge = function(array, arrayLike){
var i = 0;
for(i = 0; i < arrayLike.length; i++){
array.push(arrayLike[i]);
}
}
//Test cases
var result1 = stringconcat("a", "b"); //result1 = "a+b"
var result3 = stringconcat("c", "d"); //result1 = "a+b"
var stringconcatWithPrefix = stringconcat.prefix("hellworld");
var stringconcatWithPrefix1 = stringconcat.prefix("hellworld1");
var result2 = stringconcatWithPrefix("a", "b"); //result2 = "hellworld+a+b"
var result4 = stringconcatWithPrefix1("c", "d"); //result2 = "hellworld+a+b"
alert(result1);
alert(result2);
alert(result3);
alert(result4);