toPath
util
Converts value to a property path array.
Installation
Import
import { toPath } from '@tulx/utils';Source Code
Implementation
/**
* Converts value to a property path array.
*
* @param value - The value to convert.
* @returns Returns the new property path array.
*
* @example
* ```ts
* toPath('a.b.c'); // ['a', 'b', 'c']
* toPath('a[0].b.c'); // ['a', '0', 'b', 'c']
* ```
*/
export function toPath(
value: string | readonly (string | number)[]
): (string | number)[] {
if (Array.isArray(value)) {
return [...value];
}
const keys: (string | number)[] = [];
let current = '';
let inBrackets = false;
for (let i = 0; i < value.length; i++) {
const char = value[i];
if (char === '[') {
if (current) {
keys.push(current);
current = '';
}
inBrackets = true;
} else if (char === ']') {
if (current) {
keys.push(current);
current = '';
}
inBrackets = false;
} else if (char === '.' && !inBrackets) {
if (current) {
keys.push(current);
current = '';
}
} else {
current += char;
}
}
if (current) {
keys.push(current);
}
return keys;
}
Example
import { toPath } from '@tulx/utils';
toPath('a.b.c'); // ['a', 'b', 'c']
toPath('a[0].b.c'); // ['a', '0', 'b', 'c']Related Functions
attempt
Attempts to invoke func, returning either the result or the caught error object.
bindAll
Binds methods of an object to the object itself, overwriting the existing method.
cond
Creates a function that iterates over pairs and invokes the corresponding function of the first predicate to return truthy.
conforms
Creates a function that invokes the predicate properties of source with the corresponding property values of a given object.
constant
Creates a function that returns value.
defaultTo
Checks value to determine whether a default value should be returned in its place.