Passed
Push — async ( 76f42a...eb4889 )
by Ilya
01:16
created

binary_stream.js ➔ finalize   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
/**
2
 * binary array stream object
3
 *
4
 *
5
 * @return The binaryStream object.
6
 *
7
 * @static
8
 *
9
 * @example
10
 *     var binaryStream = binaryStream([1,2,3]);
11
 *     binaryStream.appendBytes([4,5,6]);
12
 *     binaryStream.appendBytes("\x07\x08\x09");
13
 *     console.log(binaryStream.finalize()) // returns Uint8Array [1,2,3,4,5,6,7,8,9]
14
 *
15
 * @param file a fileElement object
0 ignored issues
show
Documentation introduced by
The parameter file does not exist. Did you maybe forget to remove this comment?
Loading history...
16
 */
17
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...
18
    let _data = new Uint8Array(arr);
19
20
    function appendBytes(input) {
21
        let tmp;
22
23
        if (typeof (input) == "number") {
24
            let hex_string = input.toString(16);
25
            tmp = new Uint8Array(hex_string.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
26
        } else if (typeof (input) == "string") {
27
            tmp = new Uint8Array(input.length);
28
            for (let i = 0; i < input.length; i ++) {
29
                tmp[i] = input.charCodeAt(i);
30
            }
31
        } else {
32
            tmp = new Uint8Array(input);
33
        }
34
35
        let new_uint8_arr = new Uint8Array(_data.length + tmp.length);
36
37
        new_uint8_arr.set(_data);
38
        new_uint8_arr.set(tmp, _data.length);
39
40
        _data = new_uint8_arr;
41
    };
42
43
    function get(i) {
44
        return _data[i];
45
    }
46
47
    function finalize() {
48
        return _data;
49
    };
50
51
    function getLength() {
52
        return _data.length;
53
    }
54
55
    return {
56
        appendBytes: appendBytes,
57
        finalize: finalize,
58
        get: get,
59
        getLength: getLength,
60
    }
61
}