@cookbook/dot-notation
Version:
Object readings and complex transformations using dot notation syntax.
31 lines • 1.19 kB
JavaScript
import getArrayIndex from './utils/get-array-index';
import getKey from './utils/get-key';
import is from './utils/is';
import shallowCopy from './utils/shallow-copy';
const pick = (source, path) => {
if (is.nullish(path) || !path.toString().trim()) {
throw new SyntaxError(`A dot notation path was expected, but instead got "${path}"`);
}
const content = shallowCopy(source);
let [key, remainingPath] = getKey(path);
const hasArrayNotation = getArrayIndex(key.toString());
if (hasArrayNotation) {
const { 1: idx } = hasArrayNotation;
if (!idx) {
throw new SyntaxError(`An array index was expected but nothing was found at "${path}"`);
}
if (Number.isNaN(+idx)) {
throw new TypeError(`Array index must a positive integer "${idx}"`);
}
if (+idx < 0) {
throw new RangeError(`Array index must be equal or greater than 0, but instead got "${idx}"`);
}
key = +idx;
}
if (!remainingPath || is.nullish(content[key])) {
return content[key];
}
return pick(content[key], remainingPath);
};
export default pick;
//# sourceMappingURL=pick.js.map