UNPKG

@testyard/stats

Version:
113 lines (110 loc) 3.72 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 StringStats { constructor() { this._strings = {}; this._characters = {}; this._lowestLength = NaN; this._highestLength = NaN; this._sumLength = NaN; this._numStrings = 0; this._numStringsAdded = 0; this._numCharactersAdded = 0; this._isSummarized = false; this.add = (string) => { if (typeof string !== 'string') { throw new Error(`string must be typeof === 'string', got: typeof === '${typeof string}'.`); } if (!(string in this._strings)) { this._strings[string] = 0; } this._strings[string]++; this._numStringsAdded++; const chars = string.split(''); for (const char of chars) { if (!(char in this._characters)) { this._characters[char] = 0; } this._characters[char]++; this._numCharactersAdded++; } }; } get result() { // @ts-expect-error const object = {}; const props = { characters: { get: () => { this._summarize(); return Object .keys(this._characters) .sort() .join(''); } }, lowestLength: { get: () => { this._summarize(); return this._lowestLength; } }, highestLength: { get: () => { this._summarize(); return this._highestLength; } }, averageLength: { get: () => { this._summarize(); return this._sumLength / this._numStrings; } } }; Object.defineProperties(object, props); return object; } _summarize() { if (!this._isSummarized) { // for (const [key, value] of Object.entries(this._characters)) { // this._characters[key] = value / this._numCharactersAdded // } this._numStrings = Object.keys(this._strings).length; for (const key of Object.keys(this._strings)) { const length = key.length; // eslint-disable-next-line no-self-compare if (this._lowestLength !== this._lowestLength) { this._lowestLength = length; } if (this._lowestLength > length) { this._lowestLength = length; } // eslint-disable-next-line no-self-compare if (this._highestLength !== this._highestLength) { this._highestLength = length; } if (this._highestLength < length) { this._highestLength = length; } // eslint-disable-next-line no-self-compare if (this._sumLength !== this._sumLength) { this._sumLength = 0; } this._sumLength += length; } this._isSummarized = true; } } } module.exports = StringStats; //# sourceMappingURL=index.js.map