saebekassebil / teoria

Javascript taught Music Theory
http://saebekassebil.github.io/teoria
MIT License
1.32k stars 115 forks source link

Normalizing a note #68

Closed amitgur closed 9 years ago

amitgur commented 9 years ago

Somtimes musical operations on note and interval gets notes like B# or Fb. I needed to simplify that to c and e, I wrote this function. Any other way to do that ?

teoria.normalizeNote = function(n){

var acc = n.accidental();

if (acc === '#') {
    var name =  n.name();
    if (name === 'b'){
        return teoria.note('c' + (n.octave() + 1));
    }
    if (name === 'e'){
        return teoria.note('f' + (n.octave()));
    }
}

if (acc === 'b') {
    var name =  n.name();
    if (name === 'c'){
        return teoria.note('b' + (n.octave() - 1));
    }
    if (name === 'f'){
        return teoria.note('e' + (n.octave()));
    }
}
return n;

I guess there should be a function for the general case Gbb=F

saebekassebil commented 9 years ago

You should be able to do that by utilizing the TeoriaNote#enharmonics() method.

function simplifyNote(note) {
  var acc = Math.abs(note.accidentalValue());
  if (acc === 0) return note;

  var simplestNote = note;
  note.enharmonics().forEach(function(note) {
    var enharmonicAcc = Math.abs(note.accidentalValue());
    if (enharmonicAcc < acc) {
      simplestNote = note;
      acc = enharmonicAcc;
    }
  });

  return simplestNote;
}