-
Notifications
You must be signed in to change notification settings - Fork 0
javascript_in_depth_11
๋ฉ๋ชจ์ด์ ์ด์ ํจํด์ ์ด์ ์ ๊ณ์ฐํ ๊ฐ์ ๋ฉ๋ชจ๋ฆฌ์ ์ ์ฅํจ์ผ๋ก์จ ๋์ผํ ๊ณ์ฐ์ ๋ฐ๋ณต ์ํ์ ์ ๊ฑฐํ์ฌ ํ๋ก๊ทธ๋จ ์คํ ์๋๋ฅผ ๋น ๋ฅด๊ฒ ํ๋ ๊ธฐ์ ์ด๋ค. ์ด๋ฆ๋๋ก '๋ฉ๋ชจ'๋ฅผ ํ๋ ๊ฒ์ด ํน์ง์ธ๋ฐ, ์ด ๋ฉ๋ชจ๋ฅผ ํ๋ ๋์์ ํจ์ ๋๋ ๊ฐ์ฒด์ด๋ค.
์ผ๋ฐ์ ์ธ ํ๋ก๊ทธ๋๋ฐ ์ธ์ด์์ ์บ์๋ฅผ ์ฌ์ฉํ๋ ๊ฒ์ฒ๋ผ ํ์ฉํ ์ ์๋ค. ํนํ ์ปดํจํ ์์์ด ์๋ชจ๋๊ฑฐ๋ ์ฒ๋ฆฌ ์๊ฐ์ด ๊ธด ์ฐ์ ์์ ๋ํ์ฌ ์บ์๋ฅผ ํด๋๋ ์์ผ๋ก ํ์ฉํ๋ฉด ์ข๋ค. ๋ฉ๋ชจ์ด์ ์ด์ ํจํด์ ๊ณ์ฐ์ด๋ ์์ฒญ์ด ์ค๋ ๊ฑธ๋ฆฌ๋ฉด์ ๋ฐ๋ณต์ ์ผ๋ก ๊ฐ์ ํธ์ถ์ด ์ผ์ด๋ ๋๋ ์ฌ๊ท ํจ์ ๊ตฌํ์์ ๋ฉ๋ชจ์ด์ ์ด์ ํจํด์ ์ค๊ณํ์ฌ ์ฌ์ฉํ๋ ๊ฒ์ด ์ข์ ์ฑ๋ฅ์ ๋ณด์ฌ์ค๋ค.
// ๋ฉ๋ชจ์ด์ ์ด์
ํจํด์ ์ด์ฉํ ์บ์ ๊ตฌํ
(function () {
var inputItemId = document.getElementById("itemId");
function searchItem(id) {
var xhr;
if (searchItem.cache.hasOwnProperty(id)) {
return searchItem.cache[id];
}
xhr = new XMLHttpRequest();
xhr.open("GET", "/searchItem");
xhr.onload = function () {
var item = JSON.parse(xhr.responseText);
searchItem.cache[item.id] = item;
}
xhr.send();
}
searchItem.cache = {};
document.getElementById("search").addEventListener("click", function () {
searchItem(searchItem.value);
});
}());๋ฉ๋ชจ์ด์ ์ด์ ํจํด์ ์ผ๋ฐ์ ์ผ๋ก ์ฌ์ฉํ ์ ์๋๋ก Function์ ํ๋กํ ํ์ ์ ์ถ๊ฐํด์ ์ฌ์ฉํ๋ฉด ๋ณต์กํ์ง ์๊ณ ํธ๋ฆฌํ๊ฒ ํ์ฉํ ์ ์๋ค.
// Function ๊ธฐ๋ณธ ํจ์๋ก memoize ํจ์ ์ ์
(function () {
Function.prototype.memoize = function () {
var _this = this,
memo = {};
return function () {
var argsString = JSON.stringify(arguments),
returnValue;
if (memo.hasOwnProperty(argsString)) {
return memo[argsString];
} else {
returnValue = _this.apply(this, arguments);
memo[argsString] = returnValue;
return returnValue;
}
}
};
function fibonacci(n) {
if (n === 0 || n === 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
var fibonacciMemo = fibonacci.memoize();
var testNum = 10, start, end;
start = Date.now();
console.log(fibonacciMemo(testNum));
end = Date.now();
console.log(`Elapsed time of ${((end-start)/1000).toFixed(2)} seconds for recursive fibonacciMemo(${testNum}) for the first time`);
start = Date.now();
console.log(fibonacciMemo(testNum));
end = Date.now();
console.log(`Elapsed time of ${((end-start)/1000).toFixed(2)} seconds for recursive fibonacciMemo(${testNum}) for the second time`);
}());