Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript supplant

I recently came across the Javascript supplant function by crockford. The function goes like this -

if (!String.prototype.supplant) {
    String.prototype.supplant = function (o) {
        return this.replace(/{([^{}]*)}/g,
            function (a, b) {
                var r = o[b];
                return typeof r === 'string' || typeof r === 'number' ? r : a;
            }
        );
    };
}

I need to understand the mechanics of this function and how exactly is this thing working. I have come across many explanations but all tend to make things complex by introducing technicalities that make things worse.

Trying to look for

1.The regex explanation here

2.the logic for the function(a,b) code block

3.the use of that return statement

like image 461
heysupratim Avatar asked Apr 09 '26 02:04

heysupratim


1 Answers

as Tomalak said, spaces in regex are not trivial

  1. the regex basically matchs something like this: { ... }. the [^{}] means the content in the curly braces can be anything but curly nraces. The * means the length of the content can be zero or any number. The part inside the parentheses is Parenthesized Substring Matches

  2. The function passes a dictionary in as o, and performs a replace using the regex above. Whenever there is a match, the callback function of the replace will be invoked. a is the whole matched part, and b is the submatch part corresponding to the "Parenthesized Substring Matches". The callback function looks for b as the key in the dictionary, and return the corresponding value

  3. the return statement means if the type of r is string or number, then return r; otherwise return a

You can checkout the example code provided by Jared Farrish, which shows how the match and replace work very clearly.

like image 126
xvatar Avatar answered Apr 11 '26 16:04

xvatar