-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathobjects.ni
59 lines (51 loc) · 1.47 KB
/
objects.ni
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
* Copyright (c) 2017, Lee Keitel
* This file is released under the BSD 3-Clause license.
*
* This file demonstrates "object-oriented" programming
* using hashmaps.
*/
const account = fn(name) {
// The "object" is declared inside the fntion making it unique
// Since oBalance is not in the dispatch map, it can't be modified
// except through the exposed fntions.
let oBalance = 0
let dispatch = {
"withdraw": nil,
"deposit": nil,
"balance": nil,
}
// "methods" are added as key pairs to the map
dispatch.withdraw = fn(amount) {
if amount > oBalance {
return 'Insufficent balance'
}
oBalance = oBalance - amount
return oBalance
}
dispatch.deposit = fn(amount) {
oBalance = oBalance + amount
return oBalance
}
dispatch.balance = fn() { oBalance }
dispatch.name = name
return dispatch
}
const main = fn() {
let me = account("John Smith")
println(me.name)
println(me.balance())
println(me.deposit(200)) // "methods" are invoked by simply looking up the key in the map
println(me.withdraw(50))
println(me.withdraw(250))
println(me.balance())
// Multiple invocations of account() create new, unique "objects"
let me2 = account("John Smith2")
println(me2.name)
println(me2.balance())
println(me2.deposit(90))
// Show original account was not modified
println(me.name)
println(me.balance())
}
main()