Repository navigation
Expand file tree
/
Copy pathUser.java
More file actions
115 lines (95 loc) · 2.86 KB
/
Copy pathUser.java
File metadata and controls
115 lines (95 loc) · 2.86 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import static java.util.Collections.unmodifiableList;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONObject;
/** POJO representing a User in the database. */
public class User {
private final String name;
private final List<Iou> owes;
private final List<Iou> owedBy;
private User(String name, List<Iou> owes, List<Iou> owedBy) {
this.name = name;
this.owes = new ArrayList<>(owes);
this.owedBy = new ArrayList<>(owedBy);
}
public String name() {
return name;
}
/** IOUs this user owes to other users. */
public List<Iou> owes() {
return unmodifiableList(owes);
}
public double getAmountOwedTo(String other) {
return owes().stream()
.filter(iou -> iou.name.equals(other))
.map(iou -> iou.amount)
.findFirst()
.orElse(0.0);
}
/** IOUs other users owe to this user. */
public List<Iou> owedBy() {
return unmodifiableList(owedBy);
}
public double getAmountOwedBy(String other) {
return owedBy().stream()
.filter(iou -> iou.name.equals(other))
.map(iou -> iou.amount)
.findFirst()
.orElse(0.0);
}
public static Builder builder() {
return new Builder();
}
public JSONObject toJson() {
JSONObject object =
new JSONObject()
.put("name", name())
.put("owes", owesToJson())
.put("owedBy", owedByToJson())
.put("balance", balance());
return object;
}
private JSONObject owesToJson() {
return iousToJson(owes());
}
private JSONObject owedByToJson() {
return iousToJson(owedBy());
}
private static JSONObject iousToJson(List<Iou> ious) {
JSONObject object = new JSONObject();
for (Iou iou : ious) {
object.put(iou.name, iou.amount);
}
return object;
}
private double balance() {
double balance = 0.0;
for (Iou iou : owes()) {
balance -= iou.amount;
}
for (Iou iou : owedBy()) {
balance += iou.amount;
}
return balance;
}
public static class Builder {
private String name;
private final List<Iou> owes = new ArrayList<>();
private final List<Iou> owedBy = new ArrayList<>();
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder owes(String name, double amount) {
owes.add(new Iou(name, amount));
return this;
}
public Builder owedBy(String name, double amount) {
owedBy.add(new Iou(name, amount));
return this;
}
public User build() {
return new User(name, owes, owedBy);
}
}
}