Skip to content

Latest commit

 

History

History
2061 lines (1301 loc) · 57.9 KB

File metadata and controls

2061 lines (1301 loc) · 57.9 KB

Pathist v1.3.0


Pathist / Pathist

Class: Pathist

Defined in: pathist.ts:85

A path utility class for parsing, manipulating, and comparing object property paths.

Pathist provides a comprehensive API for working with property paths in JavaScript objects. It supports multiple notation styles (dot, bracket, and mixed), handles numeric indices, and offers powerful comparison and manipulation methods.

Quick Reference

Methods

Method Description
from() Creates a new Pathist instance from various input types
fromJSONPointer() Creates a new Pathist instance from a JSON Pointer string (RFC 6901)
toArray() Returns the path as an array of segments
toString() Converts the path to a string representation using the specified notation
toJSONPath() Converts the path to JSONPath format (RFC 9535)
toJSONPointer() Converts the path to JSON Pointer format (RFC 6901)
[[iterator]()](#iterator) Makes the Pathist instance iterable, allowing use in for...of loops and spread operators
reduce() Convenience wrapper for Array.reduce() on the path segments
equals() Checks if this path is equal to another path
startsWith() Checks if this path starts with the specified path segment sequence
endsWith() Checks if this path ends with the specified path segment sequence
includes() Checks if this path contains the specified path segment sequence anywhere within it
relativeTo() Extracts the relative path from a base path
commonStart() Finds the common prefix path shared between this path and another path
commonEnd() Finds the common suffix path shared between this path and another path
positionOf() Finds the first position where the specified path segment sequence occurs within this path
lastPositionOf() Finds the last position where the specified path segment sequence occurs within this path
pathTo() Returns the path up to and including the first occurrence of the specified path segment sequence
pathToLast() Returns the path up to and including the last occurrence of the specified path segment sequence
match() Returns the first matched subsequence anywhere in this path
matchStart() Returns the matched prefix if this path starts with the pattern
matchEnd() Returns the matched suffix if this path ends with the pattern
slice() Returns a new path containing a subset of this path's segments
parentPath() Returns the parent path by removing segments from the end
concat() Returns a new path that combines this path with one or more other paths
merge() Intelligently merges another path with this path by detecting overlapping segments
firstNodePath() Returns the path to the first node
lastNodePath() Returns the full path to the last node in the contiguous tree structure
afterNodePath() Returns the path segments after the last node in the tree
parentNode() Returns the parent node in the tree structure by removing nodes from the end
nodeIndices() Returns the numeric index values from the contiguous tree structure
nodePaths() Generates paths to each successive node in the tree structure

Accessors

Accessor Description
defaultNotation Gets or sets the default notation style used when converting paths to strings
defaultIndices Gets or sets the default indices comparison mode
indexWildcards Gets or sets the values that are treated as index wildcards
defaultNodeChildrenProperties No description
notation Gets the notation style for this instance
indices Gets the indices comparison mode for this instance
nodeChildrenProperties Gets the node children properties for this instance
array Gets the path as an array of segments
string Gets the path as a string using the instance's default notation
jsonPath Gets the path as a JSONPath string
jsonPointer Gets the path as a JSON Pointer string

Examples

Basic usage

const path = Pathist.from('foo.bar.baz');
console.log(path.length); // 3
console.log(path.toArray()); // ['foo', 'bar', 'baz']

Path comparison

const path1 = Pathist.from('foo.bar');
const path2 = Pathist.from('foo.bar.baz');
console.log(path2.startsWith(path1)); // true

Constructors

Constructor

new Pathist(input, config?): Pathist

Defined in: pathist.ts:810

Creates a new Pathist instance from a string, array, or existing Pathist.

Parameters

Parameter Type Description
input PathistInput The path input (string like "foo.bar", array like ['foo', 'bar'], or Pathist instance)
config? PathistConfig Optional configuration for notation, indices mode, and node children properties

Returns

Pathist

Throws

If the string path contains syntax errors (unclosed brackets, mismatched quotes, etc.)

Throws

If array segments contain invalid types (must be string or number)

Examples

From string

const path = Pathist.from('foo.bar.baz');

From array

const path = Pathist.from(['foo', 'bar', 0, 'baz']);

With custom configuration

const path = Pathist.from('foo.bar', {
  notation: Pathist.Notation.Bracket,
  indices: Pathist.Indices.Ignore
});

Properties

Property Modifier Type Description Defined in
Notation readonly object Notation styles for converting paths to strings. - Mixed: Combines dot notation for properties and bracket notation for indices (e.g., foo.bar[0].baz) - Dot: Uses dot notation exclusively (e.g., foo.bar.0.baz) - Bracket: Uses bracket notation exclusively (e.g., ["foo"]["bar"][0]["baz"]) pathist.ts:97
Notation.Mixed readonly "Mixed" - pathist.ts:98
Notation.Dot readonly "Dot" - pathist.ts:99
Notation.Bracket readonly "Bracket" - pathist.ts:100
Indices readonly object Modes for handling numeric indices during path comparisons. - Preserve: Numeric indices must match exactly for paths to be considered equal - Ignore: Any numeric index matches any other numeric index (useful for comparing paths across different array positions) pathist.ts:109
Indices.Preserve readonly "Preserve" - pathist.ts:110
Indices.Ignore readonly "Ignore" - pathist.ts:111
length readonly number The number of segments in this path. Example const path = Pathist.from('foo.bar.baz'); console.log(path.length); // 3 pathist.ts:724
hasIndexWildcards readonly boolean Indicates whether this path contains any wildcard index tokens. A path has index wildcards if any of its segments match the configured wildcard values (by default * and -1). Example const path1 = Pathist.from('foo[*].bar'); console.log(path1.hasIndexWildcards); // true const path2 = Pathist.from('foo[-1].bar'); console.log(path2.hasIndexWildcards); // true const path3 = Pathist.from('foo[0].bar'); console.log(path3.hasIndexWildcards); // false const path4 = Pathist.from('foo.bar.baz'); console.log(path4.hasIndexWildcards); // false pathist.ts:747

Accessors

defaultNotation

Get Signature

get static defaultNotation(): Notation

Defined in: pathist.ts:132

Gets or sets the default notation style used when converting paths to strings.

When setting, the notation is validated and applied to all new Pathist instances.

Throws

When setting: If the notation value is invalid

Default Value

Pathist.Notation.Mixed

Returns

Notation

Set Signature

set static defaultNotation(notation): void

Defined in: pathist.ts:136

Parameters
Parameter Type
notation Notation
Returns

void


defaultIndices

Get Signature

get static defaultIndices(): Indices

Defined in: pathist.ts:150

Gets or sets the default indices comparison mode.

When setting, the mode is validated and applied to all new Pathist instances.

Throws

When setting: If the indices mode is invalid

Default Value

Pathist.Indices.Preserve

Returns

Indices

Set Signature

set static defaultIndices(mode): void

Defined in: pathist.ts:154

Parameters
Parameter Type
mode Indices
Returns

void


indexWildcards

Get Signature

get static indexWildcards(): ReadonlySet<string | number>

Defined in: pathist.ts:172

Gets or sets the values that are treated as index wildcards.

Wildcard values match any numeric index during comparisons.

When setting, wildcard values can be:

  • Negative numbers or non-finite numbers (Infinity, -Infinity, NaN)
  • Strings that don't match the pattern /^[0-9]+$/
Throws

When setting: If any wildcard value is invalid (e.g., positive finite number or numeric string)

Default Value

Set([-1, '*'])

Returns

ReadonlySet<string | number>

Set Signature

set static indexWildcards(value): void

Defined in: pathist.ts:176

Parameters
Parameter Type
value string
Returns

void


defaultNodeChildrenProperties

Get Signature

get static defaultNodeChildrenProperties(): ReadonlySet<string>

Defined in: pathist.ts:211

Returns

ReadonlySet<string>

Set Signature

set static defaultNodeChildrenProperties(value): void

Defined in: pathist.ts:223

Gets or sets the default property names that contain child nodes in tree structures. These properties are used by node-related methods to identify and traverse tree relationships.

Throws
  • When setting: If the value is not a Set, Array, or string, or if any value is not a string
Default Value

Set(['children'])

Parameters
Parameter Type Description
value string ReadonlySet<string>
Returns

void


notation

Get Signature

get notation(): Notation

Defined in: pathist.ts:754

Gets the notation style for this instance.

Returns the instance-specific notation if set, otherwise returns the global default.

Returns

Notation


indices

Get Signature

get indices(): Indices

Defined in: pathist.ts:763

Gets the indices comparison mode for this instance.

Returns the instance-specific mode if set, otherwise returns the global default.

Returns

Indices


nodeChildrenProperties

Get Signature

get nodeChildrenProperties(): ReadonlySet<string>

Defined in: pathist.ts:772

Gets the node children properties for this instance.

Returns the instance-specific properties if set, otherwise returns the global default.

Returns

ReadonlySet<string>


array

Get Signature

get array(): PathSegment[]

Defined in: pathist.ts:869

Gets the path as an array of segments.

See

toArray - Method form of this getter

Returns

PathSegment[]


string

Get Signature

get string(): string

Defined in: pathist.ts:943

Gets the path as a string using the instance's default notation.

See

toString - Method form of this getter

Returns

string


jsonPath

Get Signature

get jsonPath(): string

Defined in: pathist.ts:1026

Gets the path as a JSONPath string.

See

toJSONPath - Method form of this getter

Returns

string


jsonPointer

Get Signature

get jsonPointer(): string

Defined in: pathist.ts:1106

Gets the path as a JSON Pointer string.

See

toJSONPointer - Method form of this getter

Returns

string

Methods

from()

static from(input, config?): Pathist

Defined in: pathist.ts:313

Creates a new Pathist instance from various input types. This is the Temporal-style factory method alternative to using Pathist.from().

Parameters

Parameter Type Description
input PathistInput Path string, array of segments, or existing Pathist instance
config? PathistConfig Optional configuration for notation, indices mode, etc.

Returns

Pathist

A new Pathist instance

Example

Pathist.from('foo.bar.baz')
Pathist.from(['foo', 'bar', 'baz'])
Pathist.from('foo.bar', { notation: 'bracket' })

fromJSONPointer()

static fromJSONPointer(pointer, config?): Pathist

Defined in: pathist.ts:360

Creates a new Pathist instance from a JSON Pointer string (RFC 6901).

Parses a JSON Pointer formatted string and converts it to a Pathist instance. JSON Pointer uses / as segment separators and requires unescaping of special characters (~1 becomes /, ~0 becomes ~).

Parameters

Parameter Type Description
pointer string A JSON Pointer string (e.g., '/foo/bar/0')
config? PathistConfig Optional configuration for notation, indices mode, etc.

Returns

Pathist

A new Pathist instance

Throws

If the pointer contains invalid escape sequences

See

  • toJSONPointer - Convert path to JSON Pointer format
  • from - General factory method for creating paths

Examples

Basic usage

const path = Pathist.fromJSONPointer('/foo/bar/baz');
console.log(path.toArray()); // ['foo', 'bar', 'baz']

With numeric indices

const path = Pathist.fromJSONPointer('/items/0/name');
console.log(path.toString()); // 'items[0].name'

With escaped special characters

const path = Pathist.fromJSONPointer('/foo~0bar/baz~1qux');
console.log(path.toArray()); // ['foo~bar', 'baz/qux']

Root reference (empty string)

const path = Pathist.fromJSONPointer('');
console.log(path.length); // 0

toArray()

toArray(): PathSegment[]

Defined in: pathist.ts:859

Returns the path as an array of segments.

Returns a copy of the internal segments array to maintain immutability.

Returns

PathSegment[]

A new array containing all path segments

See

  • array - Getter alias for this method
  • toString - Convert to string representation

Example

const path = Pathist.from('foo.bar[0].baz');
console.log(path.toArray()); // ['foo', 'bar', 0, 'baz']

toString()

toString(notation?): string

Defined in: pathist.ts:906

Converts the path to a string representation using the specified notation.

Results are cached for performance. The notation parameter allows overriding the instance's default notation on a per-call basis.

Parameters

Parameter Type Description
notation? Notation Optional notation style to use (overrides instance default)

Returns

string

The path as a string

Throws

If the notation value is invalid

See

  • string - Getter alias for this method (uses instance default notation)
  • toArray - Convert to array representation
  • toJSONPath - Convert to JSONPath format

Examples

Default notation (Mixed)

const path = Pathist.from(['foo', 'bar', 0, 'baz']);
console.log(path.toString()); // 'foo.bar[0].baz'

Bracket notation

console.log(path.toString(Pathist.Notation.Bracket)); // '["foo"]["bar"][0]["baz"]'

Dot notation

console.log(path.toString(Pathist.Notation.Dot)); // 'foo.bar.0.baz'

toJSONPath()

toJSONPath(): string

Defined in: pathist.ts:980

Converts the path to JSONPath format (RFC 9535).

JSONPath is a standardized query language for JSON. This method converts the path to a JSONPath selector string starting with $ (the root).

Returns

string

The path as a JSONPath string

See

  • jsonPath - Getter alias for this method
  • toString - Convert to standard notation
  • toArray - Convert to array representation

Examples

Basic usage

const path = Pathist.from('foo.bar.baz');
console.log(path.toJSONPath()); // '$.foo.bar.baz'

With numeric indices

const path = Pathist.from('items[0].name');
console.log(path.toJSONPath()); // '$.items[0].name'

With wildcards

const path = Pathist.from('items[*].name');
console.log(path.toJSONPath()); // '$.items[*].name'

toJSONPointer()

toJSONPointer(): string

Defined in: pathist.ts:1072

Converts the path to JSON Pointer format (RFC 6901).

JSON Pointer is a standardized string format for identifying a specific value within a JSON document. Each segment is separated by /, and special characters are escaped (~ becomes ~0, / becomes ~1).

Returns

string

The path as a JSON Pointer string

See

Examples

Basic usage

const path = Pathist.from('foo.bar.baz');
console.log(path.toJSONPointer()); // '/foo/bar/baz'

With numeric indices

const path = Pathist.from('items[0].name');
console.log(path.toJSONPointer()); // '/items/0/name'

With special characters requiring escaping

const path = Pathist.from(['foo~bar', 'baz/qux']);
console.log(path.toJSONPointer()); // '/foo~0bar/baz~1qux'

Empty path (root)

const path = Pathist.from('');
console.log(path.toJSONPointer()); // ''

[iterator]()

[iterator](): Iterator<PathSegment>

Defined in: pathist.ts:1137

Makes the Pathist instance iterable, allowing use in for...of loops and spread operators.

Returns

Iterator<PathSegment>

An iterator over the path segments

See

  • toArray - Get all segments as an array
  • nodePaths - Iterate over tree node paths

Examples

Using for...of

const path = Pathist.from('foo.bar.baz');
for (const segment of path) {
  console.log(segment); // 'foo', 'bar', 'baz'
}

Using spread operator

const segments = [...path]; // ['foo', 'bar', 'baz']

reduce()

reduce<T>(callbackfn, initialValue): T

Defined in: pathist.ts:1186

Convenience wrapper for Array.reduce() on the path segments.

This is equivalent to path.toArray().reduce(...) but more concise. Allows you to define custom reduction logic for navigating objects.

Type Parameters

Type Parameter
T

Parameters

Parameter Type Description
callbackfn (previousValue, currentValue, currentIndex, array) => T Function to execute on each segment
initialValue T Value to use as the first argument to the first call of the callback

Returns

T

The accumulated result from the reduction

See

  • toArray - Get the path segments as an array
  • array - Getter for path segments
  • Symbol.iterator - Iterate over segments

Examples

Navigate through an object

const data = {
  users: [
    { profile: { name: 'Alice' } },
    { profile: { name: 'Bob' } }
  ]
};

const path = Pathist.from('users[0].profile.name');
const value = path.reduce((obj, segment) => obj?.[segment], data);
console.log(value); // 'Alice'

Custom reduction with default fallback

const path = Pathist.from('users[5].profile.name');
const value = path.reduce((obj, seg) => obj?.[seg] ?? {}, data);
console.log(value); // {} (instead of undefined)

Building a path string during reduction

const path = Pathist.from('foo.bar.baz');
const result = path.reduce((acc, seg) => acc + '/' + seg, '');
console.log(result); // '/foo/bar/baz'

equals()

equals(other, options?): boolean

Defined in: pathist.ts:1232

Checks if this path is equal to another path.

Two paths are equal if they have the same length and all corresponding segments match. The indices option controls how numeric indices are compared.

Parameters

Parameter Type Description
other PathistInput Pathist
options? ComparisonOptions Optional comparison options

Returns

boolean

true if the paths are equal, false otherwise

See

  • startsWith for checking if this path starts with another
  • endsWith for checking if this path ends with another
  • includes for checking if this path contains another

Examples

Exact comparison (default)

const path1 = Pathist.from('foo[0].bar');
const path2 = Pathist.from('foo[0].bar');
console.log(path1.equals(path2)); // true

Ignoring indices

const path1 = Pathist.from('foo[0].bar');
const path2 = Pathist.from('foo[5].bar');
console.log(path1.equals(path2, { indices: Pathist.Indices.Ignore })); // true

startsWith()

startsWith(other, options?): boolean

Defined in: pathist.ts:1274

Checks if this path starts with the specified path segment sequence.

Parameters

Parameter Type Description
other PathistInput Pathist
options? ComparisonOptions Optional comparison options

Returns

boolean

true if this path starts with the specified sequence, false otherwise

See

  • endsWith for checking if this path ends with a sequence
  • equals for exact path comparison
  • positionOf for finding the position of a sequence

Example

const path = Pathist.from('foo.bar.baz');
console.log(path.startsWith('foo.bar')); // true
console.log(path.startsWith('bar')); // false

endsWith()

endsWith(other, options?): boolean

Defined in: pathist.ts:1296

Checks if this path ends with the specified path segment sequence.

Parameters

Parameter Type Description
other PathistInput Pathist
options? ComparisonOptions Optional comparison options

Returns

boolean

true if this path ends with the specified sequence, false otherwise

See

  • startsWith for checking if this path starts with a sequence
  • equals for exact path comparison
  • lastPositionOf for finding the last position of a sequence

Example

const path = Pathist.from('foo.bar.baz');
console.log(path.endsWith('bar.baz')); // true
console.log(path.endsWith('bar')); // false

includes()

includes(other, options?): boolean

Defined in: pathist.ts:1328

Checks if this path contains the specified path segment sequence anywhere within it.

Parameters

Parameter Type Description
other PathistInput Pathist
options? ComparisonOptions Optional comparison options

Returns

boolean

true if this path contains the specified sequence, false otherwise

See

  • positionOf for finding the exact position of the sequence
  • startsWith for checking if the sequence is at the start
  • endsWith for checking if the sequence is at the end

Example

const path = Pathist.from('foo.bar.baz.qux');
console.log(path.includes('bar.baz')); // true
console.log(path.includes('baz.foo')); // false

relativeTo()

relativeTo(base, options?): Pathist | null

Defined in: pathist.ts:1376

Extracts the relative path from a base path.

Returns a new path representing the segments that would need to be concatenated to the base to produce this path. Returns null if this path doesn't start with the base path.

Parameters

Parameter Type Description
base PathistInput Pathist
options? ComparisonOptions Optional comparison options

Returns

Pathist | null

The relative path, or null if this path doesn't start with the base

See

  • concat for combining paths (the inverse operation)
  • startsWith for checking if this path starts with a base
  • commonStart for finding the common prefix between paths

Examples

Extract relative path

const fullPath = Pathist.from('api.users[0].profile.settings');
const basePath = Pathist.from('api.users[0]');
const relative = fullPath.relativeTo(basePath);
console.log(relative?.string); // 'profile.settings'

Inverse of concat

const base = Pathist.from('api.users[0]');
const relative = Pathist.from('profile.settings');
const full = base.concat(relative);
console.log(full.relativeTo(base)?.equals(relative)); // true

Returns null when not relative

const path = Pathist.from('posts.comments');
const base = Pathist.from('users.profile');
console.log(path.relativeTo(base)); // null

commonStart()

commonStart(other, options?): Pathist

Defined in: pathist.ts:1446

Finds the common prefix path shared between this path and another path.

Returns a new path containing the longest sequence of segments that both paths start with. Returns an empty path if there is no common prefix.

Parameters

Parameter Type Description
other PathistInput Pathist
options? ComparisonOptions Optional comparison options

Returns

Pathist

The common prefix path (may be empty if no common prefix exists)

See

  • commonEnd for finding the common suffix
  • startsWith for checking if this path starts with another
  • relativeTo for extracting the relative path after a common base

Examples

Find common prefix

const path1 = Pathist.from('users[0].profile.settings.theme');
const path2 = Pathist.from('users[0].profile.avatar.url');
const common = path1.commonStart(path2);
console.log(common.string); // 'users[0].profile'

No common prefix

const path1 = Pathist.from('users.name');
const path2 = Pathist.from('posts.title');
const common = path1.commonStart(path2);
console.log(common.length); // 0 (empty path)

Use with relativeTo to decompose paths

const path1 = Pathist.from('api.users[0].profile.settings');
const path2 = Pathist.from('api.users[0].posts.recent');
const common = path1.commonStart(path2);  // 'api.users[0]'
const rel1 = path1.relativeTo(common);     // 'profile.settings'
const rel2 = path2.relativeTo(common);     // 'posts.recent'

commonEnd()

commonEnd(other, options?): Pathist

Defined in: pathist.ts:1512

Finds the common suffix path shared between this path and another path.

Returns a new path containing the longest sequence of segments that both paths end with. Returns an empty path if there is no common suffix.

Parameters

Parameter Type Description
other PathistInput Pathist
options? ComparisonOptions Optional comparison options

Returns

Pathist

The common suffix path (may be empty if no common suffix exists)

See

  • commonStart for finding the common prefix
  • endsWith for checking if this path ends with another

Examples

Find common suffix

const path1 = Pathist.from('users[0].profile.settings');
const path2 = Pathist.from('config.default.settings');
const common = path1.commonEnd(path2);
console.log(common.string); // 'settings'

No common suffix

const path1 = Pathist.from('users.name');
const path2 = Pathist.from('posts.title');
const common = path1.commonEnd(path2);
console.log(common.length); // 0 (empty path)

Extract unique prefixes

const path1 = Pathist.from('api.users.profile.settings');
const path2 = Pathist.from('config.profile.settings');
const suffix = path1.commonEnd(path2);  // 'profile.settings'
const prefix1 = path1.slice(0, path1.length - suffix.length); // 'api.users'
const prefix2 = path2.slice(0, path2.length - suffix.length); // 'config'

positionOf()

positionOf(other, options?): number

Defined in: pathist.ts:1567

Finds the first position where the specified path segment sequence occurs within this path.

Returns the index of the first segment where the match begins, or -1 if not found.

Parameters

Parameter Type Description
other PathistInput Pathist
options? ComparisonOptions Optional comparison options

Returns

number

The zero-based position of the first match, or -1 if not found

See

  • lastPositionOf for finding the last occurrence
  • includes for checking if a sequence exists without needing the position
  • pathTo for extracting the path up to the first occurrence

Example

const path = Pathist.from('foo.bar.baz.bar');
console.log(path.positionOf('bar')); // 1 (first occurrence)
console.log(path.positionOf('qux')); // -1 (not found)

lastPositionOf()

lastPositionOf(other, options?): number

Defined in: pathist.ts:1623

Finds the last position where the specified path segment sequence occurs within this path.

Returns the index of the first segment where the last match begins, or -1 if not found.

Parameters

Parameter Type Description
other PathistInput Pathist
options? ComparisonOptions Optional comparison options

Returns

number

The zero-based position of the last match, or -1 if not found

See

  • positionOf for finding the first occurrence
  • pathToLast for extracting the path up to the last occurrence

Example

const path = Pathist.from('foo.bar.baz.bar');
console.log(path.lastPositionOf('bar')); // 3 (last occurrence)
console.log(path.lastPositionOf('qux')); // -1 (not found)

pathTo()

pathTo(other, options?): Pathist

Defined in: pathist.ts:1683

Returns the path up to and including the first occurrence of the specified path segment sequence.

This method searches for the first match of the provided path within this path and returns a new Pathist instance containing all segments from the start up to and including the match.

Parameters

Parameter Type Description
other PathistInput Pathist
options? ComparisonOptions Optional comparison options (e.g., indices mode)

Returns

Pathist

A new Pathist instance containing the path up to and including the first match, or an empty path if no match is found

See

  • pathToLast for extracting up to the last occurrence
  • positionOf for getting just the position without extraction
  • slice for general segment extraction

Example

const p = Pathist.from('foo.bar.baz.bar.qux');
p.pathTo('bar').toString();        // 'foo.bar'
p.pathTo('bar.baz').toString();    // 'foo.bar.baz'
p.pathTo('notfound').toString();   // ''

pathToLast()

pathToLast(other, options?): Pathist

Defined in: pathist.ts:1722

Returns the path up to and including the last occurrence of the specified path segment sequence.

This method searches for the last match of the provided path within this path and returns a new Pathist instance containing all segments from the start up to and including the last match.

Parameters

Parameter Type Description
other PathistInput Pathist
options? ComparisonOptions Optional comparison options (e.g., indices mode)

Returns

Pathist

A new Pathist instance containing the path up to and including the last match, or an empty path if no match is found

See

  • pathTo for extracting up to the first occurrence
  • lastPositionOf for getting just the position without extraction

Example

const p = Pathist.from('foo.bar.baz.bar.qux');
p.pathToLast('bar').toString();        // 'foo.bar.baz.bar'
p.pathToLast('bar.baz').toString();    // 'foo.bar.baz'
p.pathToLast('notfound').toString();   // ''

match()

match(pattern, options?): Pathist | null

Defined in: pathist.ts:1784

Returns the first matched subsequence anywhere in this path.

Finds the first occurrence of the pattern within this path and returns a new Pathist containing just the matched segments with their concrete values (not wildcards from the pattern). Returns null if no match is found.

Parameters

Parameter Type Description
pattern PathistInput Pathist
options? ComparisonOptions Optional comparison options (e.g., indices mode)

Returns

Pathist | null

A new Pathist instance containing the matched subsequence, or null if no match

See

  • matchStart for matching only at the beginning
  • matchEnd for matching only at the end
  • includes for checking if a match exists without extraction
  • positionOf for getting just the position

Examples

Basic matching

const path = Pathist.from('foo.bar.baz.qux');
const match = path.match('bar.baz');
console.log(match?.toString()); // 'bar.baz'

Wildcard matching with concrete values

const path = Pathist.from(['foo', 0, 'bar', 1, 'baz']);
const match = path.match('[-1].bar');
console.log(match?.toString()); // '[0].bar' - concrete value!

No match returns null

const path = Pathist.from('foo.bar.baz');
const match = path.match('qux');
console.log(match); // null

matchStart()

matchStart(pattern, options?): Pathist | null

Defined in: pathist.ts:1844

Returns the matched prefix if this path starts with the pattern.

If this path starts with the given pattern, returns a new Pathist containing the matched prefix with concrete values from this path (not wildcards from the pattern). Returns null if the path doesn't start with the pattern.

This method avoids redundant parsing - the pattern is only parsed once, making it more efficient than calling startsWith() followed by slice().

Parameters

Parameter Type Description
pattern PathistInput Pathist
options? ComparisonOptions Optional comparison options (e.g., indices mode)

Returns

Pathist | null

A new Pathist instance containing the matched prefix, or null if no match

See

  • startsWith for checking if path starts with pattern without extraction
  • matchEnd for matching at the end
  • match for matching anywhere

Examples

Basic prefix matching

const path = Pathist.from('foo.bar.baz.qux');
const match = path.matchStart('foo.bar');
console.log(match?.toString()); // 'foo.bar'
console.log(match?.length); // 2

Wildcard matching preserves concrete values

const errorPath = Pathist.from(['foo', 2, 'bar', 'baz']);
const match = errorPath.matchStart('foo[-1].bar');
if (match) {
  console.log(match.toString()); // 'foo[2].bar' - concrete index!
  const remaining = errorPath.slice(match.length); // ['baz']
}

No match returns null

const path = Pathist.from('foo.bar.baz');
const match = path.matchStart('qux');
console.log(match); // null

matchEnd()

matchEnd(pattern, options?): Pathist | null

Defined in: pathist.ts:1898

Returns the matched suffix if this path ends with the pattern.

If this path ends with the given pattern, returns a new Pathist containing the matched suffix with concrete values from this path (not wildcards from the pattern). Returns null if the path doesn't end with the pattern.

This method avoids redundant parsing - the pattern is only parsed once, making it more efficient than calling endsWith() followed by slice().

Parameters

Parameter Type Description
pattern PathistInput Pathist
options? ComparisonOptions Optional comparison options (e.g., indices mode)

Returns

Pathist | null

A new Pathist instance containing the matched suffix, or null if no match

See

  • endsWith for checking if path ends with pattern without extraction
  • matchStart for matching at the start
  • match for matching anywhere

Examples

Basic suffix matching

const path = Pathist.from('foo.bar.baz.qux');
const match = path.matchEnd('baz.qux');
console.log(match?.toString()); // 'baz.qux'
console.log(match?.length); // 2

Wildcard matching preserves concrete values

const errorPath = Pathist.from(['foo', 0, 'bar', 2, 'baz']);
const match = errorPath.matchEnd('[-1].baz');
if (match) {
  console.log(match.toString()); // '[2].baz' - concrete index!
}

No match returns null

const path = Pathist.from('foo.bar.baz');
const match = path.matchEnd('qux');
console.log(match); // null

slice()

slice(start?, end?): Pathist

Defined in: pathist.ts:1932

Returns a new path containing a subset of this path's segments.

Works like Array.slice(), extracting segments from start to end (end not included). The new path preserves this path's configuration.

Parameters

Parameter Type Description
start? number Zero-based index at which to start extraction (default: 0)
end? number Zero-based index before which to end extraction (default: path length)

Returns

Pathist

A new Pathist instance containing the extracted segments

See

  • concat - Combine paths sequentially
  • merge - Intelligently merge paths with overlap detection
  • pathTo - Extract path up to a match

Example

const path = Pathist.from('foo.bar.baz.qux');
console.log(path.slice(1, 3).toString()); // 'bar.baz'
console.log(path.slice(2).toString()); // 'baz.qux'

parentPath()

parentPath(depth): Pathist

Defined in: pathist.ts:1975

Returns the parent path by removing segments from the end.

Removes the specified number of segments from the end of the path, returning a new path representing the parent. If the depth exceeds the path length, returns an empty path rather than throwing an error.

Parameters

Parameter Type Default value Description
depth number 1 Number of levels to go up (default: 1)

Returns

Pathist

A new Pathist instance representing the parent path

Throws

If depth is negative

See

  • slice - General segment extraction
  • concat - Combine paths

Examples

Basic usage

const path = Pathist.from('foo.bar.baz');
console.log(path.parentPath().toString()); // 'foo.bar'
console.log(path.parentPath(2).toString()); // 'foo'
console.log(path.parentPath(3).toString()); // '' (empty path)

Exceeding depth returns empty path

const path = Pathist.from('foo.bar');
console.log(path.parentPath(5).toString()); // '' (empty path, not error)

With zero depth

const path = Pathist.from('foo.bar.baz');
const clone = path.parentPath(0); // Returns clone of full path
console.log(clone.toString()); // 'foo.bar.baz'

concat()

concat(...paths): Pathist

Defined in: pathist.ts:2018

Returns a new path that combines this path with one or more other paths.

Creates a new path by concatenating all segments in order. The new path preserves this path's configuration.

Parameters

Parameter Type Description
...paths (PathistInput Pathist)[]

Returns

Pathist

A new Pathist instance containing all concatenated segments

Throws

If any path input is invalid

See

  • merge - Intelligently merge paths with overlap detection
  • slice - Extract subset of segments

Examples

const path1 = Pathist.from('foo.bar');
const path2 = Pathist.from('baz.qux');
console.log(path1.concat(path2).toString()); // 'foo.bar.baz.qux'

Multiple paths

const result = path1.concat('baz', ['qux', 'quux']);
console.log(result.toString()); // 'foo.bar.baz.qux.quux'

merge()

merge(path): Pathist

Defined in: pathist.ts:2072

Intelligently merges another path with this path by detecting overlapping segments.

Finds the longest suffix of this path that matches a prefix of the other path, then combines them by merging at the overlap point. When overlapping segments include wildcards, concrete values take precedence.

Parameters

Parameter Type Description
path PathistInput Pathist

Returns

Pathist

A new Pathist instance containing the merged path

Throws

If the path input is invalid

See

  • concat - Simple concatenation without overlap detection
  • slice - Extract subset of segments
  • positionOf - Find position of subsequence

Examples

Basic merge with overlap

const left = Pathist.from('foo.bar.baz');
const right = Pathist.from('baz.qux');
console.log(left.merge(right).toString()); // 'foo.bar.baz.qux'

Merge with wildcard replacement

const left = Pathist.from('foo[*].bar');
const right = Pathist.from('foo[5].bar.baz');
console.log(left.merge(right).toString()); // 'foo[5].bar.baz'
// The wildcard is replaced with the concrete index

No overlap - simple concatenation

const left = Pathist.from('foo.bar');
const right = Pathist.from('qux.quux');
console.log(left.merge(right).toString()); // 'foo.bar.qux.quux'

firstNodePath()

firstNodePath(): Pathist

Defined in: pathist.ts:2277

Returns the path to the first node.

  • If the path starts with a numeric index, returns the path up to and including that index
  • Otherwise, returns an empty path (representing the root node)

Returns

Pathist

A new Pathist representing the path to the first node

See

Examples

Path starting with index

const path = new Pathist('[0].children[1].foo');
console.log(path.firstNodePath().toString()); // '[0]'

Path starting with property

const path = new Pathist('children[0].children[1].foo');
console.log(path.firstNodePath().toString()); // '' (root)

Path with no indices

const path = new Pathist('foo.bar');
console.log(path.firstNodePath().toString()); // '' (root)

lastNodePath()

lastNodePath(): Pathist

Defined in: pathist.ts:2312

Returns the full path to the last node in the contiguous tree structure.

  • If the path contains numeric indices, returns the path up to and including the last node
  • Otherwise, returns an empty path (representing the root node)

Returns

Pathist

A new Pathist representing the full node path

See

Examples

Tree structure

const path = new Pathist('children[0].children[1].foo');
console.log(path.lastNodePath().toString()); // 'children[0].children[1]'

Path with no indices

const path = new Pathist('foo.bar');
console.log(path.lastNodePath().toString()); // '' (root)

afterNodePath()

afterNodePath(): Pathist

Defined in: pathist.ts:2348

Returns the path segments after the last node in the tree.

  • If the path contains numeric indices, returns the path after the last node
  • Otherwise, returns the full path (all segments are relative to the root node)

Returns

Pathist

A new Pathist containing the segments after the tree structure

See

Examples

Tree with properties after

const path = new Pathist('children[0].children[1].foo');
console.log(path.afterNodePath().toString()); // 'foo'

No indices - all relative to root

const path = new Pathist('foo.bar');
console.log(path.afterNodePath().toString()); // 'foo.bar'

parentNode()

parentNode(depth): Pathist

Defined in: pathist.ts:2407

Returns the parent node in the tree structure by removing nodes from the end.

Navigates up the tree hierarchy by the specified depth, removing nodes from the end of the node path. If the depth exceeds the number of nodes, returns the first node (or empty path for root).

Parameters

Parameter Type Default value Description
depth number 1 Number of node levels to go up (default: 1)

Returns

Pathist

A new Pathist instance representing the parent node path

Throws

If depth is negative

See

Examples

Basic usage

const path = Pathist.from('children[0].children[1].children[2].value');
console.log(path.lastNodePath().toString()); // 'children[0].children[1].children[2]'
console.log(path.parentNode().toString()); // 'children[0].children[1]'
console.log(path.parentNode(2).toString()); // 'children[0]'
console.log(path.parentNode(3).toString()); // '' (root)

Path starting with index

const path = Pathist.from('[0].children[1].name');
console.log(path.parentNode().toString()); // '[0]'
console.log(path.parentNode(2).toString()); // '[0]' (can't go higher)

Exceeding depth returns first node

const path = Pathist.from('children[0].children[1].value');
console.log(path.parentNode(10).toString()); // '' (root)

No tree structure

const path = Pathist.from('foo.bar.baz');
console.log(path.parentNode().toString()); // '' (root, no nodes in path)

nodeIndices()

nodeIndices(): number[]

Defined in: pathist.ts:2459

Returns the numeric index values from the contiguous tree structure.

Extracts all numeric indices from the tree path, representing the tree path coordinates.

Returns

number[]

An array of numeric indices, or an empty array if no tree structure exists

See

Example

const path = Pathist.from('items[5].children[1].children[3].name');
console.log(path.nodeIndices()); // [5, 1, 3]

const path2 = Pathist.from('foo.bar.baz');
console.log(path2.nodeIndices()); // []

nodePaths()

nodePaths(): Generator<Pathist, void, undefined>

Defined in: pathist.ts:2525

Generates paths to each successive node in the tree structure.

Yields the path to each node level, starting with the root (empty path) and progressively building up through each node in the tree.

Returns

Generator<Pathist, void, undefined>

A generator that yields Pathist instances for each node level

See

Examples

Full tree structure

const path = new Pathist('children[0].children[1].foo');
for (const nodePath of path.nodePaths()) {
  console.log(nodePath.string);
}
// Output:
// ''                            (root)
// 'children[0]'                 (first node)
// 'children[0].children[1]'     (second node)

Path starting with index

const path = new Pathist('[0].children[1].children[2]');
const paths = [...path.nodePaths()];
// paths = [
//   Pathist('[0]'),
//   Pathist('[0].children[1]'),
//   Pathist('[0].children[1].children[2]')
// ]

No tree structure - just root

const path = new Pathist('foo.bar');
const paths = [...path.nodePaths()];
// paths = [Pathist('')]