Skip to content

Commit dcbe883

Browse files
committed
Add js way example
1 parent 580d230 commit dcbe883

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

JavaScript/5-js-way.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
'use strict';
2+
3+
const flyweightPool = new Map();
4+
5+
const getFlyweight = (shared) => {
6+
const { char, font, size } = shared;
7+
const key = `${char}:${font}:${size}`;
8+
let flyweight = flyweightPool.get(key);
9+
if (!flyweight) {
10+
flyweight = Object.freeze({ ...shared });
11+
flyweightPool.set(key, flyweight);
12+
}
13+
return flyweight;
14+
};
15+
16+
const createChar = (char, font, size, row, col) => {
17+
const intrinsic = getFlyweight({ char, font, size });
18+
return { intrinsic, row, col };
19+
};
20+
21+
// Usage
22+
23+
const a1 = createChar('A', 'Arial', 12, 0, 0);
24+
const a2 = createChar('A', 'Arial', 12, 0, 5);
25+
console.log(a1.intrinsic === a2.intrinsic);

0 commit comments

Comments
 (0)