Skip to content

Commit 09fcaa6

Browse files
committed
add abs function to Math library
1 parent 1e77b69 commit 09fcaa6

File tree

3 files changed

+21
-0
lines changed

3 files changed

+21
-0
lines changed

contracts/utils/Math.sol

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,15 @@
33
pragma solidity ^0.8.8;
44

55
library Math {
6+
/**
7+
* @notice calculate the absolute value of a number
8+
* @param a number whose absoluve value to calculate
9+
* @return absolute value
10+
*/
11+
function abs(int256 a) internal pure returns (uint256) {
12+
return uint256(a < 0 ? -a : a);
13+
}
14+
615
/**
716
* @notice select the greater of two numbers
817
* @param a first number

contracts/utils/MathMock.sol

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@ import { Math } from './Math.sol';
77
contract MathMock {
88
using Math for uint256;
99

10+
function abs(int256 a) external pure returns (uint256) {
11+
return Math.abs(a);
12+
}
13+
1014
function max(uint256 a, uint256 b) external pure returns (uint256) {
1115
return Math.max(a, b);
1216
}

test/utils/Math.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,14 @@ describe('Math', function () {
1111
});
1212

1313
describe('__internal', function () {
14+
describe('#abs(int256)', function () {
15+
it('returns the absolute value of a number', async () => {
16+
expect(await instance.callStatic.abs(-1)).to.equal(1);
17+
expect(await instance.callStatic.abs(0)).to.equal(0);
18+
expect(await instance.callStatic.abs(1)).to.equal(1);
19+
});
20+
});
21+
1422
describe('#max(uint256,uint256)', function () {
1523
it('returns the greater of two numbers', async () => {
1624
expect(

0 commit comments

Comments
 (0)