UNPKG

tonal-abc-notation

Version:

Conversion between notes in ABC and scientific notation

86 lines (77 loc) 2.38 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var tonalNote = require('tonal-note'); /** * [![npm version](https://img.shields.io/npm/v/tonal-abc-notation.svg?style=flat-square)](https://www.npmjs.com/package/tonal-abc-notation) * * Convert note strings between ABC and scientific notation * * This is part of [tonal](https://www.npmjs.com/package/tonal) music theory library. * * @example * const Abc = require("tonal-abc-notation") * Abc.toNote("c") // => "C5" * Abc.toAbc("Db2") // => "_D,," * * @example * import Tonal from "tonal" * import { toAbc } from "tonal-abc-notation" * Tonal.Scale.notes("C major").map(toAbc); * * @module Abc */ var REGEX = /^(_{1,}|=|\^{1,}|)([abcdefgABCDEFG])([,']*)$/; var fillStr = function (s, n) { return Array(n + 1).join(s); }; function tokenize(str) { var 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 * * @param {string} abcNote - the note in ABC notation * @return {string} the note in scientific notation of null if not valid * @example * Abc.toNote("c") // => "C5" */ function toNote(str) { var ref = tokenize(str); var acc = ref[0]; var letter = ref[1]; var oct = ref[2]; if (letter === "") { return null; } var o = 4; for (var i = 0; i < oct.length; i++) { o += oct[i] === "," ? -1 : 1; } var 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 * * @param {string} note - a note in scientific notation * @return {string} the note in ABC notation or null if not valid note * @example * abc.toAbc("C#4") // => "^C" */ function toAbc(str) { var ref = tonalNote.props(str); var letter = ref.letter; var acc = ref.acc; var oct = ref.oct; var a = acc[0] === "b" ? acc.replace(/b/g, "_") : acc.replace(/#/g, "^"); var l = oct > 4 ? letter.toLowerCase() : letter; var o = oct === 5 ? "" : oct > 4 ? fillStr("'", oct - 5) : fillStr(",", 4 - oct); return a + l + o; } exports.tokenize = tokenize; exports.toNote = toNote; exports.toAbc = toAbc;