2016-07-13 67 views
-1

對不起,首先嚐試解釋這個問題很糟糕。試圖學習Javascript和一個代碼問題(codewars)的問題讓我難住。它聲明,編寫一個函數,將另一個函數作爲參數並緩存結果,以便如果發送相同的參數,則返回值將從緩存中提取,並且實際函數不會再被調用。例如:函數如何處理通過另一個函數傳遞的參數? Javascript

var x = function(a, b) { a * b }; 
var cachedFunction = cache(x); 

cachedFunction(4, 5); // function x should be executed 
cachedFunction(4, 5); // function x should not be invoked again, instead the cached result should be returned 
cachedFunction(4, 6); // should be executed, because the method wasn't invoked before with these arguments 

我不知道如何訪問通過cachedFunction發送的參數。目標是編寫緩存,以便它可以使用任意數量的參數處理函數x。

+1

你沒有真正傳遞'x','5'和'4'到'cache'功能。您將5和4傳遞給'x'函數,接收結果,然後將_that_傳遞給'cache'。 (爲什麼它值得) – enhzflep

+1

你不能。你的'cache'函數被調用的值爲'20'(* x(5,4)'的*結果*),它不知道什麼值傳遞給'x'或者'x'是曾經叫過。另外,你的'cache'函數是做什麼的?你認爲*是否會傳遞一個函數?因爲目前,你不是。 –

+0

對不起,我第一次嘗試瞭解問題,並說這個問題很糟糕。我重寫了它。不知道正確的禮節是否完全廢棄原版,並重寫或做出如此大的編輯。我很抱歉,如果我應該做前者。 –

回答

2

你所描述的是不可能的。

表達式x(5, 4)在甚至調用cache()函數之前被評估。它沒有收到一個函數。它正在接收價值20。之後

function x(a,b){ 
    return [a, b, a*b]; 
} 

你可以得到PARAMS這樣的:

0

你可以返回一個表像這樣

var result=x(values1,value2); 
console.log(result[0]);// a == value1 
console.log(result[1]);// b == value2 
console.log(result[2]);// a*b == value1*value2 
1

在你的榜樣,cache只能訪問的x返回值。它不知道如何計算這個返回值(即通過調用參數爲5, 4x)。

您需要分別將函數及其參數傳遞給cache函數, G。如下:

function cache(func, ...params) { 
 
    // Todo: do something with params 
 
    return func(...params); 
 
} 
 

 
function x(a, b){ 
 
    return a * b; 
 
} 
 

 
console.log(cache(x, 5, 4));

相關問題