# 2623. Memoize
###### tags:`Function` | `leetCode`
<font color="#FBC01E" background="E1F3F0">`medium`</font>
### 題目
Given a function fn, return a new function that is identical to the original function except that it ensures fn is called at most once.
The first time the returned function is called, it should return the same result as fn.
Every subsequent time it is called, it should return undefined.
### Example
```javascript=
Input: fn = (a,b,c) => (a + b + c), calls = [[1,2,3],[2,3,6]]
Output: [{"calls":1,"value":6}]
Explanation:
const onceFn = once(fn);
onceFn(1, 2, 3); // 6
onceFn(2, 3, 6); // undefined, fn was not called
```
```javascript=
Input: fn = (a,b,c) => (a * b * c), calls = [[5,7,4],[2,3,6],[4,6,8]]
Output: [{"calls":1,"value":140}]
Explanation:
const onceFn = once(fn);
onceFn(5, 7, 4); // 140
onceFn(2, 3, 6); // undefined, fn was not called
onceFn(4, 6, 8); // undefined, fn was not called
```
---
### 解題邏輯
```javascript=
function memoize(fn) {
const cache = {}
return function(...args) {
const key = JSON.stringify(args)
if(key in cache){
//已存在
return cache[key]
}
const output = fn(...args)
cache[key] = output
//不存在
return output
}
}
/**
* let callCount = 0;
* const memoizedFn = memoize(function (a, b) {
* callCount += 1;
* return a + b;
* })
* memoizedFn(2, 3) // 5
* memoizedFn(2, 3) // 5
* console.log(callCount) // 1
*/
```
一開始我想用array的方式,但因為`[2,2]===[2,2]`會印出false(因為兩這所存在的記憶體不所以不會一樣)
一開始先設一個空 object ,並把傳入的參數字串化,放進物件裡當作 key,再將計算後的 output 放進物件裡當作剛剛那個 key 的 value