7kyu Lazily executing a function

题目:

Deferring a function execution can sometimes save a lot of execution time in our programs by postponing the execution to the latest possible instant of time, when we're sure that the time spent while executing it is worth it.
译文:延迟一个函数执行有时可以在我们的程序中节省大量的执行时间,把执行时间推迟到最新的可能的时间,当我们确定执行它的时间是值得的。

Write a method make_lazy that takes in a function (symbol for Ruby) and the arguments to the function and returns another function (lambda for Ruby) which when invoked, returns the result of the original function invoked with the supplied arguments.
译文:编写一个使用函数(Ruby的符号)和函数参数的方法,并返回另一个函数(Ruby的lambda),当调用该函数时,返回的是原始函数的结果,该函数用提供的参数调用。

For example:

Given a function add

function add (a, b) {
return a + b;
}
One could make it lazy as:

var lazy_value = make_lazy(add, 2, 3);
The expression does not get evaluated at the moment, but only when you invoke lazy_value as:

lazy_value() => 5
The above invokation then performs the sum.

Please note: The functions that are passed to make_lazy may take one or more arguments and the number of arguments is not fixed.

 


Sample Tests:
// Methods taking in a single parameter

var double = function (n) {
return n * 2;
};

var lazy_value = make_lazy(double, 5);

Test.expect(lazy_value() === 10, 'Evaluates the expression when required');

// Methods taking in multiple parameters

var add = function (a, b) {
return a + b;
};

var lazy_sum = make_lazy(add, 2, 3);

Test.expect(lazy_sum() === 5, 'Evaluates the expression when required');

 

答案:

var make_lazy = function () {
var args = Array.prototype.slice.call(arguments, 1);
return function () {
return fn.apply(fn, args);
}
};

posted @ 2017-08-08 12:56  tong24  阅读(213)  评论(0编辑  收藏  举报