Last active
August 29, 2015 14:06
-
-
Save Rich-Harris/1128353e4a9500e07871 to your computer and use it in GitHub Desktop.
Keypath object idea
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ) ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
L12:
this.parent = getKeypath( this.keys.slice( 0, -1 ).join( '.' ) );
?