Skip to content
Advertisement

Wrapping around on a list when list index is out of range

I’m looking for some code improvement, or a pre-built version of what I’ve implemented myself as I think there might be, or should be, a cleaner way to achieve what I want.

I’m writing a piece of software to convert guitar tabs into classical notation, I need to convert the number on a tab to it’s corresponding note and it would be useful for building a list of each strings note from the starting string.

I have a list of notes, (a – g#) and a list of frets (0, 21).

Notes[fret] works fine for the first eleven notes but after that I obviously get an out of index error.

The code I have to get around this is here:

JavaScript

It works but it seems a little long, is there a better way to do this?

Advertisement

Answer

Use the % operator to produce a modulus:

JavaScript

Demo:

JavaScript

or in a loop:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement