src/frames/frame-popm.ts   A
last analyzed

Complexity

Total Complexity 3
Complexity/F 0

Size

Lines of Code 48
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 3
eloc 29
mnd 3
bc 3
fnc 0
dl 0
loc 48
rs 10
bpm 0
cpm 0
noi 0
c 0
b 0
f 0
1
import { FrameBuilder } from "../FrameBuilder"
2
import { FrameReader } from "../FrameReader"
3
import { Popularimeter } from "../types/TagFrames"
4
5
export const POPM = {
6
    create: (data: Popularimeter): Buffer => {
7
        if(data.email == undefined) {
8
            throw new RangeError("An email is expected")
9
        }
10
11
        // TODO: starting version 0.3 for both rating and counter do not
12
        // implicitely trunc and use Number.isInteger() instead to validate
13
14
        const rating = Math.trunc(data.rating)
15
        if( isNaN(rating) || rating < 0 || rating > 255) {
16
            throw new RangeError(
17
                `Provided rating ${data.rating} is not in the valid range 0-255`
18
            )
19
        }
20
21
        // TODO: According to specs, the counter can be omitted
22
        // TODO: According to specs if the value is bigger than a 32 bits
23
        // a byte can be added and so on... (very unlikely to happen in
24
        // real life as it means more than 4GB listenings!)
25
26
        const counter = Math.trunc(data.counter)
27
        if (isNaN(counter) || counter < 0) {
28
            throw new RangeError(
29
                `Provided counter ${data.counter} is not a positive integer`
30
            )
31
        }
32
33
        return new FrameBuilder("POPM")
34
            .appendTerminatedText(data.email)
35
            .appendNumber(rating, {size: 1})
36
            .appendNumber(counter, {size: 4})
37
            .getBufferWithPartialHeader()
38
    },
39
    read: (buffer: Buffer): Popularimeter => {
40
        const reader = new FrameReader(buffer)
41
        return {
42
            email: reader.consumeTerminatedText(),
43
            rating: reader.consumeNumber({size: 1}),
44
            counter: reader.consumeNumber({size: 4})
45
        }
46
    }
47
}
48