JSFiddle - React, Tailwind, and code Playground

by Aaron Zhang

JavaScript

(function () {
    'use strict';
    var _REGEXP = /\{\s*(\d)\s*\}/g;
    String.prototype.compile = function () {
        var match, i;
        var toReplace = [];
        while ((match = _REGEXP.exec(this)) !== null) {
            toReplace.push(parseInt(match[1], 10));
        }
        toReplace.sort();
        if (toReplace.length) {
            if (toReplace[0] !== 0) {
                throw '{0} not found';
            }
            if (toReplace.length > 1) {
                for (i = 0; i < toReplace.length - 1; ++i) {
                    if (toReplace[i + 1] - toReplace[i] > 1) {
                        throw '{' + (toReplace[i] + 1) + '} not found';
                    }
                }
            }
            var max = toReplace[toReplace.length - 1];
            if (arguments.length != max + 1) {
                throw 'Not enough arguments to unpack';
            }
            var result = this;
            for (i = 0; i < arguments.length; ++i) {
                result = result.replace(new RegExp('\\{\\s*(' + i + ')\\s*\\}', 'g'), arguments[i]);
            }
            return result;
        }
        return this;
    };

    String.prototype.asParagraph = function () {
        return '<p>{0}</p>'.compile(this);
    };
    String.prototype.asHeading1 = function () {
        return '<h1>{0}</h1>'.compile(this);
    };

    console.log('hello,world'.asParagraph().asHeading1());
    console.log('Hello,{0} {0} {0}!'.compile('Aaron').asHeading1());
})();