Killer one-liners Javascript
const shuffleArray = ( arr ) => arr . sort ( ( ) => Math . random ( ) - 0.5 ) ;
// Testing
const arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] ;
console . log ( shuffleArray ( arr ) ) ;
const copyToClipboard = ( text ) =>
navigator . clipboard ?. writeText && navigator . clipboard . writeText ( text ) ;
// Testing
copyToClipboard ( "Hello World!" ) ;
const scrollToTop = ( element ) =>
element . scrollIntoView ( { behavior : "smooth" , block : "start" } ) ;
const scrollToBottom = ( element ) =>
element . scrollIntoView ( { behavior : "smooth" , block : "end" } ) ;
const sleep = ( ms ) => new Promise ( ( resolve ) => setTimeout ( resolve , ms ) ) ;
Go Back to the Previous Page
const navigateBack = ( ) => history . back ( ) ;
// Or
const navigateBack = ( ) => history . go ( - 1 ) ;
const isEqual = ( a , b ) => JSON . stringify ( a ) === JSON . stringify ( b ) ;
// examples
isEqual ( { a : 1 , b : 2 } , { a : 1 , b : 2 } ) ; // true
isEqual ( { a : 1 , b : 2 } , { a : 1 , b : 3 } ) ; // false
// works with arrays too
isEqual ( [ 1 , 2 , 3 ] , [ 1 , 2 , 3 ] ) ; // true
isEqual ( [ 1 , 2 , 3 ] , [ 1 , 2 , 4 ] ) ; // false
const uuid = ( ) =>
( [ 1e7 ] + - 1e3 + - 4e3 + - 8e3 + - 1e11 ) . replace ( / [018]/ g, ( c ) =>
(
c ^
( crypto . getRandomValues ( new Uint8Array ( 1 ) ) [ 0 ] & ( 15 >> ( c / 4 ) ) )
) . toString ( 16 )
) ;
const getSelectedText = ( ) => window . getSelection ( ) . toString ( ) ;
Check if an Element is Focused
const hasFocus = ( element ) => element === document . activeElement ;
Count by the Properties of an Array of Objects
const countElementsByProp = ( arr , prop ) =>
arr . reduce (
( prev , curr ) => ( ( prev [ curr [ prop ] ] = ++ prev [ curr [ prop ] ] || 1 ) , prev ) ,
{ }
) ;
// example
countElementsByProp (
[
{ manufacturer : "audi" , model : "q8" , year : "2019" } ,
{ manufacturer : "audi" , model : "rs7" , year : "2020" } ,
{ manufacturer : "ford" , model : "mustang" , year : "2019" } ,
{ manufacturer : "ford" , model : "explorer" , year : "2020" } ,
{ manufacturer : "bmw" , model : "x7" , year : "2020" } ,
] ,
"manufacturer"
) ; // { 'audi': 2, 'ford': 2, 'bmw': 1 }