Skip to content

Commit eb0fac0

Browse files
committed
Improve examples
1 parent f2ea240 commit eb0fac0

File tree

3 files changed

+28
-16
lines changed

3 files changed

+28
-16
lines changed

Classification/5-abstract.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@ class CreditAccount extends Account {
1818
}
1919
}
2020

21-
const accounts: Account[] = [new SavingsAccount(5000), new CreditAccount(-750)];
21+
const a1 = new SavingsAccount(5000);
22+
console.log(a1.describe());
2223

23-
for (const account of accounts) {
24-
console.log(account.describe());
25-
}
24+
const a2 = new CreditAccount(-750);
25+
console.log(a2.describe());

Classification/6-protocol.js

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,13 @@
22

33
// Subtype polymorphism: protocol/duck typing
44

5-
const describe = (entity) => {
6-
if (typeof entity.describe !== 'function') {
7-
throw new TypeError('Requires describe method');
8-
}
9-
entity.describe();
10-
};
11-
125
class SavingsAccount {
136
constructor(balance) {
147
this.balance = balance;
158
}
169

1710
describe() {
18-
console.log(`Savings -> Balance: ${this.balance}`);
11+
return `Savings -> Balance: ${this.balance}`;
1912
}
2013
}
2114

@@ -25,9 +18,24 @@ class CreditAccount {
2518
}
2619

2720
describe() {
28-
console.log(`Credit -> Balance: ${this.balance}`);
21+
return `Credit -> Balance: ${this.balance}`;
2922
}
3023
}
3124

32-
describe(new SavingsAccount(5000));
33-
describe(new CreditAccount(-750));
25+
const getInfo = (entity) => {
26+
if (typeof entity.describe !== 'function') {
27+
throw new TypeError('Requires describe method');
28+
}
29+
const res = entity.describe();
30+
console.log(res);
31+
};
32+
33+
const account = {
34+
describe() {
35+
return 'Stub account';
36+
},
37+
};
38+
39+
getInfo(account);
40+
getInfo(new SavingsAccount(5000));
41+
getInfo(new CreditAccount(-750));

Classification/7-dynamic.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,11 @@ class CreditAccount extends Account {
2424
}
2525
}
2626

27-
const accounts = [new SavingsAccount(5000), new CreditAccount(-750)];
27+
const accounts = [
28+
new SavingsAccount(5000),
29+
new CreditAccount(-750),
30+
{ describe: () => 'Account stub' },
31+
];
2832

2933
for (const account of accounts) {
3034
console.log(account.describe());

0 commit comments

Comments
 (0)