Skip to content

Instantly share code, notes, and snippets.

@Rich-Harris
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rich-Harris/1128353e4a9500e07871 to your computer and use it in GitHub Desktop.
Save Rich-Harris/1128353e4a9500e07871 to your computer and use it in GitHub Desktop.
Keypath object idea
import normaliseKeypath from 'shared/normaliseKeypath';
var cache = {}, Keypath;
Keypath = function ( str ) {
this.str = str;
this.keys = this.str.split( '.' );
this.last = this.keys[ this.keys.length - 1 ];
if ( this.keys.length > 1 ) {
this.parent = new Keypath( this.keys.slice( 0, -1 ).join( '.' ) );
} else {
this.parent = null;
}
};
Keypath.prototype = {
toString: function () {
return this.str;
}
};
export default function getKeypath ( str ) {
str = normaliseKeypath( str ); // foo[0] -> foo.0
return ( cache[ str ] || ( cache[ str ] = new Keypath( str ) );
}
@martypdx
Copy link

L12: this.parent = getKeypath( this.keys.slice( 0, -1 ).join( '.' ) );?

kp1 = getKeypath('foo.1.name')
kp2 = getKeypath('foo.1.title')
kp3 = getKeypath('foo.1')
kp3.update(1 /*index*/, 3 /*value*/)

kp1.toString()
// foo.3.name

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment