Manish Kumar
Manish's Blog

Manish's Blog

How I fixed a bug using javascript `call` method

How I fixed a bug using javascript `call` method

Manish Kumar's photo
Manish Kumar

Published on Oct 16, 2021

3 min read

Last week we discovered a bug in my workplace project. The error was similar to below

Cannot read properties of null (reading 'map')

Which is very simple to understand that somewhere in code we are calling map over a variable which is null .

I was like "okay this shouldn't take much time, I just need to find the source of error and fix it"

But the next minute I found the error was not coming from our source code but from 3rd Party library which we were using to download and parse SVG image.

So my next doubt was the SVG image we are downloading may be incorrect or corrupt, So I downloaded that image manually and it was totally valid image and we can view it in image viewer without any issue.

This makes me look deep in the source code of the library and found the function which was throwing error was doing a RegEx match on SVG image style content and doing map over all the matching values

let rules = styleContents.match(/[^{]*\{[\s\S]*?\}/g);
rules = rules.map(function(rule) { return rule.trim(); });

Now we found the problem here is rules value is getting null because match of function

By definition, match method will return an array of matching values or null if there is no match for the given RegEx

So at this point I know that our image has style which doesn't have any matching content to the RegEx but it is still a valid image and I can't control image content that is about to be downloaded and I can't change the library code, of course, I can open a PR but that will take some time before it gets merged.

To quickly fix this problem in our project by the time the library brings a fix, I decided to make a small change in the match method behavior, which was to return an empty array if there is no match found. Which is very easy to achieve using javascript's call method.

// keep reference of original match method
const originalMatch = String.prototype.match

// Overriding match function to return empty array if no match found
String.prototype.match = function (regExp) {
  return originalMatch.call(this, regExp) || []
}

loadSVGFromURL(url)
// restore original match after our usage 
String.prototype.match = originalMatch

As you can see we just modified the match method to fix a problem temporarily as the real fix will be in the library to handle this case and then we don't have to handle this case in our code.

But as you can see, this method can be very powerful and could help you to change the behavior of code which may not be your control as well

That's it for this post. Thanks for reading it

 
Share this