Return to Snippet

Revision: 50390
at August 19, 2011 10:28 by mejamiewilson


Initial Code
String.prototype.supplant = function (o) {
            return this.replace(/{([^{}]*)}/g,
                function (a, b) {

                    //Evaluators
                    var ev = {
                        _Object: /([^\[\]]*)\[([^\[\]]*)\]/g,
                        _Equation: /([^\=\!\?]*)([\=\!\?]*)([^\?\:]*)([\?\:]*)([^\?\:]*)([\?\:]*)([^\?\:]*)/g
                    };

                    //Test if it's an equation - A==B?this:that
                    var _1 = b.indexOf('?');

                    if (_1 !== -1) {

                        var ci = null;
                        b.replace(ev._Equation, function (x, y, z, xx, yy, zz, xxx, yyy, zzz) {
                            //Seems to fire twice, yet to work that out
                            if (x == "") return;

                            //A==B?this:that would create
                            //equation  = {
                            //    l: "A",      left
                            //    r: "B",      right
                            //    s: "this",   success
                            //    f: "that"    fail
                            //}
                            var equation = {
                                l: y.replace(ev._Object, function (x, y, z) {
                                    return o[y][z]
                                }) || y,
                                r: (z != '?') ? xx : null,
                                s: (z != '?') ? zz : xx,
                                f: (z != '?') ? yyy : zz
                            },
                            evald = null;

                            if (z != '?') {
                                evald = eval(equation.l + z + equation.r);
                            } else {
                                evald = o[equation.l];
                            }

                            if (evald == true)
                                ci = equation.s;
                            if (evald == false)
                                ci = equation.f;

                        });
                        return ci;

                    } else {
                        var r = o[b];
                        return typeof r === 'string' ? r : a;
                    }

                }
            );
        };

Initial URL

                                

Initial Description

                                

Initial Title
Supplanting Data with Equations

Initial Tags
javascript, replace

Initial Language
JavaScript