halis-state
Version:
Manage immutable state with these helpers for Objects and Arrays
89 lines (64 loc) • 1.76 kB
JavaScript
;
const isObject = object => {
if ( object instanceof Array ) return false;
else if ( object === null ) return false;
else return typeof object === 'object';
};
const isArray = array => array instanceof Array;
const isString = string => typeof string === 'string';
const defaultFn = ( is, defaultValue ) => {
return object => {
if ( object && is( object) ) return object;
else return defaultValue;
};
};
const defaultObject = defaultFn( isObject, {} );
const defaultArray = defaultFn( isArray, [] );
const copyObject = ( object, merge ) => {
merge = defaultObject( merge || {} );
object = defaultObject( object || {} );
return Object.assign( merge, object );
};
const copyArray = ( array, merge ) => ( array || [] ).concat( merge || [] );
const insertObject = ( object, key, value ) => {
let copy;
if ( !key || !isString( key ) ) return object;
copy = copyObject( object );
copy[ key ] = value || null;
return copy;
};
const pushArray = ( array, item ) => {
let copy;
if ( !array || !array.length || !isArray( array ) ) return [ item ];
if ( item === undefined ) return array;
copy = copyArray( array );
copy.push( item );
return copy;
};
const removeArrayIndex = ( array, index ) => {
let copy;
if ( !array || array.length < index ) return array;
copy = copyArray( array );
copy.splice( index, 1 );
return copy;
};
const removeObjectKey = ( object, key ) => {
let copy;
if ( !key || !isString( key ) || object[ key ] === undefined ) return object;
copy = copyObject( object );
delete copy[ key ];
return copy;
};
module.exports = {
isObject,
isArray,
isString,
defaultObject,
defaultArray,
copyObject,
copyArray,
insertObject,
pushArray,
removeArrayIndex,
removeObjectKey
};