0

I've found a really nice pice of code here https://stackoverflow.com/a/45979883/9138729

I have a hard time to make it work in my C# form application

function transposeChord(chord, amount) {
    var scale = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
    var normalizeMap = {
        "Cb": "B",
        "Db": "C#",
        "Eb": "D#",
        "Fb": "E",
        "Gb": "F#",
        "Ab": "G#",
        "Bb": "A#",
        "E#": "F",
        "B#": "C"
    };
    return chord.replace(/[CDEFGAB](b|#)?/g, function(match) {
        matchIndex = normalizeMap[match] ? normalizeMap[match] : match;
        var i = (scale.indexOf(matchIndex) + amount) % scale.length;
        if (i < 0) {
            return scale[i + scale.length];
        } else {
            return scale[i];
        }
        }
    );
}
  1. The normalizeMap var has 2 options on each line (string[,]?).
  2. The replace function in C# doesn't work with the "(b|#)?/g" part (i think)
  3. The function(match) is present in C#?

Or do I need to take a whole new approach to fit C# logic?

mason
  • 31,774
  • 10
  • 77
  • 121
Sander
  • 37
  • 5
  • 3
    C# has all similar constructs for you to be able to convert this code. `normalizeMap` will be `Dictionary`. Replace will be `new Regex("[CDEFGAB](b|#)?").Replace(chord, match => { ... function here ...})` – Evk Dec 25 '17 at 12:37
  • But if you still has troubles with converting with information above - feel free to ask. – Evk Dec 25 '17 at 14:47
  • Thanks for the help, i've solved the code (for anyone want to use it, i've paste it in above) – Sander Dec 27 '17 at 16:31

1 Answers1

0

The code is solved:

        private string transposeChord(string ChordRegel, int amount)
    {
        string[] scale = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
        var normalizeMap = new Dictionary<string, string>() { { "Cb", "B" }, { "Db", "C#" }, { "Eb", "D#" }, { "Fb", "E" }, { "Gb", "F#" }, { "Ab", "G#" }, { "Bb", "A#" }, { "E#", "F" }, { "B#", "C" } };
        return new Regex("[CDEFGAB](b|#)?").Replace(ChordRegel, match =>
        {
        int i = (Array.IndexOf(scale, normalizeMap.ContainsKey(match.Value) ? normalizeMap[match.Value] : match.Value) + amount) % scale.Length;
            return scale[i < 0 ? i + scale.Length : i];
        });
    }
Sander
  • 37
  • 5