-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWithNullPattern.js
49 lines (42 loc) · 1.06 KB
/
WithNullPattern.js
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
class User {
constructor(id, name) {
this.id = id;
this.name = name;
}
hasAccess() {
return this.name === 'Bob';
}
}
class NullUser {
constructor() {
this.id = -1;
this.name = 'Guest';
}
hasAccess() {
return false;
}
}
const users = [
new User(1, 'Bob'),
new User(2, 'John')
];
function getUser(id) {
const user = users.find(user => user.id === id);
/*
We are now checking if the user is null before returning, and instead returning a NullUser object if the user is null. This means that we no longer need to check for null users later in the code and can treat all users that are returned from this function the same whether they exist or not.
*/
if (user == null) {
return new NullUser();
} else {
return user;
}
}
function printUser(id) {
const user = getUser(id);
console.log('Hello ' + user.name);
if (user.hasAccess()) {
console.log('You have access');
} else {
console.log('You are not allowed here');
}
}