-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
230403 | add five lines code chapter 06-02
- Loading branch information
1 parent
15a57af
commit 13de36f
Showing
3 changed files
with
147 additions
and
70 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
const database = { | ||
find: (to: string) => { return 12345 }, | ||
updateOne: (accountId: number, v: any) => {} | ||
} | ||
|
||
// bad | ||
function accountDeposit(to: string, amount: number) { | ||
let accountId = database.find(to); | ||
database.updateOne(accountId, { $inc: { balance: amount } }); | ||
} | ||
|
||
function accountTransfer(amount: number, from: string, to: string) { | ||
accountDeposit(from, -amount); | ||
accountDeposit(to, amount); | ||
} | ||
|
||
// good | ||
class Account { | ||
private deposit(to: string, amount: number) { | ||
let accountId = database.find(to); | ||
database.updateOne(accountId, { $inc: { balance: amount } }); | ||
} | ||
|
||
transfer(amount: number, from: string, to: string) { | ||
this.deposit(from, -amount); | ||
this.deposit(to, amount); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
// before | ||
// let counter = 0; | ||
// function incrementCounter() { | ||
// counter++; | ||
// } | ||
|
||
// function main() { | ||
// for (let i = 0; i < 20; i++) { | ||
// incrementCounter(); | ||
// console.log(counter); | ||
// } | ||
// } | ||
|
||
// after | ||
class Counter { | ||
private counter = 0; | ||
getCounter() { | ||
return this.counter; | ||
} | ||
|
||
setCounter(c: number) { | ||
this.counter = c; | ||
} | ||
} | ||
|
||
function incrementCounter(counter: Counter) { | ||
counter.setCounter(counter.getCounter() + 1); | ||
} | ||
|
||
let counter = new Counter(); | ||
function main() { | ||
for (let i = 0; i < 20; i++) { | ||
incrementCounter(counter); | ||
console.log(counter.getCounter()); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters