Search code examples
javascriptadobe-indesignextendscript

Calculation result wrong in Extendscript Javascript


I'm writing a InDesign Script and I'm using moments.js for calculating dates.

When I'm using the date-format "Do", which should return fore example "1st, 2nd, 3rd, 4th...", but the calculation the function does, returns a wrong result and the result is this:

1rd 2rd 3rd 4th 5th 6th 7th 8th 9th 10rd 11rd 12rd 13rd 14rd 15rd 16rd 17rd 18rd 19rd 20th 21rd 22rd 23rd 24th 25th 26th 27th 28th 29th 30th 31rd

This is the function:

function returnOrdinal(number) {
  var b = number % 10,
  output = (parseInt(number % 100 / 10) === 1) ? 'th' :
   (b === 1) ? 'st' :
   (b === 2) ? 'nd' :
   (b === 3) ? 'rd' : 'th';
  return number + output;
}

I created a JSFiddle that uses the same function and it returns the correct results.

So is this a known issue in Extendscript? Do you know any other way to return the ordinals? Any workaround?

Thanks in advance


Solution

  • It looks like chained ternary operators are not supported by ExtendScript.As far as I remember, it is ECMA 3. Another option working in InDesign - just use if else or switch

    function returnOrdinal(number) {
        var b = number % 10;
        var output;
        if (parseInt(number % 100 / 10) === 1) {
            output = 'th';
        } else {
            switch (number) {
                case 1:
                    output = 'st';
                    break;
                case 2:
                    output = 'nd';
                    break;
                case 3:
                    output = 'rd';
                    break;
                default:
                    output = 'th';
            }
        }
        return number + output;
    }