-
Notifications
You must be signed in to change notification settings - Fork 0
/
advanced-libraries.sol
65 lines (56 loc) · 1.65 KB
/
advanced-libraries.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
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;
library Search{
function indexOf(uint[] storage self, uint value) public view returns(uint) {
for(uint i=0; i<self.length; i++) if(self[i] == value) return i;
}
}
contract Test{
uint [] data;
constructor() {
data.push(1);
data.push(2);
data.push(3);
data.push(4);
data.push(5);
}
function isValuePresent(uint val) external view returns(uint) {
uint value = val;
uint index = Search.indexOf(data, value);
return index;
}
}
/*
The directive using 'A for B'; can be used to attach library functions of library A to a given type B.
These functions will use the caller type as their first parameter (identified using self).
---------
Exercise:
---------
1. Copy over the library Search and the contract Test below
and rename library Search to Search2 and contract Test to Test2.
2. Using the A for B library pattern assign the new library to an empty array type
and
rewrite the code so that we can run the same search hardcoded this time to the value of 4
accordingly.
*/
library Search2{
function indexOf(uint[] storage self, uint value) public view returns(uint) {
for(uint i=0; i<self.length; i++) if(self[i] == value) return i;
}
}
contract Test2{
using Search2 for uint[];
uint [] data;
constructor() {
data.push(1);
data.push(2);
data.push(3);
data.push(4);
data.push(5);
}
function isValuePresent() external view returns(uint) {
uint value = 4;
uint index = Search.indexOf(data, value);
return index;
}
}