3

I have a Tampermonkey script that adds some information to a browser-based game. I use a simple piece of code to add thousand separators to numbers based on the players' locales:

function nThousand(x) {
    return x.toLocaleString();
}

This function is used in a lot of the code, for example:

$("#CustomStats" + stat).html(
"<b>" + texts[lang].stat_points_need + ":</b> " + nThousand(remainingPoints) + "<br />" +
"<b>" + texts[lang].money_need + ": </b>" + nThousand(remainingMoney) + "<br />" +
"<b>" + texts[lang].money_spent + ": </b>" + nThousand(currentMoney) + "<br /><br />" +
"<b>" + texts[lang].bought_points + ": </b>" + nThousand(boughtPoints) + "<br />" +
"<b>" + texts[lang].equipment_points + ": </b>" + nThousand(itemPoints) + "<br />" +
"<b>" + texts[lang].points_from_level + ": </b>" + nThousand(skillPoints) + "<br />"
);

This has worked perfectly for ages, but for some reason on one particular platform the game runs on, the script now refuses to load and gives the following error message:

Cannot read property 'toLocaleString' of undefined

I've gone back several dozen versions to make sure it wasn't something I added or changed recently, and I honestly don't even know where I would start solving this issue. The function only runs when there is a value to be localised and it's only on one specific platform the game runs on that it does this.

My question: what could be causing this and how would I go about solving this problem?

Sluimerstand
  • 43
  • 1
  • 1
  • 4
  • 2
    What platform is the problem? Which other platforms work? Can you identify at exactly which call the value is null? You can either use a debugger to do this, or just add a check for null parameter in the function and console.trace the offending code. – Putr Jun 12 '19 at 17:59
  • 1
    Using console.trace helped me figure out the evildoers! It turns out it didn't have anything to do with the platform, but circumstances where certain items are missing in the game and it tries to pull non-existent numbers. That it happened on the same platform was a coincidence, as well as the fact that it's never occurred before now. – Sluimerstand Jun 12 '19 at 18:30

1 Answers1

9

The problem isn't with toLocaleString, the issue is that somewhere you're passing undefined to your function. You'll need to figure out why that's happening through debugging. It could also be a good idea to add a guard to your function that returns an empty string if it's passed a non-string value.

frodo2975
  • 10,340
  • 3
  • 34
  • 41
  • 1
    With the help of Putr's comment I figured out it was indeed trying to pull non-existent numbers which crashed the script. The fact that it never happened before and did now under similar circumstances was an enormous coincidence. I've managed to fix it by indeed making it so that if what it's trying to localise isn't a number, it just turns it to 0. Thank you! – Sluimerstand Jun 12 '19 at 18:35