ram
8/19/2015 12:20:00 PM
Ajinkya Joshi <ajinkya.joshi.d@gmail.com> writes:
>Write a javascript function, findPath(obj, str), that takes a
>javascript object and a string parameter and iterates through
>the object and returns the path to the key that contains the
>string as a value (using '.' as a separator). For example:
>var obj = { bat: bee, bird: plane, bee : { foo : bar, test : { text: needle } } };
>var path = findPath (obj, 'needle');
>Would yield:
>path = "bee.test.text"
This is a quick attempt at it that prints »bee.test.text« in
the special case you gave as an example, but still contains
errors and is written in bad style. Your remaining exercise
is to find all the errors in my code and remove them and
improve the style of my code.
( function()
{ "use strict";
function PathJoin( prefix, postfix )
{ return( prefix.length > 0 ? prefix + "." : "" )+ postfix; }
function output( string )
{ console.log( string );
document.write( string ); }
function findPathImpl( path, container, value )
{ "use strict";
const
hasOwn = Object.prototype.hasOwnProperty;
var
key,
entry;
for( key in container )if( hasOwn.call( container, key ))
{ if( typeof key === "string" )
{ entry = container[ key ];
if( typeof entry === "string" )
{ if( container[ key ]=== value )return PathJoin( path, key ); }
else if( typeof entry === "object" )
return findPathImpl( PathJoin( path, key ), entry, value ); }}
return undefined; }
function findPath( container, value )
{ "use strict";
return findPathImpl( "", container, value ); }
function test()
{ "use strict";
const
obj ={ bat: 'bee', bird: 'plane', bee :{ alpha : 'beta', test :{ text: 'needle' }}},
path = findPath( obj, 'needle' );
output( path ); }
test(); }) ();