Skip to content

Instantly share code, notes, and snippets.

@codeopensrc
Last active April 15, 2016 23:31
Show Gist options
  • Select an option

  • Save codeopensrc/e14d16c70bdd1e453fd7b82d6306b78e to your computer and use it in GitHub Desktop.

Select an option

Save codeopensrc/e14d16c70bdd1e453fd7b82d6306b78e to your computer and use it in GitHub Desktop.
Parameter type checking in JS

A helper parameter check for functions in JS

TODO: Turn into a .js file or npm module
TODO: Improve the single object version and demonstrate good usage with function parameters
TODO: Seperate arrays from objects

Supports: string, number, object, function, boolean

3rd iteration

  • This would/will be the npm module
 const typeChecker = function(req, args, functionName, verbose = false) {
        if(Array.isArray(args)) {
            let missing = req.map((types, ind) => {
                if(types.indexOf(typeof args[ind]) === -1) {
                    return functionName+": Argument "+(ind+1)+" should be: "+
                    types.join(" or ")+". Found: "+
                    ( !verbose ? typeof args[ind] :
                        ( typeof args[ind] === "object" ? 
                         JSON.stringify(args[ind]) : args[ind] )
                    )
                    +"\n";
                }
            }).join(" ").trim();
            if(missing.length) { throw new Error(missing); return false;}
            return true;
        }
    },
  • Usage
const typeChecker = require("typeChecker");

const insertDB = function(prop, value, garageVal, plan, callback) {
        let args = [ prop, value, garageVal, plan , callback];
        let req = [["string"], ["string", "number"], ["string"], ["object"], ["function"]];
        let typesAreValid = typeChecker(req, args, insertDB.name);
        if(!typesAreValid) { return; }
        /* Rest of your function */
}
  • Call
insertDB(false, {name: "obj"}, [], () => {});
  • Logs
Uncaught Error: insertDB: Argument 1 should be: string. Found: boolean
 insertDB: Argument 2 should be: string or number. Found: object
 insertDB: Argument 3 should be: string. Found: object
 insertDB: Argument 4 should be: object. Found: function
 insertDB: Argument 5 should be: function. Found: undefined
  • With verbose
//Changing
let typesAreValid = typeChecker(req, args, insertDB.name);

//To
let typesAreValid = typeChecker(req, args, insertDB.name, true);
  • Logs
Uncaught Error: insertDB: Argument 1 should be: string. Found: false
insertDB: Argument 2 should be: string or number. Found: {"name":"obj"}
insertDB: Argument 3 should be: string. Found: []
insertDB: Argument 4 should be: object. Found: function () {}
insertDB: Argument 5 should be: function. Found: undefined

Disregard below, needs revision

Below is the inital implementation with a single object parameter -- Needs revision to generalize and cut down on lines

Function should take in one Object argument "parameters" with each property being a parameter for the function

Each object in following array is the parameter being checked in the form of:
{ObjectPropertyNameToCheck: ["ArrayOfValueTypesAllowed", "function", "object", "etc"]

In this example, the NAME of the single parameter containing your arguments would be "parameters"
ex. let myFunction = (parameters) => { /* function body */ }

// Below would be placed at the top of your function
let required = [{prop: ["string"]}, {value: ["string", "number"]},
            {garageVal: ["string"]}, {plan: ["object"]}, {callback: ["function"]}];
            
let missing = required.map((param) => Object.keys(param).map((key) => {
    if(parameters[key] == undefined) { return `Missing parameter: ${key}\n`; }
    if(param[key].indexOf(typeof parameters[key]) === -1) {
        return `Parameter "${key}" should be a ${param[key].join(" or ")}. Found: ${typeof parameters[key]}\n`;
    }
})).filter((arr) => arr[0]).join(" ");
if(missing.length) { throw Error(`${missing}`); return; }
///// Above would be placed at the top of your function ////

// Now lets call our sample function
let sampleArgumentObject = { prop: "elevationimgs", value: () => {}, plan: {}, callback: {} }   
myFunction(sampleArgumentObject)   

//Would log   
Uncaught Error: Parameter "value" should be a string or number. Found: function   
 Missing parameter: garageVal   
 Parameter "callback" should be a function. Found: object   
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment