"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.SimpleHistogram = void 0; var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var _lodash = require("lodash"); /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ class SimpleHistogram { constructor(max, bucketSize) { (0, _defineProperty2.default)(this, "maxValue", void 0); (0, _defineProperty2.default)(this, "bucketSize", void 0); (0, _defineProperty2.default)(this, "histogramBuckets", []); if (bucketSize > max) { throw new Error(`bucket size cannot be greater than value range`); } this.maxValue = max; this.bucketSize = bucketSize; this.initializeBuckets(); } reset() { for (let i = 0; i < this.histogramBuckets.length; i++) { this.histogramBuckets[i].count = 0; } } record(value) { if (value < 0 || value > this.maxValue) { return; } for (let i = 0; i < this.histogramBuckets.length; i++) { if (value >= this.histogramBuckets[i].min && value < this.histogramBuckets[i].max) { this.histogramBuckets[i].count++; break; } } } get(truncate = false) { let histogramToReturn = this.histogramBuckets; if (truncate) { var _last$index, _last; // find the index of the last bucket with a non-zero value const nonZeroCountsWithIndex = this.histogramBuckets.map((bucket, index) => ({ count: bucket.count, index })).filter(({ count }) => count > 0); const lastNonZeroIndex = nonZeroCountsWithIndex.length > 0 ? (_last$index = (_last = (0, _lodash.last)(nonZeroCountsWithIndex)) === null || _last === void 0 ? void 0 : _last.index) !== null && _last$index !== void 0 ? _last$index : -1 : -1; histogramToReturn = lastNonZeroIndex >= 0 ? this.histogramBuckets.slice(0, lastNonZeroIndex + 1) : []; } return histogramToReturn.map(bucket => ({ count: bucket.count, value: bucket.max })); } initializeBuckets() { let i = 0; while (i < this.maxValue) { this.histogramBuckets.push({ min: i, max: i + Math.min(this.bucketSize, this.maxValue), count: 0 }); i += this.bucketSize; } } } exports.SimpleHistogram = SimpleHistogram;