-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
77 lines (68 loc) · 1.97 KB
/
index.ts
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
import { distance as dist, note, transpose as tr } from '../core'
const fillStr = (character: string, times: number) =>
Array(times + 1).join(character)
const REGEX = /^(_{1,}|=|\^{1,}|)([abcdefgABCDEFG])([,']*)$/
export type AbcTokens = [string, string, string]
export function tokenize(str: string): AbcTokens {
const m = REGEX.exec(str)
if (!m) {
return ['', '', '']
}
return [m[1], m[2], m[3]]
}
/**
* Convert a (string) note in ABC notation into a (string) note in scientific notation
*
* @example
* abcToScientificNotation("c") // => "C5"
*/
export function abcToScientificNotation(str: string): string {
const [acc, letter, oct] = tokenize(str)
if (letter === '') {
return ''
}
let o = 4
for (let i = 0; i < oct.length; i++) {
o += oct.charAt(i) === ',' ? -1 : 1
}
const a =
acc[0] === '_'
? acc.replace(/_/g, 'b')
: acc[0] === '^'
? acc.replace(/\^/g, '#')
: ''
return letter.charCodeAt(0) > 96
? letter.toUpperCase() + a + (o + 1)
: letter + a + o
}
/**
* Convert a (string) note in scientific notation into a (string) note in ABC notation
*
* @example
* scientificToAbcNotation("C#4") // => "^C"
*/
export function scientificToAbcNotation(str: string): string {
const n = note(str)
if (n.empty || (!n.oct && n.oct !== 0)) {
return ''
}
const { letter, acc, oct } = n
const a = acc[0] === 'b' ? acc.replace(/b/g, '_') : acc.replace(/#/g, '^')
const l = oct > 4 ? letter.toLowerCase() : letter
const o =
oct === 5 ? '' : oct > 4 ? fillStr("'", oct - 5) : fillStr(',', 4 - oct)
return a + l + o
}
export function transpose(note: string, interval: string): string {
return scientificToAbcNotation(tr(abcToScientificNotation(note), interval))
}
export function distance(from: string, to: string): string {
return dist(abcToScientificNotation(from), abcToScientificNotation(to))
}
export default {
abcToScientificNotation,
scientificToAbcNotation,
tokenize,
transpose,
distance,
}