Skip to content

Instantly share code, notes, and snippets.

@DavidGoussev
Last active December 31, 2015 07:05
Show Gist options
  • Select an option

  • Save DavidGoussev/4f11754dedb48d0130b4 to your computer and use it in GitHub Desktop.

Select an option

Save DavidGoussev/4f11754dedb48d0130b4 to your computer and use it in GitHub Desktop.
musical pitch hash
def pitch_class(note)
hash = { 'C' => 0, 'D' => 2, 'E' => 4, 'F' => 5, 'G' => 7, 'A' => 9, 'B' => 11 }
if note == 'B#'
return 0
elsif note == 'Cb'
return 11
elsif note.length > 2
return nil
elsif note.include?('#')
hash[note.delete('#')] + 1
elsif note.include?('b')
hash[note.delete('b')] - 1
else
hash[note]
end
end
@DavidGoussev
Copy link
Copy Markdown
Author

javascript (uses modulo, anything less than modulo returns that number, any multiple of module returns 0)

function pitchClass(note) {
  if (!/^[A-G][#b]?$/.test(note)) return null

  var pitch = {C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11}
  var accidental = {'#': 1, 'b': -1}

  return (12 + pitch[note[0]] + (accidental[note[1]] || 0)) % 12
}

@DavidGoussev
Copy link
Copy Markdown
Author

alternate javascript

var pitchClass = function pitchClass(note) {

  if (!note.match(/^[A-G](#|b)?$/)) {
   return null;
  };

  notes = {
          'C': 0, 'C#': 1, 'Cb': 11, 
          'D': 2, 'D#': 3, 'Db': 1, 
          'E': 4, 'E#': 5, 'Eb': 3,
          'F': 5, 'F#': 6, 'Fb': 4,
          'G': 7, 'G#': 8, 'Gb': 6,
          'A': 9, 'A#': 10,'Ab': 8,
          'B': 11,'B#': 0, 'Bb': 10,     
          };

   return notes[note];

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment