Tiny utility library for object property path handling
npm install pxth
Or
yarn add pxth
Here are all functions described.
Convert string / number / symbol to Pxth.
Usage:
import { toPxth, ROOT_PATH } from 'pxth';
toPxth('a.b.c'); // -> ['a', 'b', 'c']
// any symbol
toPxth(Symbol()); // -> [Symbol()]
// ROOT_PATH symbol
toPxth(ROOT_PATH); // -> []
toPxth(0); // -> [0]
Convert Pxth to string. Throws error if pxth cannot be stringified. Here is function for check
Usage:
import { pxthToString } from 'pxth';
pxthToString(['lol', 'b', 0, ' .as0 ']); // -> lol.b.0.[" .as0 "]
pxthToString([Symbol(), 'asdf']); // -> throws error
Convert string to pxth. Function toPxth calls it, if first argument is string.
import { stringToPxth } from 'pxth';
stringToPxth('hello.a.b'); // -> ['hello', 'a', 'b']
Deeply get value from object.
Usage:
import { get } from 'pxth';
get({ a: { b: { c: 'Hello world!' } } }, toPxth('a.b.c')); // -> 'Hello world'
// third argument is default value
get({ a: 'hello' }, toPxth('b.c.d'), 'Default value'); // -> 'Default value'
Deeply set value in object. Mutates the object and returns it. If value already exists, overwrites it.
Usage:
import { set } from 'pxth';
set({ a: { hello: 'asdf' } }, toPxth('a.hello'), 'New value'); // -> { a: { hello: 'New value' } }
set({ a: 'hello' }, toPxth('a.b'), 'New value'); // -> { a: { b: 'New value' } }
Determines if one path is child path of another.
Usage:
import { isNestedPath } from 'pxth';
isNestedPath(['hello', 'bye', 'yes'], ['hello']); // -> true
isNestedPath(['hello', 'bye', 'yes'], ['hello', 'bye', 'no']); // -> false
Returns longest common path in array
Usage:
import { longestCommonPath } from 'pxth';
longestCommonPath([
['hello', 'a'],
['hello', 'b'],
['hello', 'c'],
]); // -> ['hello']
longestCommonPath([['a'], ['b'], ['c']]); // -> []
Function, detecting if Pxth
instance could be stringified or not.
Usage:
import { canBeStringified } from 'pxth';
canBeStringified(['hello', 'world']); // -> true
canBeStringified([Symbol(), 'asdf']); // -> false
Make one path relative to another
Usage:
import { relativePath } from 'pxth';
relativePath(['hello', 'world'], ['hello', 'world', 'asdf']); // -> ['asdf']
relativePath(['a', 'b', 'c'], ['a', 'b', 'c', 'd', 'e']); // -> ['d', 'e']
relativePath(['a'], ['b']); // -> Error
Convert pxth to object key
Usage:
import { toObjectKey } from 'pxth';
toObjectKey(['a', 'b', 'c']); // -> 'a.b.c'
toObjectKey([]); // -> ROOT_PATH
Constant, used in toObjectKey function, to convert empty Pxth to object key.
import { ROOT_PATH } from 'pxth';
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.
MIT © Artiom Tretjakovas