2017-04-15 22 views
0

引数 - 別の関数 - とその関数の "memoized"バージョンを返します。関数の "memoized"バージョンは、呼び出しの結果をキャッシュして返すので、同じ入力で再度呼び出されたときに計算が実行されず、キャッシュから結果が返されるようになります。以前の結果は、再計算することなく、任意の順序で取り出すことができることに注意してください。別の関数に引数を取る

foo = function (x) { 
console.log("calculating!"); 
return x + 5; 
} 

var memoizedFoo = memoize(foo); 

memoizedFoo(5); 
// calculating! 
// 10 

memoizedFoo(5); 
// 10 (notice how 'calculating!' is not printed this time) 

memoizedFoo(10); 
// calculating! 
// 15 
+5

*は何です*簡単な質問ですか? –

+0

@ T.J.Crowderは、なぜ間違い、私は解決するためにこの質問がありますが、仕事を得る方法を取得していない – faisal

+0

ポイントはあなたが質問していないです。 –

答えて

2

memoizeを書く方がいいと思います。与えられた引数の最初の結果をコンテナに格納し、可能であればそのコンテナを使用する関数を返すことができます。

ここだけ引数文字列のような有効文字列に変換できる値、数値、ブール値のために働く、ES5の例です:あなたは他の種類をサポートする必要がある場合

function memoize(f) { 
 
    // Storage for this function's results 
 
    var values = Object.create(null); 
 
    return function(arg) { 
 
    // Already have it? 
 
    if (Object.hasOwnProperty.call(values, arg)) { 
 
     // Yes, return it 
 
     return values[arg]; 
 
    } 
 
    // No, get it, remember it, and return it 
 
    return values[arg] = f(arg); 
 
    }; 
 
} 
 

 
var foo = function (x) { 
 
    console.log("calculating!"); 
 
    return x + 5; 
 
}; 
 

 
var memoizedFoo = memoize(foo); 
 

 
console.log(memoizedFoo(5)); 
 
// calculating! 
 
// 10 
 

 
console.log(memoizedFoo(5)); 
 
// 10 
 

 
console.log(memoizedFoo(10)); 
 
// calculating! 
 
// 15

他の構造体、またはMapポリフィルを使用する必要があります。これに私たちをもたらします...

が... ES2015 +で、我々はそれが引数の値の広い範囲で動作します Map、使用することができます。

function memoize(f) { 
 
    // Storage for this function's results 
 
    const values = new Map(); 
 
    return function(arg) { 
 
    // Already have it? 
 
    if (values.has(arg)) { 
 
     // Yes, return it 
 
     return values.get(arg); 
 
    } 
 
    // No, get it, remember it, and return it 
 
    const value = f(arg); 
 
    values.set(arg, value); 
 
    return value; 
 
    }; 
 
} 
 

 
const foo = function (x) { 
 
    console.log("calculating!"); 
 
    return x.foo + 5; 
 
}; 
 

 
const memoizedFoo = memoize(foo); 
 

 
const firstArg = {foo:5}; 
 
console.log(memoizedFoo(firstArg)); 
 
// calculating! 
 
// 10 
 

 
console.log(memoizedFoo(firstArg)); 
 
// 10 
 

 
const secondArg = {foo:10}; 
 
console.log(memoizedFoo(secondArg)); 
 
// calculating! 
 
// 15 
 

 
// Note that maps consider equivalent but distinct objects as different (of course), 
 
// so we don't get the memoized reslt from 
 
// `firstArg` here 
 
const thirdArg = {foo:5}; 
 
console.log(memoizedFoo(secondArg)); 
 
// calculating! 
 
// 10

関連する問題