sodiray / radash

Functional utility library - modern, simple, typed, powerful
https://radash-docs.vercel.app
MIT License
4.19k stars 167 forks source link

add something like `pathToSegments` & `pathFromSegments` #274

Open JacobWeisenburger opened 1 year ago

JacobWeisenburger commented 1 year ago

They could be something like this:

function pathFromSegments ( pathSegments: ( string | number )[] ): string {
    return pathSegments.join( '.' )
}

console.log( pathFromSegments( [ 'sizes', 0, 'range', 1 ] ) ) // sizes.0.range.1
console.log( pathFromSegments( [ 'sizes', '0', 'range', '1' ] ) ) // sizes.0.range.1
function pathToSegments ( path: string ): string[] {
    return path.split( /[\.\[\]]/g )
        .map( string => string.trim() )
        .filter( string => string.length )
}

console.log( pathToSegments( 'sizes.0.range.1' ) ) // [ 'sizes', '0', 'range', '1' ]
console.log( pathToSegments( 'sizes[0].range[1]' ) ) // [ 'sizes', '0', 'range', '1' ]
console.log( pathToSegments( ' sizes [ 0 ] . range[ 1 ] ' ) ) // [ 'sizes', '0', 'range', '1' ]