Completed
Push — master ( 8caa6f...c37a57 )
by Jan
20s queued 13s
created

src/util-text-encoding.ts   A

Complexity

Total Complexity 5
Complexity/F 1.67

Size

Lines of Code 40
Function Count 3

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 5
eloc 30
mnd 2
bc 2
fnc 3
dl 0
loc 40
rs 10
bpm 0.6666
cpm 1.6666
noi 0
c 0
b 0
f 0

3 Functions

Rating   Name   Duplication   Size   Complexity  
A util-text-encoding.ts ➔ bufferToDecodedString 0 9 1
A util-text-encoding.ts ➔ stringToEncodedBuffer 0 8 1
A util-text-encoding.ts ➔ encodingFromStringOrByte 0 16 3
1
import iconv = require('iconv-lite')
2
import { isString } from "./util"
3
4
export function stringToEncodedBuffer(
5
    value: string,
6
    encodingByte: string | number
7
) {
8
    return iconv.encode(
9
        value,
10
        encodingFromStringOrByte(encodingByte)
11
    )
12
}
13
14
export function bufferToDecodedString(
15
    buffer: Buffer,
16
    encodingByte: string | number
17
) {
18
    return iconv.decode(
19
        buffer,
20
        encodingFromStringOrByte(encodingByte)
21
    ).replace(/\0/g, '')
22
}
23
24
function encodingFromStringOrByte(encoding: string | number) {
25
    const ENCODINGS = [
26
        'ISO-8859-1', 'UTF-16', 'UTF-16BE', 'UTF-8'
27
    ]
28
29
    if (isString(encoding) && ENCODINGS.includes(encoding)) {
30
        return encoding
31
    }
32
    if (
33
        typeof encoding === "number" &&
34
        encoding >= 0 && encoding < ENCODINGS.length
35
    ) {
36
        return ENCODINGS[encoding]
37
    }
38
    return ENCODINGS[0]
39
}
40
41