-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathfibonacci.js
71 lines (56 loc) · 1.6 KB
/
fibonacci.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
Name: fibonacci
Description: This function calculates fibonacci numbers for endless iterations
Author: Franklin (https://fvdm.com)
Source & docs: https://github.com/fvdm/nodejs-fibonacci
Contact: https://github.com/fvdm/nodejs-fibonacci/issues
License: Unlicense (Public Domain, see LICENSE file)
*/
const bignum = require( 'bn.js' );
const { EventEmitter } = require( 'events' );
module.exports = new EventEmitter();
module.exports.doWhile = false;
/**
* Start iteration
*
* @param {number} [limit=0] Run fibonacci iterations
* @return {object} result
*/
module.exports.iterate = function ( limit = 0 ) {
let next = new bignum( 1 );
let cur = new bignum( -1 );
let last = new bignum( 0 );
let loop = new bignum( 0 );
let start = new Date().getTime();
let result = {};
limit = limit && new bignum( limit );
module.exports.doWhile = true;
while ( module.exports.doWhile ) {
// prev cur -> now last
// prev next -> now cur
last = cur;
cur = next;
next = cur.add( last );
result.number = next.toString();
result.length = next.toString().length;
result.iterations = loop.toString();
result.ms = new Date().getTime() - start;
module.exports.emit( 'result', result );
// found the one
if ( limit && loop.eq( limit ) ) {
module.exports.doWhile = false;
module.exports.emit( 'done', result );
}
// count
loop = loop.add( new bignum( 1 ) );
}
return result;
};
/**
* Stop iteration
*
* @return {void}
*/
module.exports.kill = function () {
module.exports.doWhile = false;
};