Skip to content

Commit 8a465a4

Browse files
committed
fixed chuanxshi#6, now use hasOwnProperty for memoization pattern
1 parent 8758c4b commit 8a465a4

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

function-patterns/memoization.html

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
</head>
77
<body>
88
<script>
9+
// antipattern
10+
// reason see: https://github.com/shichuan/javascript-patterns/issues/6
911
var myFunc = function (param) {
1012
if (!myFunc.cache[param]) {
1113
var result = {};
@@ -18,6 +20,28 @@
1820
// cache storage
1921
myFunc.cache = {};
2022

23+
24+
// preferred
25+
26+
/*
27+
only one argument using param
28+
*/
29+
var myFunc = function (param) {
30+
if (!myFunc.cache.hasOwnProperty(param)) {
31+
var result = {};
32+
// ... expsensive operation ...
33+
myFunc.cache[param] = result;
34+
}
35+
return myFunc.cache[param];
36+
};
37+
38+
// cache storage
39+
myFunc.cache = {};
40+
41+
42+
/*
43+
multiple arguments using JSON stringify
44+
*/
2145
var myFunc = function () {
2246
var cachekey = JSON.stringify(Array.prototype.slice.call(arguments)),
2347
result;
@@ -32,6 +56,10 @@
3256
// cache storage
3357
myFunc.cache = {};
3458

59+
60+
/*
61+
multiple arguments using arguments.callee
62+
*/
3563
var myFunc = function (param) {
3664
var f = arguments.callee,
3765
result;

0 commit comments

Comments
 (0)