loading...

Why did I rewrite Momentjs format method using RegExp?

svaani profile image Vani Shivanand Updated on ・2 min read

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!

Posted on by:

svaani profile

Vani Shivanand

@svaani

UI Developer - learning goes on forever

Discussion

markdown guide
 

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". Yes it's the right point. Almost all beginners go through libraries for the sake of easy invention but they end up consuming memory resources, managing issues and poor performance. Sometimes those libraries are so big that users has to wait for some moments that gives a bad impression.

I also believe that we shouldn't depend on libraries when we really don't need them. It simply turns out as a glimpse of creativity as well as a new experience. Agreed with @ryands17

 
 

Thank you for reading and for the comment!

 

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

 

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