Passed
Pull Request — main (#2)
by Ilya
01:56
created

binary_stream.js ➔ getLength   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
1
/** global: binaryStream */
2
3
/**
4
 * binary array stream object
5
 *
6
 *
7
 * @return The binaryStream object.
8
 *
9
 * @static
10
 *
11
 * @example
12
 *     var binaryStream = binaryStream([1,2,3]);
13
 *     binaryStream.appendBytes([4,5,6]);
14
 *     binaryStream.appendBytes("\x07\x08\x09");
15
 *     console.log(binaryStream.finalize()) // returns Uint8Array [1,2,3,4,5,6,7,8,9]
16
 *
17
 * @param arr origin array
18
 */
19
const binaryStream = function(arr = []) {
1 ignored issue
show
Unused Code introduced by
The constant binaryStream seems to be never used. Consider removing it.
Loading history...
20
    let _data = new Uint8Array(arr);
21
22
    function appendBytes(input) {
23
        let tmp;
24
25
        if (typeof (input) == "number") {
26
            let hex_string = input.toString(16);
27
            tmp = new Uint8Array(hex_string.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
28
        } else if (typeof (input) == "string") {
29
            tmp = new Uint8Array(input.length);
30
            for (let i = 0; i < input.length; i ++) {
31
                tmp[i] = input.charCodeAt(i);
32
            }
33
        } else {
34
            tmp = new Uint8Array(input);
35
        }
36
37
        let new_uint8_arr = new Uint8Array(_data.length + tmp.length);
38
39
        new_uint8_arr.set(_data);
40
        new_uint8_arr.set(tmp, _data.length);
41
42
        _data = new_uint8_arr;
43
    };
44
45
    function get(i) {
46
        return _data[i];
47
    }
48
49
    function finalize() {
50
        return _data;
51
    };
52
53
    function getLength() {
54
        return _data.length;
55
    }
56
57
    return {
58
        appendBytes: appendBytes,
59
        finalize: finalize,
60
        get: get,
61
        getLength: getLength,
62
    }
63
}