UNPKG

@testyard/stats

Version:
132 lines (129 loc) 4.27 kB
/*! * @testyard/stats v1.4.1 * https://github.com/testyardjs/stats * * Copyright (c) 2023 Richard King <richrdkng@gmail.com> (https://richrdkng.com) * Released under the MIT License * https://github.com/testyardjs/stats/blob/main/LICENSE * * Date: 2023-07-19T13:11:26.750Z */ 'use strict'; class CharacterStats { constructor() { this._result = {}; this._numCharacters = 0; this._lowestValue = NaN; this._highestValue = NaN; this._sumValue = NaN; this._numAdded = 0; this._isSummarized = false; this.add = (character) => { const chars = []; if (typeof character === 'string') { chars.push(...character.split('')); } else if (Array.isArray(character)) { for (const entry of character) { chars.push(...entry.split('')); } } for (const char of chars) { if (!(char in this._result)) { this._result[char] = 0; } this._result[char]++; this._numAdded++; } }; } get result() { // @ts-expect-error const object = { of: (character) => { this._summarize(); if (character.length > 1) { throw new Error(`character ${character} must be .length === 1, got .length === ${character.length}.`); } if (!(character in this._result)) { throw new Error(`character ${character} is not in the results.`); } return this._result[character]; } }; const props = { entries: { get: () => { this._summarize(); return { ...this._result }; } }, characters: { get: () => { this._summarize(); return Object .keys(this._result) .sort(); } }, numCharacters: { get: () => { this._summarize(); return this._numCharacters; } }, lowestValue: { get: () => { this._summarize(); return this._lowestValue; } }, highestValue: { get: () => { this._summarize(); return this._highestValue; } }, averageValue: { get: () => { this._summarize(); return this._sumValue / this._numCharacters; } } }; Object.defineProperties(object, props); return object; } _summarize() { if (!this._isSummarized) { for (const [key, value] of Object.entries(this._result)) { this._result[key] = value / this._numAdded; } this._numCharacters = Object.keys(this._result).length; for (const value of Object.values(this._result)) { // eslint-disable-next-line no-self-compare if (this._lowestValue !== this._lowestValue) { this._lowestValue = value; } if (this._lowestValue > value) { this._lowestValue = value; } // eslint-disable-next-line no-self-compare if (this._highestValue !== this._highestValue) { this._highestValue = value; } if (this._highestValue < value) { this._highestValue = value; } // eslint-disable-next-line no-self-compare if (this._sumValue !== this._sumValue) { this._sumValue = 0; } this._sumValue += value; } this._isSummarized = true; } } } module.exports = CharacterStats; //# sourceMappingURL=index.js.map