Search code examples
regexnode.jsoptimizationcode-duplication

Reducing code duplication when parsing


I prefer to have as little duplicate code as possible within my code base and as such I am constantly looking for ways to reduce it.

I have however become a little stuck on the following case: Say I have a method that parses output from one program into an object to make it readable in another program.

My current approach is to use regex to scan the input to form a new object for output.

This creates a long list of if statements that look more or less the same with slight variations here and there. Is there a meaningful way to reduce the code duplication here or is this something I have to live with?

if ((match = block.match(/bssid=([A-Fa-f0-9:]{17})/))) {
    parsed.bssid = match[1].toLowerCase();
}

if ((match = block.match(/freq=([0-9]+)/))) {
    parsed.frequency = parseInt(match[1], 10);
}

if ((match = block.match(/mode=([^\s]+)/))) {
    parsed.mode = match[1];
}

if ((match = block.match(/key_mgmt=([^\s]+)/))) {
    parsed.key_mgmt = match[1].toLowerCase();
}

Solution

  • I'm guessing you want something like this:

    var parseConfig = {
        bssid: {
            expr: /bssid=([A-Fa-f0-9:]{17})/,
            handle: match => match[1].toLowerCase()
        },
        frequency: {
            expr: /freq=([0-9]+)/,
            handle: match => parseInt(match[1], 10)
        },
        mode: {
            expr: /mode=([^\s]+)/,
            handle: match => match[1]
        },
        key_mgmt: {
            expr: /key_mgmt=([^\s]+)/,
            handle: match => match[1].toLowerCase()
        }
    };
    
    function parse(block, cfg) {
        var parsed = {};
    
        Object.keys(cfg).forEach(key => {
            var item = cfg[key],
                match = block.match(item.expr);
    
            parsed[key] = match ? item.handle(match) : null;
        });
    
        return parsed;
    }