-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparse.js
92 lines (74 loc) · 2.8 KB
/
parse.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// parse.js contains the implementation for translating some random input into
// the tracks.
function newTrack(track) {
return {
id: Math.floor(Math.random() * 1e9),
number: '',
title: '',
time: '',
highlight: [],
editingNumber: false,
editingTitle: false,
editingTime: false,
...track
}
}
function parseTracks(str, lineMode) {
let lines = str.split('\n').filter(x => x.trim() !== '');
const trackNumberRegex = /^\d+[.-\s|]*/;
const trackTimeRegex = /(\d+:)?\d+:\d\d/;
if (lineMode === 'artist-first') {
let newLines = [];
for (let i = 0; i < lines.length; i += 2) {
newLines.push(lines[i] + ' - ' + lines[i+1])
}
lines = newLines;
}
if (lineMode === 'title-first') {
let newLines = [];
for (let i = 0; i < lines.length; i += 2) {
newLines.push(lines[i+1] + ' - ' + lines[i])
}
lines = newLines;
}
const tracks = lines.map((line, i) => {
let track = {
title: line.trim()
};
// Always use short dashes.
track.title = track.title.replace(/\u2013|\u2014/g, '-');
if (track.title.match(trackNumberRegex)) {
const match = trackNumberRegex.exec(track.title)[0];
track.number = match.replace(/[^\d]/g, '');
track.number = track.number.replace(/^0+/, '');
track.title = track.title.replace(match, '').trim();
}
if (track.title.match(trackTimeRegex)) {
track.time = trackTimeRegex.exec(track.title)[0];
track.title = track.title.replace(track.time, '').trim();
// Trim off any leading zeros from the time (ie. '01:23' -> '1:23').
track.time = track.time.replace(/^[0:]+/g, '');
}
// Strip surrounding "".
// TODO: This should be smarter to only do this is almost all of the
// tracks look like this.
track.title = track.title.replace(/^"|"$/g, '');
// Remove multiple spaces. This also replaces tabs with spaces.
track.title = track.title.replace(/\s+/g, ' ');
// Strip remaining punctuation.
track.title = track.title.replace(/\(\s*\)$/g, ' ');
track.title = track.title.replace(/[|-\s]+$/g, '');
// Replace backticks and single curly apostrophes with regular apostrophes
track.title = track.title
.replace(/`/g, "'")
.replace(/[\u2018\u2019]/g, "'");
// Replace double smart quotes with regular apostrophes
track.title = track.title.replace(/[\u201C\u201D]/g, "\"");
track.title = track.title.trim();
return newTrack(track);
});
return tracks;
}
if (typeof module !== 'undefined') {
module.exports = parseTracks;
}