function formatBytes(bytes) {
if (0 === bytes)
return '0 Bytes';
const sizes = [
'Bytes',
'KB',
'MB',
'GB',
'TB',
'PB',
'EB',
'ZB',
'YB'
],
s = Math.floor(Math.log(bytes) / Math.log(1024)),
size = bytes / Math.pow(1024, s);
return `${size.toFixed(2)} ${sizes[s]}`
}
Concatenate Arrays of Objects and Exclude Duplicates
function mergeUniqueObjects(array, items, key = 'id') {
return array.reduce((accumulator, item) => {
const duplicate = accumulator.find(i => item[key] === i[key]);
if (duplicate === undefined) {
accumulator.push(item);
}
return accumulator;
}, items);
}
Remove Objects with Duplicate Property from Array
function removeDuplicates(array, property) {
return array.filter((item, index, a) => a.map(i => i[property]).indexOf(item[property]) === index);
}
Get Distance Between Two Points
from math import sqrt
def get_distance(origin, destination):
'''Distance Between Two Points'''
(o_x, o_y) = origin
(d_x, d_y) = destination
return sqrt((d_x - o_x)**2.0 + (d_y - o_y)**2.0)
Synchronize $remote and $local Files
function sync_files( $remote, $local )
{
if ( ! is_file( $local ) ) { return copy( $remote, $local ); }
$handle = fopen( $remote, 'r' );
if ( ! $handle ) { die( "Could not open {$remote}." ); }
$meta = stream_get_meta_data( $handle );
fclose( $handle );
foreach( $meta['wrapper_data'] as $response )
{
// Redirection
if ( substr( strtolower( $response ), 0, 10 ) === 'location: ' ) {
return sync_files( substr( $response, 10 ), $local );
}
// Compare sizes
if ( substr( strtolower( $response ), 0, 16 ) === 'content-length: ' )
{
if ( (int) filesize( $local ) !== (int) substr( $response, 16 ) ) {
return copy( $remote, $local );
}
continue;
}
// Compare dates
if ( substr( strtolower( $response ), 0, 15 ) === 'last-modified: ' )
{
if ( (int) filemtime( $local ) < (int) strtotime( substr( $response, 15 ) ) ) {
return copy( $remote, $local );
}
continue;
}
}
return false;
}
Remove Nodes (Comments, Script Tags) from $html String
function remove_nodes( $html, array $selectors = array( '//comment()', '//script' ) )
{
$dom = new DOMDocument;
$dom->loadHtml( strval( $html ) );
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$xpath = new DOMXPath( $dom );
foreach( $selectors as $selector ) {
while ( $node = $xpath->query( $selector )->item( 0 ) ) {
// Remove selected tag from html string
$node->parentNode->removeChild( $node );
}
}
return $dom->saveHTML();
}