Chris Barrett
Chris Barrett

Reputation: 601

Set value of object using function

I'm trying to set the value of a named object key SORT with a function, like this:

  statementPdfs.push ({
      NAME: currFile.getName(), 
      ID: currFile.getId(), 
      BLOB: currFile.getBlob(), 
      MIME_TYPE: currFile.getBlob().getContentType(),
      URL: currFile.getUrl(),
      SORT:  () => {
         let dates = currFile.getName().match(/(\w+)\s(\d+)/);
         return (dates[2]+
              (dateNums[dates[1].toUpperCase()] < 10
                  ? "0"+dateNums[dates[1].toUpperCase()]
                  : dateNums[dates[1].toUpperCase()]
               )
         );
      }
  });

...but the returned value for the SORT property is the function and not the return value. Sure there must be a simple answer, but it eludes me...

Upvotes: 0

Views: 206

Answers (1)

trincot
trincot

Reputation: 350841

You need what is called an immediately invoked function expression (IIFE): wrap the function in (.....)():

SORT: (() => {
    let dates = currFile.getName().match(/(\w+)\s(\d+)/);
    return (dates[2]+
          (dateNums[dates[1].toUpperCase()] < 10 
               ? "0"+dateNums[dates[1].toUpperCase()] 
               : dateNums[dates[1].toUpperCase()]
          )
    );
})()

Unrelated, but you can prepad with a zero using padStart:

SORT: (() => {
    let dates = currFile.getName().match(/(\w+)\s(\d+)/);
    return dates[2]+dateNums[dates[1].toUpperCase()].padStart(2, "0");
})()

Upvotes: 1

Related Questions