Add approximatelyEqual

This commit is contained in:
Angelos Chalaris
2018-02-14 12:47:13 +02:00
parent a8caa9c75d
commit ba59e8020a
5 changed files with 46 additions and 4 deletions

View File

@ -0,0 +1,14 @@
### approximatelyEqual
Checks if two numbers are approximately equal to each other.
Use `Math.abs()` to compare the absolute difference of the two values to `epsilon`.
Omit the third parameter, `epsilon`, to use a default value of `0.001`.
```js
const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon;
```
```js
approximatelyEqual(Math.PI / 2.0 , 1.5708); // true
```

View File

@ -1,4 +1,5 @@
anagrams:string,recursion
approximatelyEqual:math
arrayToHtmlList:browser,array
ary:adapter,function
atob:node,string,utility

View File

@ -0,0 +1,2 @@
const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon;
module.exports = approximatelyEqual;

View File

@ -0,0 +1,17 @@
const test = require('tape');
const approximatelyEqual = require('./approximatelyEqual.js');
test('Testing approximatelyEqual', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof approximatelyEqual === 'function', 'approximatelyEqual is a Function');
t.true(approximatelyEqual(Math.PI / 2.0 , 1.5708), 'Works for PI / 2');
t.true(approximatelyEqual(0.1 + 0.2, 0.3), 'Works for 0.1 + 0.2 === 0.3');
t.true(approximatelyEqual(0.5, 0.5), 'Works for exactly equal values');
t.true(approximatelyEqual(0.501, 0.5, 0.1), 'Works for a custom epsilon');
//t.deepEqual(approximatelyEqual(args..), 'Expected');
//t.equal(approximatelyEqual(args..), 'Expected');
//t.false(approximatelyEqual(args..), 'Expected');
//t.throws(approximatelyEqual(args..), 'Expected');
t.end();
});

View File

@ -1,4 +1,4 @@
Test log for: Wed Feb 14 2018 12:33:42 GMT+0200 (GTB Standard Time)
Test log for: Wed Feb 14 2018 12:46:59 GMT+0200 (GTB Standard Time)
> 30-seconds-of-code@0.0.1 test G:\My Files\git Repositories\30-seconds-of-code
> tape test/**/*.test.js | tap-spec
@ -11,6 +11,14 @@ Test log for: Wed Feb 14 2018 12:33:42 GMT+0200 (GTB Standard Time)
√ Works for single-letter strings
√ Works for empty strings
Testing approximatelyEqual
√ approximatelyEqual is a Function
√ Works for PI / 2
√ Works for 0.1 + 0.2 === 0.3
√ Works for exactly equal values
√ Works for a custom epsilon
Testing arrayToHtmlList
√ arrayToHtmlList is a Function
@ -1839,8 +1847,8 @@ Test log for: Wed Feb 14 2018 12:33:42 GMT+0200 (GTB Standard Time)
√ Works with multiple promises
total: 919
passing: 919
duration: 2.4s
total: 924
passing: 924
duration: 2.5s