piotrkabacinski
8/20/2018 - 5:45 PM

Script Router

Script Router

class ScriptRouter {
    constructor(location){
        this.location = location || window.location.href.split(window.location.hostname)[1];
        this.forAll = ScriptRouter.forAll;
        this.routes = this.route;
    }
 
    route(paths, callback) {
        if (typeof callback !== 'function') {
            console.error('Callback is not a function');
            return this;
        }

        let pathsArray = [];

        if (paths instanceof RegExp){
            pathsArray.push(paths);
        } else if (Array.isArray(paths)) {
            pathsArray = [...paths].filter((path) => path instanceof RegExp);
        } else {
            console.error('\'paths\' argument is not a RegExp nor an Array');
            return this;
        }

        pathsArray.forEach((path) => {
            try {
                if (path.test(this.location)) callback(this.location, path, pathsArray);
            } catch (err) {
                console.error(err);
            }
        });

        return this;
    }

    static forAll(callback) {
        if (typeof callback !== 'function') {
            console.error('Callback is not a function');
            return this;
        }

        callback(this.location);

        return this;
    }
}

const routes = [
  /\/foo/, /* '/foo'and everytihing else */
  /\/foo\/param/, /* '/foo/param' and everything else */
  /\/foo\/param(.*$|\?)/, /* 'foo/param' + 'foo/param?...' ONLY */
  /\/foo(?!\/bar)/ /* everything '/foo' EXCEPT '/foo/bar' */
];

const scriptRouter1 = new ScriptRouter('/foo?test=foo#boo');

scriptRouter1.route(routes, (location, path) => {
    document.querySelector('body').innerText += `
     Test for \n ${location} \n
     passed successfully! (${path}) \n\n`;
});