-
Notifications
You must be signed in to change notification settings - Fork 0
/
5-Mappings.sol
70 lines (58 loc) · 2.02 KB
/
5-Mappings.sol
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
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract FavoriteRecords {
mapping(string => bool) public approvedRecords;
mapping(address => mapping(string => bool)) public userFavorites;
string[] private approvedAlbumList;
error NotApproved(string albumName);
constructor() {
string[9] memory albums = [
"Thriller",
"Back in Black",
"The Bodyguard",
"The Dark Side of the Moon",
"Their Greatest Hits (1971-1975)",
"Hotel California",
"Come On Over",
"Rumours",
"Saturday Night Fever"
];
for (uint i = 0; i < albums.length; i++) {
approvedRecords[albums[i]] = true;
approvedAlbumList.push(albums[i]);
}
}
function getApprovedRecords() public view returns (string[] memory) {
return approvedAlbumList;
}
function addRecord(string memory albumName) public {
if (!approvedRecords[albumName]) {
revert NotApproved(albumName);
}
userFavorites[msg.sender][albumName] = true;
}
function getUserFavorites(address user) public view returns (string[] memory) {
uint favoriteCount = 0;
for (uint i = 0; i < approvedAlbumList.length; i++) {
if (userFavorites[user][approvedAlbumList[i]]) {
favoriteCount++;
}
}
string[] memory favorites = new string[](favoriteCount);
uint index = 0;
for (uint i = 0; i < approvedAlbumList.length; i++) {
if (userFavorites[user][approvedAlbumList[i]]) {
favorites[index] = approvedAlbumList[i];
index++;
}
}
return favorites;
}
function resetUserFavorites() public {
for (uint i = 0; i < approvedAlbumList.length; i++) {
if (userFavorites[msg.sender][approvedAlbumList[i]]) {
userFavorites[msg.sender][approvedAlbumList[i]] = false;
}
}
}
}