import Base64 from "./base64" ; /**
 * Tuple of 4 Uint8Arrays representing 4 serialized Long Unsigned Integers
 */ export type ByteBuffer = [ Uint8Array , Uint8Array , Uint8Array , Uint8Array ] ; const B64 = new Base64 ( ) ; param str returns { ByteBuffer } export const decode = ( str ) : ByteBuffer => { const base64Array = B64 . decode ( str ) . split ( "=" ) ; base64Array . pop ( ) ; return [ decodeB64 ( base64Array [ 0 ] ) , decodeB64 ( base64Array [ 1 ] ) , decodeB64 ( base64Array [ 2 ] ) , decodeB64 ( base64Array [ 3 ] ) , ] ; } ; param buffer returns { string } export const encode = ( buffer ) : string => { const base64Array = buffer . map ( ( u8 ) => B64 . encode ( String . fromCharCode . apply ( null , u8 ) ) ) ; return B64 . encode ( base64Array . join ( "" ) ) ; } ; returns { string } export const getUUID = ( ) : string => { const dateBytes = NumberToByteArray ( Date . now ( ) ) ; return encode ( [ dateBytes , randomByteArray ( ) , randomByteArray ( ) , randomByteArray ( ) ] ) ; } ; param id returns { Date } export const getDate = ( id ) : Date => { let time = 0 ; const decoded = decode ( id ) ; const decodedTime = decoded [ 0 ] ; for ( let i = decodedTime . length - 1 ; i >= 0 ; i -- ) { if ( decodedTime [ i - 2 ] !== undefined ) { time = ( time + decodedTime [ i - 1 ] ) * 256 ; } else if ( decodedTime [ i - 1 ] === undefined ) { time += decodedTime [ i ] ; } } return new Date ( time ) ; } ; param b64 returns { Uint8Array } function decodeB64 ( b64 ) { const decoded = B64 . decode ( b64 ) . split ( "" ) . map ( ( c ) => c . charCodeAt ( 0 ) ) ; decoded . pop ( ) ; return new Uint8Array ( decoded ) ; } param long returns { Uint8Array } constructor function NumberToByteArray ( long ) { const byteArray = [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] ; for ( let index = 0 ; index < byteArray . length ; index ++ ) { const byte = long & 0xff ; byteArray [ index ] = byte ; long = ( long - byte ) / 256 ; } return new Uint8Array ( byteArray ) ; } returns { Uint8Array } function randomByteArray ( ) { const byteArray = [ ] ; byteArray . push ( Math . floor ( Math . random ( ) * ( 0x100 ) ) ) ; byteArray . push ( Math . floor ( Math . random ( ) * ( 0x100 ) ) ) ; byteArray . push ( Math . floor ( Math . random ( ) * ( 0x100 ) ) ) ; byteArray . push ( Math . floor ( Math . random ( ) * ( 0x100 ) ) ) ; byteArray . push ( Math . floor ( Math . random ( ) * ( 0x100 ) ) ) ; byteArray . push ( Math . floor ( Math . random ( ) * ( 0x100 ) ) ) ; byteArray . push ( Math . floor ( Math . random ( ) * ( 0x100 ) ) ) ; byteArray . push ( Math . floor ( Math . random ( ) * ( 0x100 ) ) ) ; return new Uint8Array ( byteArray ) ; }