# Helpers (Chartist API)

> The data, math and utility functions the charts are built from, for plugins and custom layers.

## axisUnits

```ts
const axisUnits: { readonly x: { readonly pos: 'x'; readonly len: 'width'; readonly dir: 'horizontal'; readonly rectStart: 'x1'; readonly rectEnd: 'x2'; readonly rectOffset: 'y2' }; readonly y: { readonly pos: 'y'; readonly len: 'height'; readonly dir: 'vertical'; readonly rectStart: 'y2'; readonly rectEnd: 'y1'; readonly rectOffset: 'x1' } }
```

The names an axis uses per dimension: its position, length and direction, and its edges in the [`ChartRect`](https://chartist.dev/api/helpers/#ChartRect).

## namespaces

```ts
const namespaces: Record<string, string>
```

This object contains all namespaces used within Chartist.

## precision

```ts
const precision: 8
```

Precision level used internally in Chartist for rounding. If you require more decimal places you can increase this number.

## escapingMap

```ts
const escapingMap: Record<string, string>
```

A map with characters to escape for strings to be safely used as attribute values.

## normalizePadding

```ts
function normalizePadding(padding: number | Partial<ChartPadding> | undefined): { top: number; right: number; bottom: number; left: number }
```

Turns a padding option into a full [`ChartPadding`](https://chartist.dev/api/classes/#ChartPadding): a number pads every side, an object keeps its numeric sides and sets the missing ones to 0, and `undefined` gives 0 on every side.

## createChartRect

```ts
function createChartRect(svg: Svg, options: Options): { x1: number; x2: number; y1: number; y2: number; padding: { top: number; right: number; bottom: number; left: number }; width: () => number; height: () => number }
```

Initialize chart drawing rectangle (area where chart is drawn) x1,y1 = bottom left / x2,y2 = top right

## getBounds

```ts
function getBounds(axisLength: number, highLow: { high: number; low: number }, scaleMinSpace: number, onlyInteger?: boolean): Bounds
```

Calculate and retrieve all the bounds for the chart and return them in one array

## getMetaData

```ts
function getMetaData(seriesData: FlatSeriesValue | Series | SeriesObject<SeriesPrimitiveValue>, index: number): any
```

Get meta data of a specific value in a series.

## isDataHoleValue

```ts
function isDataHoleValue(value: unknown): value is null | undefined
```

Checks if a value is considered a hole in the data series.

## isArrayOfSeries

```ts
function isArrayOfSeries(value: unknown): value is (Series | SeriesObject<SeriesPrimitiveValue>)[]
```

Checks if value is array of series objects.

## isMultiValue

```ts
function isMultiValue(value: unknown): value is Multi
```

Checks if provided value object is multi value (contains x or y properties)

## getMultiValue

```ts
function getMultiValue(value: unknown, dimension?: AxisName): number | undefined
```

Gets a value from a dimension `value.x` or `value.y` while returning value directly if it's a valid numeric value. If the value is not numeric and it's falsey this function will return `defaultValue`.

## getHighLow

```ts
function getHighLow(data: NormalizedSeries[], options: Options, dimension?: AxisName, extent?: { readonly low: number; readonly high: number }): { high: number; low: number }
```

Get highest and lowest value of data array. This Array contains the data that will be visualized in the chart.

## normalizeData

```ts
function normalizeData(data: Data<FlatSeries>, reverse?: boolean, multi?: false): NormalizedData<NormalizedFlatSeries>
function normalizeData(data: Data<(Series | SeriesObject<SeriesPrimitiveValue>)[]>, reverse: boolean | undefined, multi: true | AxisName): NormalizedData<NormalizedSeries[]>
function normalizeData(data: Data<(Series | SeriesObject<SeriesPrimitiveValue>)[] | FlatSeries>, reverse: boolean | undefined, multi: boolean | AxisName, distributed: true): NormalizedData<NormalizedSeries[]>
function normalizeData(data: Data<(Series | SeriesObject<SeriesPrimitiveValue>)[] | FlatSeries>, reverse?: boolean, multi?: boolean | AxisName): NormalizedData<NormalizedSeries[] | NormalizedFlatSeries>
```

Ensures that the data object passed as second argument to the charts is present and correctly initialized.

## splitIntoSegments

```ts
function splitIntoSegments(pathCoordinates: number[], valueData: SegmentData[], options?: { increasingX?: boolean; fillHoles?: boolean }): Segment[]
```

Splits a list of coordinates and associated values into segments. Each returned segment contains a pathCoordinates valueData property describing the segment.

With the default options, segments consist of contiguous sets of points that do not have an undefined value. Any points with undefined values are discarded.

**Options** The following options are used to determine how segments are formed ```javascript
var options = {
  // If fillHoles is true, undefined values are simply discarded without creating a new segment. Assuming other options are default, this returns single segment.
  fillHoles: false,
  // If increasingX is true, the coordinates in all segments have strictly increasing x-values.
  increasingX: false
};
```

## serialize

```ts
function serialize(data: string | number | object): string
function serialize(data: unknown): string | null | undefined
```

This function serializes arbitrary data to a string. In case of data that can't be easily converted to a string, this function will create a wrapper object and serialize the data using JSON.stringify. The outcoming string will always be escaped using Chartist.escapingMap. If called with null or undefined the function will return immediately with null or undefined.

## deserialize

```ts
function deserialize<T extends string | number | object = object>(data: string): T
function deserialize<T extends string | number | object = object>(data: string | null | undefined): T | null | undefined
```

This function de-serializes a string previously serialized with Chartist.serialize. The string will always be unescaped using Chartist.escapingMap before it's returned. Based on the input value the return type can be Number, String or Object. JSON.parse is used with try / catch to see if the unescaped string can be parsed into an Object and this Object will be returned on success.

## ensureUnit

```ts
function ensureUnit<T>(value: T, unit: string): string | T
```

Converts a number to a string with a unit. If a string is passed then this will be returned unmodified.

## quantity

```ts
function quantity<T>(input: T): { value: number; unit: string | undefined } | { unit?: undefined; value: number }
```

Converts a number or string to a quantity object.

## alphaNumerate

```ts
function alphaNumerate(n: number): string
```

Generates a-z from a number 0 to 26

## EPSILON

```ts
const EPSILON: 2.221e-16
```

A tiny number, about the gap between 1 and the next float: the tolerance of float comparisons.

## orderOfMagnitude

```ts
function orderOfMagnitude(value: number): number
```

Calculate the order of magnitude for the chart scale

## projectLength

```ts
function projectLength(axisLength: number, length: number, bounds: Bounds): number
```

Project a data length into screen coordinates (pixels)

## roundWithPrecision

```ts
function roundWithPrecision(value: number, digits?: number): number
```

Rounds a value to a number of digits after the decimal point, to remove float errors such as `0.30000000000000004`. `0` digits round to whole numbers.

## rho

```ts
function rho(num: number): number
```

Pollard Rho Algorithm to find smallest factor of an integer value. There are more efficient algorithms for factorization, but this one is quite efficient and not so complex.

## polarToCartesian

```ts
function polarToCartesian(centerX: number, centerY: number, radius: number, angleInDegrees: number): { x: number; y: number }
```

Calculate cartesian coordinates of polar coordinates

## extend

```ts
function extend<T>(target: T): T
function extend<T, A>(target: T, a: A): T & A
function extend<T, A, B>(target: T, a: A, b: B): T & A & B
```

Merges the sources into `target`, deeply, and returns `target`. Plain objects merge key by key into an object already there, and replace any other value (an object over a number gives a copy of the object); arrays, from any realm, and other values replace what's there. Keys of the target's prototype are skipped, against prototype pollution.

## noop

```ts
function noop<T>(n: T): T
```

Helps to simplify functional style code

## times

```ts
function times(length: number): undefined[]
function times<T = unknown>(length: number, filler: (index: number) => T): T[]
```

Functional style helper to produce array with given length initialized with undefined values

## sum

```ts
function sum(previous: number, current: number): number
```

Sum helper to be used in reduce functions

## serialMap

```ts
function serialMap<T, K>(array: T[][], callback: (...args: T[]) => K): K[]
```

Map for multi dimensional arrays where their nested arrays will be mapped in serial. The output array will have the length of the largest nested array. The callback function is called with variable arguments where each argument is the nested array value (or undefined if there are no more values).

For example:

## safeHasProperty

```ts
function safeHasProperty<T, K extends string>(target: T, property: K): target is FilterByKey<T, K>
```

This function safely checks if an objects has an owned property.

## isNumeric

```ts
function isNumeric(value: number): true
function isNumeric(value: unknown): boolean
```

Checks if a value can be safely coerced to a number. This includes all values except null which result in finite numbers when coerced. This excludes NaN, since it's not finite.

## isFalseyButZero

```ts
function isFalseyButZero(value: unknown): value is false | '' | null | undefined
```

Returns true on all falsey values except the numeric value 0.

## getNumberOrUndefined

```ts
function getNumberOrUndefined(value: number): number
function getNumberOrUndefined(value: unknown): number | undefined
```

Returns a number if the passed parameter is a valid number or the function will return undefined. On all other values than a valid number, this function will return undefined.

## isArrayOfArrays

```ts
function isArrayOfArrays(data: unknown): data is unknown[][]
```

Checks if value is array of arrays or not.

## each

```ts
function each<T>(list: T[], callback: (item: T, index: number, itemIndex: number) => void, reverse?: boolean): void
```

Loop over array.

## XAxisUnits

```ts
type XAxisUnits = typeof axisUnits.x
```

The units of the X axis: `axisUnits.x`.

## YAxisUnits

```ts
type YAxisUnits = typeof axisUnits.y
```

The units of the Y axis: `axisUnits.y`.

## AxisUnits

```ts
type AxisUnits = XAxisUnits | YAxisUnits
```

The units of either axis.

## ChartRect

```ts
interface ChartRect
```

The drawing area of a 1.x chart in px: `x1`, `y1` is its bottom left corner and `x2`, `y2` its top right (SVG y grows downward, so `y1` is the larger one).

## ViewBox

```ts
interface ViewBox
```

The size of an SVG `viewBox`.

## Bounds

```ts
interface Bounds
```

The scale [`getBounds`](https://chartist.dev/api/helpers/#getBounds) computes for an axis: its range and steps.

## Segment

```ts
interface Segment
```

A run of points without holes, as [`splitIntoSegments`](https://chartist.dev/api/helpers/#splitIntoSegments) returns it.

## SegmentData

```ts
interface SegmentData
```

A point's value, its index in the series and its meta.

## AxisName

```ts
type AxisName = 'x' | 'y'
```

An axis dimension: `'x'` or `'y'`.

## FilterByKey

```ts
type FilterByKey<T, K extends string> = T extends Record<K, unknown> ? T : T extends Partial<Record<K, unknown>> ? T & { [key in K]: T[K] } : never
```

Narrows a union `T` to the members that have the key `K` (an optional `K` becomes required).

## RequiredKeys

```ts
type RequiredKeys<T, K extends keyof T, V extends keyof T = never> = T & Required<Pick<T, K | V>> & { [key in V]: Required<T[V]> }
```

`T` with the keys `K` required, and the keys `V` required down one level.
