Skip to content

Instantly share code, notes, and snippets.

@iSkore
Last active March 15, 2017 20:57
Show Gist options
  • Save iSkore/dcfa6399f7dce509fd4a7b7c7592ec96 to your computer and use it in GitHub Desktop.
Save iSkore/dcfa6399f7dce509fd4a7b7c7592ec96 to your computer and use it in GitHub Desktop.
Very helpful JavaScript functions
/**
* Desc: Checks if a deep property exists
* Exp: checkNested( { a: { b: { c: "d" } } } );
* Returns: Boolean
*/
function checkNested( obj ) {
const args = Array.prototype.slice.call( arguments, 1 );
for( let i = 0; i < args.length; i++ ) {
if( !obj || !obj.hasOwnProperty( args[ i ] ) )
return false;
obj = obj[ args[ i ] ];
}
return true;
}
/**
* Desc: Checks if string is encoded with encodeURIComponent
* Exp: isEncoded( "~%2F" );
* Returns: Boolean
*/
function isEncoded( str ) {
return typeof str === 'string' && decodeURIComponent( str ) !== str;
}
function isString( str ) {
return str && typeof str === 'string';
}
function removeProperties( obj, properties ) {
for( let i = 0; i < properties.length; i++ )
delete obj[ properties[ i ] ];
return obj;
}
function isMissingProperty( obj, properties ) {
let hasOwnProperty = false, i = 0;
for( ; i < properties.length; i++ )
if( !obj.hasOwnProperty( properties[ i ] ) )
hasOwnProperty = properties[ i ];
return hasOwnProperty;
}
function containsProperty( obj, properties ) {
let hasOwnProperty = false, i = 0;
for( ; i < properties.length; i++ )
if( !hasOwnProperty && obj.hasOwnProperty( properties[ i ] ) )
hasOwnProperty = properties[ i ];
return hasOwnProperty;
}
function payloadSizeMax( obj ) {
return JSON.stringify( obj ).length >= 1536;
}
function uriSizeMax( obj ) {
let isOk = false;
Object.keys( obj ).filter( k => isOk = !isOk ? k.length >= 512 ? k : isOk : isOk );
return isOk;
}
function notValidEmail( email ) {
return !/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test( email );
}
function notValidPassword( pass ) {
return !/^(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,})/.test( pass );
}
function cleanObj( o ) {
if( o && o === o )
if( typeof o === "string" ) return o;
else if( typeof o === "number" ) return o;
else if( Array.isArray( o ) ) {
let x = [], i = -1, l = o.length, r = 0;
while( ++i < l ) if( o[ i ] ) x[ r++ ] = cleanObj( o[ i ] );
return x;
} else if( typeof o === "object" ) {
for( const k in o ) o[ k ] ? o[ k ] = cleanObj( o[ k ] ) : delete o[ k ];
return o;
} else
return "Argument Error - Unknown Item";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment