UNPKG

@tonaljs/abc-notation

Version:

Parse musical notes in abc notation

57 lines 1.72 kB
// index.ts import { distance as dist, transpose as tr } from "@tonaljs/pitch-distance"; import { note } from "@tonaljs/pitch-note"; var fillStr = (character, times) => Array(times + 1).join(character); var REGEX = /^(_{1,}|=|\^{1,}|)([abcdefgABCDEFG])([,']*)$/; function tokenize(str) { const m = REGEX.exec(str); if (!m) { return ["", "", ""]; } return [m[1], m[2], m[3]]; } function abcToScientificNotation(str) { 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; } function scientificToAbcNotation(str) { 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; } function transpose(note2, interval) { return scientificToAbcNotation(tr(abcToScientificNotation(note2), interval)); } function distance(from, to) { return dist(abcToScientificNotation(from), abcToScientificNotation(to)); } var abc_notation_default = { abcToScientificNotation, scientificToAbcNotation, tokenize, transpose, distance }; export { abcToScientificNotation, abc_notation_default as default, distance, scientificToAbcNotation, tokenize, transpose }; //# sourceMappingURL=index.mjs.map