15
15
* limitations under the License.
16
16
*/
17
17
18
+ import { base64Encode } from '@firebase/util' ;
18
19
import { HeartbeatsByUserAgent } from './types' ;
19
20
20
- const BASE64_SIZE_MULTIPLIER = 4 / 3 ;
21
- const BYTES_PER_DATE = 12 * BASE64_SIZE_MULTIPLIER ;
22
-
21
+ /**
22
+ * Calculate byte length of a string. From:
23
+ * https://codereview.stackexchange.com/questions/37512/count-byte-length-of-string
24
+ */
23
25
function getByteLength ( str : string ) : number {
24
26
let byteLength = 0 ;
25
27
for ( let i = 0 ; i < str . length ; i ++ ) {
@@ -41,7 +43,7 @@ function getByteLength(str: string): number {
41
43
* being stringified and converted to base64.
42
44
*/
43
45
export function countHeartbeatBytes ( heartbeat : HeartbeatsByUserAgent ) : number {
44
- return getByteLength ( JSON . stringify ( heartbeat ) ) * BASE64_SIZE_MULTIPLIER ;
46
+ return getByteLength ( base64Encode ( JSON . stringify ( heartbeat ) ) ) ;
45
47
}
46
48
47
49
/**
@@ -51,13 +53,9 @@ export function countHeartbeatBytes(heartbeat: HeartbeatsByUserAgent): number {
51
53
*/
52
54
export function countBytes ( heartbeatsCache : HeartbeatsByUserAgent [ ] ) : number {
53
55
// heartbeatsCache wrapper properties
54
- let count =
55
- getByteLength ( JSON . stringify ( { version : 2 , heartbeats : [ ] } ) ) *
56
- BASE64_SIZE_MULTIPLIER ;
57
- for ( const heartbeat of heartbeatsCache ) {
58
- count += countHeartbeatBytes ( heartbeat ) ;
59
- }
60
- return count ;
56
+ return getByteLength (
57
+ base64Encode ( JSON . stringify ( { version : 2 , heartbeats : heartbeatsCache } ) )
58
+ ) ;
61
59
}
62
60
63
61
/**
@@ -73,6 +71,9 @@ export function splitHeartbeatsCache(
73
71
heartbeatsToSend : HeartbeatsByUserAgent [ ] ;
74
72
heartbeatsToKeep : HeartbeatsByUserAgent [ ] ;
75
73
} {
74
+ const BYTES_PER_DATE = getByteLength (
75
+ base64Encode ( JSON . stringify ( '2022-12-12' ) )
76
+ ) ;
76
77
let totalBytes = 0 ;
77
78
const heartbeatsToSend = [ ] ;
78
79
const heartbeatsToKeep = [ ...heartbeatsCache ] ;
0 commit comments