All files / src/namespace simpleObjectPath.js

0% Statements 0/36
0% Branches 0/30
0% Functions 0/3
0% Lines 0/36
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66                                                                                                                                   
function get( obj, path, defaultValue ) {
  if ( typeof path === 'number' ) {
    path = [ path ];
  }
  if ( !path || path.length === 0 ) {
    return obj;
  }
  if ( obj == null ) {
    return defaultValue;
  }
  if ( typeof path === 'string' ) {
    return get( obj, path.split( '.' ), defaultValue );
  }
 
  var currentPath = getKey( path[ 0 ] );
  var nextObj = obj[ currentPath ];
  if ( nextObj === void 0 ) {
    return defaultValue;
  }
 
  if ( path.length === 1 ) {
    return nextObj;
  }
 
  return get( obj[ currentPath ], path.slice( 1 ), defaultValue );
}
 
function set( obj, path, value ) {
  if ( typeof path === 'number' ) {
    path = [ path ];
  }
  if ( !path || path.length === 0 ) {
    return obj;
  }
  if ( typeof path === 'string' ) {
    return set( obj, path.split( '.' ).map( getKey ), value );
  }
  var currentPath = path[ 0 ];
  var currentValue = obj[ currentPath ];
  if ( path.length === 1 ) {
    obj[ currentPath ] = value;
    return currentValue;
  }
 
  if ( currentValue === void 0 ) {
    //check if we assume an array
    if ( typeof path[ 1 ] === 'number' ) {
      obj[ currentPath ] = [];
    } else {
      obj[ currentPath ] = {};
    }
  }
 
  return set( obj[ currentPath ], path.slice( 1 ), value );
}
 
function getKey( key ) {
  var intKey = parseInt( key );
  if ( intKey.toString() === key ) {
    return intKey;
  }
  return key;
}
 
module.exports = { get, set };