Skip to content

Commit 0712c3f

Browse files
committed
added function patterns
1 parent 523b897 commit 0712c3f

File tree

2 files changed

+72
-7
lines changed

2 files changed

+72
-7
lines changed

function-patterns/memoization.html

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,45 @@
66
</head>
77
<body>
88
<script>
9-
function myFunc(param) {
10-
if (!myFunc.cache) {
11-
myFunc.cache = {};
12-
}
9+
var myFunc = function (param) {
1310
if (!myFunc.cache[param]) {
14-
var result = {}; // ...
11+
var result = {};
12+
// ... expsensive operation ...
1513
myFunc.cache[param] = result;
1614
}
1715
return myFunc.cache[param];
18-
}
19-
myFunc('hello');
16+
};
17+
18+
// cache storage
19+
myFunc.cache = {};
20+
21+
var myFunc = function () {
22+
var cachekey = JSON.stringify(Array.prototype.slice.call(arguments)),
23+
result;
24+
if (!myFunc.cache[cachekey]) {
25+
result = {};
26+
// ... expensive operation ...
27+
myFunc.cache[cachekey] = result;
28+
}
29+
return myFunc.cache[cachekey];
30+
};
31+
32+
// cache storage
33+
myFunc.cache = {};
34+
35+
var myFunc = function (param) {
36+
var f = arguments.callee,
37+
result;
38+
if (!f.cache[param]) {
39+
result = {};
40+
// ... expensive operation ...
41+
f.cache[param] = result;
42+
}
43+
return f.cache[param];
44+
};
2045

46+
// cache storage
47+
myFunc.cache = {};
2148
</script>
2249
</body>
2350
</html>
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<!doctype html>
2+
<html lang="en">
3+
<head>
4+
<title>JavaScript Patterns</title>
5+
<meta charset="utf-8">
6+
</head>
7+
<body>
8+
<script>
9+
var scareMe = function () {
10+
alert("Boo!");
11+
scareMe = function () {
12+
alert("Double boo!");
13+
};
14+
};
15+
16+
// 1. adding a new property
17+
scareMe.property = "properly";
18+
// 2. assigning to a different name
19+
var prank = scareMe;
20+
// 3. using as a method
21+
var spooky = {
22+
boo: scareMe
23+
};
24+
// calling with a new name
25+
prank(); // "Boo!"
26+
prank(); // "Boo!"
27+
console.log(prank.property); // "properly"
28+
// calling as a method
29+
spooky.boo(); // "Boo!"
30+
spooky.boo(); // "Boo!"
31+
console.log(spooky.boo.property); // "properly"
32+
// using the self-defined function
33+
scareMe(); // Double boo!
34+
scareMe(); // Double boo!
35+
console.log(scareMe.property); // undefined
36+
</script>
37+
</body>
38+
</html>

0 commit comments

Comments
 (0)