diff --git a/packages/backend/src/Chain.ts b/packages/backend/src/Chain.ts index 7a6c5bb..bc95389 100644 --- a/packages/backend/src/Chain.ts +++ b/packages/backend/src/Chain.ts @@ -2,7 +2,7 @@ import * as EventEmitter from 'events'; import Node from './Node'; import Feed from './Feed'; import FeedSet from './FeedSet'; -import { Maybe, Types, FeedMessage } from '@dotstats/common'; +import { Maybe, Types, FeedMessage, blockAverage } from '@dotstats/common'; const BLOCK_TIME_HISTORY = 10; @@ -112,17 +112,7 @@ export default class Chain { private updateAverageBlockTime(height: Types.BlockNumber, now: Types.Timestamp) { this.blockTimes[height % BLOCK_TIME_HISTORY] = now - this.blockTimestamp; - let sum = 0; - let count = 0; - - for (const time of this.blockTimes) { - if (time) { - sum += time; - count += 1; - } - } - // We are guaranteed that count > 0 - this.averageBlockTime = (sum / count) as Types.Milliseconds; + this.averageBlockTime = blockAverage(this.blockTimes); } } diff --git a/packages/backend/src/Node.ts b/packages/backend/src/Node.ts index 40637a1..fd5b10e 100644 --- a/packages/backend/src/Node.ts +++ b/packages/backend/src/Node.ts @@ -1,6 +1,7 @@ import * as WebSocket from 'ws'; import * as EventEmitter from 'events'; -import { noop, timestamp, Maybe, Types, idGenerator } from '@dotstats/common'; + +import { noop, timestamp, Maybe, Types, idGenerator, blockAverage } from '@dotstats/common'; import { parseMessage, getBestBlock, Message, BestBlock, SystemInterval } from './message'; import { locate, Location } from './location'; @@ -176,22 +177,8 @@ export default class Node { return location ? [location.lat, location.lon, location.city] : null; } - public get average(): number { - let accounted = 0; - let sum = 0; - - for (const time of this.blockTimes) { - if (time) { - accounted += 1; - sum += time; - } - } - - if (accounted === 0) { - return 0; - } - - return sum / accounted; + public get average(): Types.Milliseconds { + return blockAverage(this.blockTimes); } public get localBlockAt(): Types.Milliseconds { diff --git a/packages/common/src/block.ts b/packages/common/src/block.ts new file mode 100644 index 0000000..c48fc32 --- /dev/null +++ b/packages/common/src/block.ts @@ -0,0 +1,19 @@ +import { Milliseconds } from './types'; + +export function blockAverage(blockTimes: Array): Milliseconds { + let count = 0; + let sum = 0; + + for (const time of blockTimes) { + if (time) { + count += 1; + sum += time; + } + } + + if (count === 0) { + return 0 as Milliseconds; + } + + return (sum / count) as Milliseconds; +} diff --git a/packages/common/src/index.ts b/packages/common/src/index.ts index c330025..aeb1ad4 100644 --- a/packages/common/src/index.ts +++ b/packages/common/src/index.ts @@ -1,5 +1,6 @@ export * from './helpers'; export * from './id'; +export * from './block'; import * as Types from './types'; import * as FeedMessage from './feed';