Untitled conversation
- Usercode
- Assistant
import { Axis } from 'highcharts';
import { AdditionalProperties, MeasurementUnit, UnitProperties } from '~/api';
import { getRoundUpToValue, getRoundingValue } from '~/utils';
import { ExtendedAxis, ExtendedSeriesOptions, ExtendedSeriesOptionsType } from '../types';
const TICK_MAX_COUNT = 10;
const DEFAULT_INTERVAL = 1;
const MIN_INTERVAL = 0.01;
const DEFAULT_SERIES = 'defaultSeries';
const limits = new Map();
function getIntervalTick(delta: number, step: number): number {
let tickCount = delta / step;
let tick = 0;
let newStep = step;
if (tickCount > TICK_MAX_COUNT) {
while (tickCount > TICK_MAX_COUNT) {
tick += newStep;
tickCount = delta / tick;
}
} else if (tickCount < TICK_MAX_COUNT / 2) {
newStep /= 10;
return getIntervalTick(delta, newStep);
} else {
tick = newStep;
}
return tick;
}
function getTick(delta: number, accuracy: number) {
let step = DEFAULT_INTERVAL;
if (delta < MIN_INTERVAL) {
return step;
}
const interval = delta / TICK_MAX_COUNT;
if (step < interval) {
while (step * 10 < delta) {
step *= 10;
}
} else {
while (step * 10 > delta) {
step /= 10;
}
}
const tick = getIntervalTick(delta, step);
const accuracyTick = 10 ** -accuracy;
if (tick < accuracyTick) {
return accuracyTick;
}
return tick;
}
const getAccuracyFromAxis = (axis: ExtendedAxis): number => {
const { chart } = axis || {};
const { series } = chart || {};
const [firstSeries] = series || [];
const { options } = firstSeries || {};
const { measurementUnit = {} as MeasurementUnit, properties } = (options as ExtendedSeriesOptionsType) || {};
const { accuracy = 1 } = measurementUnit || {};
const { physicalValue, originalParameterUnit } = properties || ({} as UnitProperties);
return getRoundUpToValue(physicalValue, originalParameterUnit, accuracy);
};
export function linearTickPositioner(this: Axis): number[] {
let positions: number[] = [];
let min;
let max;
let name;
const axis = this as ExtendedAxis;
const accuracy = getAccuracyFromAxis(axis);
const { min: userMin, max: userMax } = axis.userOptions;
const { series } = axis;
const [firstSeries] = series;
if (firstSeries) {
const { userOptions, options } = firstSeries;
const { anomalies, fullName: paramName } = userOptions as ExtendedSeriesOptions;
const { lowerLimit: isEnableLowerLimit, upperLimit: isEnableUpperLimit } = options as ExtendedSeriesOptions;
if (paramName !== DEFAULT_SERIES) {
name = paramName;
}
if (name) {
limits.set(name, {
lowerLimit: {
dataMin: axis.dataMin,
selected: isEnableLowerLimit,
},
upperLimit: {
dataMax: axis.dataMax,
selected: isEnableUpperLimit,
},
});
}
if (anomalies?.length) {
const [firstAnomaly] = anomalies;
const { algSettings, additionalProperties } = firstAnomaly;
const { lowerLimit: lowerLimitValue, upperLimit: upperLimitValue } = algSettings;
const { lowerRange, upperRange } = additionalProperties as AdditionalProperties;
const curLimit = limits.get(name);
limits.set(name, {
lowerLimit: {
...curLimit.lowerLimit,
value: lowerLimitValue || lowerRange,
},
upperLimit: {
...curLimit.upperLimit,
value: upperLimitValue || upperRange,
},
});
}
}
const curLimit = limits.get(name);
const { lowerLimit, upperLimit } = curLimit || {};
const { dataMin, selected: lowerLimitSelected, value: lowerLimitValue } = lowerLimit || {};
const { dataMax, selected: upperLimitSelected, value: upperLimitValue } = upperLimit || {};
if (lowerLimitSelected && upperLimitSelected) {
min = lowerLimitValue > dataMin ? dataMin : lowerLimitValue;
max = upperLimitValue > dataMax ? upperLimitValue : dataMax;
} else if (lowerLimitSelected && !upperLimitSelected) {
min = lowerLimitValue > dataMin ? dataMin : lowerLimitValue;
max = dataMax;
} else if (!lowerLimitSelected && upperLimitSelected) {
if (upperLimitValue > dataMin && upperLimitValue > dataMax) {
max = upperLimitValue;
min = dataMin;
}
if (upperLimitValue > dataMin && upperLimitValue < dataMax) {
max = dataMax;
min = dataMin;
}
if (upperLimitValue < dataMin) {
max = dataMax;
min = upperLimitValue;
}
} else {
min = dataMin;
max = dataMax;
}
if (max !== null && min !== null) {
if (userMin != null && userMax !== undefined && userMax !== null) {
min = userMin;
max = userMax;
} else {
const delta = max - min > MIN_INTERVAL * 10 ? (max - min) / 10 : MIN_INTERVAL;
min -= delta;
max += delta;
}
const tick = getTick(max - min, accuracy);
if (min < 0) {
// заполняем отрицательную ось ординат
for (let nextTick = -tick; nextTick >= min; nextTick -= tick) {
if (nextTick > min && nextTick < max) {
positions.unshift(nextTick);
}
}
positions.unshift(min);
} else {
positions = [min];
}
if (max > 0) {
for (let nextTick = 0; nextTick <= max; nextTick += tick) {
if (nextTick > min) {
positions.push(nextTick);
}
}
}
positions.push(max);
// удаляем "слипшиеся" тики
if (Math.abs(positions[0] - positions[1]) < tick / 2 && positions.length > 2) {
positions.splice(1, 1);
}
const { length } = positions;
if (Math.abs(positions[length - 1] - positions[length - 2]) < tick / 2 && length > 2) {
positions.splice(length - 2, 1);
}
}
const result: number[] = positions
.filter((value) => !Number.isNaN(value))
.map((value) => getRoundingValue(value, accuracy));
if (limits.size) {
if (curLimit) {
limits.set(name, {
lowerLimit: {
...curLimit.lowerLimit,
minYAxisValue: result[0],
},
upperLimit: {
...curLimit.upperLimit,
maxYAxisValue: result[result.length - 1],
},
});
}
return result;
}
return [];
}
export function limitYAxisPositioner(this: Axis) {
const axis = this as unknown as ExtendedAxis;
const accuracy = getAccuracyFromAxis(axis);
let curLimit;
let min;
let max;
const { series } = axis;
const [firstSeries] = series;
if (firstSeries) {
const { userOptions } = firstSeries;
const { fullName } = userOptions as ExtendedSeriesOptions;
curLimit = limits.get(fullName);
const { lowerLimit: curLowerLimit, upperLimit: curUpperLimit } = curLimit || {};
const { dataMin, selected: lowerLimitSelected, value: lowerLimitValue } = curLowerLimit || {};
const { dataMax, selected: upperLimitSelected, value: upperLimitValue } = curUpperLimit || {};
if (lowerLimitSelected && upperLimitSelected) {
min = lowerLimitValue;
max = upperLimitValue;
} else if (lowerLimitSelected && !upperLimitSelected) {
min = lowerLimitValue;
max = dataMax;
} else if (!lowerLimitSelected && upperLimitSelected) {
min = dataMin;
max = upperLimitValue;
} else {
min = dataMin;
max = dataMax;
}
} else {
return [];
}
const { upperLimit, lowerLimit } = curLimit || {};
const { selected: upperLimitSelected, maxYAxisValue } = upperLimit || {};
const { selected: lowerLimitSelected, minYAxisValue } = lowerLimit || {};
const positions = [
minYAxisValue ? getRoundingValue(minYAxisValue, accuracy) : undefined,
upperLimitSelected && max ? getRoundingValue(max, accuracy) : undefined,
lowerLimitSelected && min ? getRoundingValue(min, accuracy) : undefined,
maxYAxisValue ? getRoundingValue(maxYAxisValue, accuracy) : undefined,
] as number[];
return positions.filter((value) => value !== undefined);
}
Hi! This code is written in typescript in the react application. The linearTickPositioner function describes a custom function to calculate tickPositioner in highcharts. The values in the limits variable can be different depending on the data coming from the server. limits is responsible for the upper and lower limit of the measurement range. limitYAxisPositioner describes a separate scale on which the values from limits are displayed. The limits themselves are common to both functions. The function getRoundingValue performs rounding of values. Please note that the data coming from the server may not be valid and should be checked, and because of asynchronousness in react, the code may start executing before the data arrives.
1.Optimise and refactor all this code to make it simpler, faster and clearer. Use all modern typescript functionality. 2. Add variants of linearTickPositioner function when logarithmic type is selected in highcharts. It should contain no more than 10 ticks considering the values from limits 3. Add variants of the function limitYAxisPositioner with the selected logarithmic type in highcharts. It should contain the minimum and maximum value on the chart and the upper and lower range of measurements, if any. Use all modern features of typescript, javascript, react. Check all new code for bugs and fix them. Remove all unused code
Certainly! Here’s a refactored version of your code that’s more concise, leverages modern TypeScript functionality, and supports both linear and logarithmic scales. I’ve also ensured that the data fetched from the server is validated and handled asynchronously if needed.
Note that I made some assumptions based on the provided code. Adjustments may be required based on specific requirements of your application and server responses.
import { Axis } from 'highcharts';
import { AdditionalProperties, MeasurementUnit, UnitProperties } from '~/api';
import { getRoundUpToValue, getRoundingValue } from '~/utils';
import { ExtendedAxis, ExtendedSeriesOptions, ExtendedSeriesOptionsType } from '../types';
const TICK_MAX_COUNT = 10;
const DEFAULT_INTERVAL = 1;
const MIN_INTERVAL = 0.01;
const DEFAULT_SERIES = 'defaultSeries';
const DEFAULT_ACCURACY = 1;
const limits = new Map<string, any>();
type Limit = {
dataMin?: number;
dataMax?: number;
value?: number;
selected?: boolean;
};
type AxisLimits = {
lowerLimit?: Limit;
upperLimit?: Limit;
};
function getIntervalTick(delta: number, step: number): number {
let tickCount = delta / step;
while (tickCount > TICK_MAX_COUNT) {
step *= 2;
tickCount = delta / step;
}
while (tickCount < TICK_MAX_COUNT / 2) {
step /= 2;
tickCount = delta / step;
}
return step;
}
function getTick(delta: number, accuracy: number): number {
if (delta < MIN_INTERVAL) return DEFAULT_INTERVAL;
const baseStep = MIN_INTERVAL * 10 ** Math.floor(Math.log10(delta / TICK_MAX_COUNT));
const intervalStep = getIntervalTick(delta, baseStep);
return Math.max(intervalStep, 10 ** -accuracy);
}
function getAccuracyFromAxis(axis: ExtendedAxis): number {
const { series } = axis.chart;
const firstSeriesOptions = series[0]?.options as ExtendedSeriesOptionsType;
if (!firstSeriesOptions) return DEFAULT_ACCURACY;
const { measurementUnit = {} as MeasurementUnit, properties = {} as UnitProperties } = firstSeriesOptions;
const { accuracy = DEFAULT_ACCURACY, physicalValue, originalParameterUnit } = measurementUnit || properties;
return getRoundUpToValue(physicalValue, originalParameterUnit, accuracy);
}
function calculateMinMaxAndTicks(axis: ExtendedAxis, accuracy: number, logarithmic = false) {
const { min: userMin, max: userMax } = axis.userOptions;
const currentSeries = axis.series[0];
const paramName = currentSeries?.userOptions.fullName || DEFAULT_SERIES;
let min: number | null = null;
let max: number | null = null;
if (paramName && limits.has(paramName)) {
const { lowerLimit, upperLimit } = limits.get(paramName);
const { dataMin, selected: lowerLimitSelected, value: lowerLimitValue } = lowerLimit || {};
const { dataMax, selected: upperLimitSelected, value: upperLimitValue } = upperLimit || {};
if (lowerLimitSelected) min = Math.min(dataMin || Infinity, lowerLimitValue || Infinity);
if (upperLimitSelected) max = Math.max(dataMax || -Infinity, upperLimitValue || -Infinity);
}
min = userMin ?? min ?? axis.min;
max = userMax ?? max ?? axis.max;
if (logarithmic && min && max) {
min = Math.max(min, 1e-30);
max = Math.max(max, min + MIN_INTERVAL); // Ensure max is greater than min
} else if (min !== null && max !== null) {
const delta = max - min > MIN_INTERVAL * 10 ? (max - min) / 10 : MIN_INTERVAL;
min -= delta;
max += delta;
}
const tick = getTick(max - min, accuracy);
return { min, max, tick };
}
export function linearTickPositioner(this: Axis): number[] {
const axis = this as ExtendedAxis;
const accuracy = getAccuracyFromAxis(axis);
const { min, max, tick } = calculateMinMaxAndTicks(axis, accuracy);
if (min === null || max === null) return [];
const positions = [];
for (let pos = Math.ceil(min / tick) * tick; pos <= max; pos += tick) {
positions.push(pos);
}
return positions.map(value => getRoundingValue(value, accuracy));
}
export function limitYAxisPositioner(this: Axis): number[] {
const axis = this as ExtendedAxis;
const accuracy = getAccuracyFromAxis(axis);
const paramName = axis.series[0]?.userOptions.fullName || DEFAULT_SERIES;
if (!paramName || !limits.has(paramName)) return [];
const { lowerLimit, upperLimit } = limits.get(paramName) as AxisLimits;
const positions = [
lowerLimit?.selected ? getRoundingValue(lowerLimit.value, accuracy) : lowerLimit?.dataMin,
upperLimit?.selected ? getRoundingValue(upperLimit.value, accuracy) : upperLimit?.dataMax
].filter(value => value !== undefined && value !== null) as number[];
return positions;
}
export function logarithmicTickPositioner(this: Axis): number[] {
const axis = this as ExtendedAxis;
const accuracy = getAccuracyFromAxis(axis);
const { min, max } = calculateMinMaxAndTicks(axis, accuracy, true);
if (min === null || max === null) return [];
const logMin = Math.log10(min);
const logMax = Math.log10(max);
const logRange = logMax - logMin;
const positions = [];
for (let i = 0; i <= TICK_MAX_COUNT; i++) {
const pos = 10 ** (logMin + (logRange * i / TICK_MAX_COUNT));
positions.push(pos);
}
return positions.map(value => getRoundingValue(value, accuracy));
}
export function logarithmicLimitYAxisPositioner(this: Axis): number[] {
const axis = this as ExtendedAxis;
const accuracy = getAccuracyFromAxis(axis);
const paramName = axis.series[0]?.userOptions.fullName || DEFAULT_SERIES;
if (!paramName || !limits.has(paramName)) return [];
const { lowerLimit, upperLimit } = limits.get(paramName) as AxisLimits;
const positions = [
lowerLimit?.selected ? getRoundingValue(lowerLimit.value, accuracy) : (lowerLimit?.dataMin && Math.max(lowerLimit.dataMin, 1e-30)),
upperLimit?.selected ? getRoundingValue(upperLimit.value, accuracy) : upperLimit?.dataMax
].filter(value => value !== undefined && value !== null) as number[];
return positions;
}
logarithmicTickPositioner and logarithmicLimitYAxisPositioner functions to handle logarithmic scales.Check the enhancements and modify them as per your specific requirements or constraints.
Not yet included in a published release.