DEV Community

Vani Shivanand
Vani Shivanand

Posted on • Updated on

Why did I rewrite Momentjs format method using RegExp?

The popular library momentjs is widely used to any date related calculations. For 10 lines of utility code, we end up using 18kb or 72.5kb gz format minified momentjs file. It's not just download time, it also about the memory that it consumes to operate.

Here is an effort to replace that momentjs format code with the RegExp functions with a very few lines.

If you wish to learn about regEx, visit https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

Format date in RegExp

var months = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'];

//listing all the possible keys to regular exp
Date.regExMap = {
  MMM: new RegExp("\\" + months.join("|"), "gi"),
  dddd: /\b\w+/,
  dd: /\d{2}/,
  YYYY: /\d{4}/,
  hh: /\d{2}(?=:\d{2}:\d{2})/,
  mm: /\d{2}(?=:\d{2}\s)/,
  ss: /\d{2}(?=.[A-Z]{3})/
};

//creating regular exp to query the string
Date.regExKeys = new RegExp("\\"+Object.keys(Date.regExMap).join("|"),"gi");

//adding it to Date default object & having an optional date param
Date.prototype.tinyDateFormat = function(str,date) {
  //validations
  if(str === null || str === undefined || str.length <= 0) throw "invalid string";
  if(date === undefined || date === null) date = this;
  if(!(date instanceof Date)) throw "invalid date";

  let newStr = str;
  //extracting the matchable words & looping through
  str.match(Date.regExKeys).forEach((regEx) => {
    if (Date.regExMap[regEx]) {
      newStr = newStr.replace(regEx,date.toString().match(Date.regExMap[regEx]));
      //arr.push(this.toString().match(Date.regExMap[regEx]));
     }
  });
  return newStr;
};

Usage

// var date1 = new Date().tinyDateFormat("MMM dd YYYY, hh:mm:ss");
var date = new Date().tinyDateFormat("I am coding on MMM dd YYYY at hh hours & mm minutes");
document.body.innerHTML = date;

Why did I write this?

The companies do interview the people for library/framework knowledge. But if the preference of interview changes to basics or core concepts, everyone would start to get more stability and strength in basics or core. This does helps in the application quality.

For this momentjs format method, it takes the same amount of time to learn the syntax by library as it takes to write the utility using RegExp and get the job done.

The above example may not be covering all the use-cases of momentjs format function. It's not to copy & use it as a small library. But to learn it and to write it again.

In other than date format cases also, try to take time and write your utility functions on your own. Anyway we do spend time on algorithms. The same time can be spent in writing such a utility functions.

It is not considered as re-inventing the wheel but it can be marked as "efficient in writing the code using core concepts for the sake of efficient app".

Heard of tip of ice-berg problem? For a few lines from library, we end up using the entire bundle.

To be efficient may be more beneficial than being knowledgeable. Thanks for reading!

Top comments (5)

Collapse
 
ryands17 profile image
Ryan Dsouza

Great snippet! It's true that we import an entire library just for a single method, and that causes an extra dependency to manage.

Collapse
 
svaani profile image
Vani Shivanand

Yeah, and that dependency gets downloaded on every customer's browser! Thank you for the comment!

Collapse
 
shriji profile image
Shriji

Looks great!

Collapse
 
svaani profile image
Vani Shivanand

Thank you for reading and for the comment!

Collapse
 
neel1985 profile image
neel1985

Hi Vaani, I have requirement that involves overriding the defaut monthsShortRegex of moment.js. Can you lease share, how can i do that?