import * as is from '../is';
import { extend } from './extend';
export const mapEmpty = map => {
let empty = true;
if( map != null ){
return Object.keys( map ).length === 0;
}
return empty;
};
export const pushMap = options => {
let array = getMap( options );
if( array == null ){ setMap( extend( {}, options, {
value: [ options.value ]
} ) );
} else {
array.push( options.value );
}
};
export const setMap = options => {
let obj = options.map;
let keys = options.keys;
let l = keys.length;
for( let i = 0; i < l; i++ ){
let key = keys[ i ];
if( is.plainObject( key ) ){
throw Error( 'Tried to set map with object key' );
}
if( i < keys.length - 1 ){
if( obj[ key ] == null ){
obj[ key ] = {};
}
obj = obj[ key ];
} else {
obj[ key ] = options.value;
}
}
};
export const getMap = options => {
let obj = options.map;
let keys = options.keys;
let l = keys.length;
for( let i = 0; i < l; i++ ){
let key = keys[ i ];
if( is.plainObject( key ) ){
throw Error( 'Tried to get map with object key' );
}
obj = obj[ key ];
if( obj == null ){
return obj;
}
}
return obj;
};
export const deleteMap = options => {
let obj = options.map;
let keys = options.keys;
let l = keys.length;
let keepChildren = options.keepChildren;
for( let i = 0; i < l; i++ ){
let key = keys[ i ];
if( is.plainObject( key ) ){
throw Error( 'Tried to delete map with object key' );
}
let lastKey = i === options.keys.length - 1;
if( lastKey ){
if( keepChildren ){ let children = Object.keys( obj );
for( let j = 0; j < children.length; j++ ){
let child = children[j];
if( !keepChildren[ child ] ){
obj[ child ] = undefined;
}
}
} else {
obj[ key ] = undefined;
}
} else {
obj = obj[ key ];
}
}
};