@storm-stack/utilities
Version:
This package includes various base utility class and various functions to assist in the development process.
35 lines (34 loc) • 1.09 kB
JavaScript
const DOTS_KEY = /^[\w.]+$/g;
const ESCAPE_REGEXP = /\\(?<temp1>\\)?/g;
const PROPERTY_REGEXP = new RegExp(
// Match anything that isn't a dot or bracket.
String.raw`[^.[\]]+` + "|" + // Or match property names within brackets.
String.raw`\[(?:` + // Match a non-string expression.
`([^"'][^[]*)|` + // Or match strings (supports escaping characters).
String.raw`(["'])((?:(?!\2)[^\\]|\\.)*?)\2` + String.raw`)\]` + "|" + // Or match "" as the space between consecutive dots or empty brackets.
String.raw`(?=(?:\.|\[\])(?:\.|\[\]|$))`,
"g"
);
export function toPath(deepKey) {
if (DOTS_KEY.test(deepKey)) {
return deepKey.split(".");
}
const result = [];
if (deepKey[0] === ".") {
result.push("");
}
const matches = deepKey.matchAll(PROPERTY_REGEXP);
for (const match of matches) {
let key = match[0];
const expr = match[1];
const quote = match[2];
const substr = match[3];
if (quote && substr) {
key = substr.replace(ESCAPE_REGEXP, "$1");
} else if (expr) {
key = expr;
}
result.push(key);
}
return result;
}