Ambrosius Topor

Notiz — 2017-09-08

Extract filter function

Situation before

function filter() {

    return this.links.filter(function(link) {

        var doesMatch = false;

        // All the logic for expression filter
        // ..

        // All the logic for keywords filter
        // ..

        return doesMatch;
    });
}

Situation after

The filter function is the cleaned up and only invokes other functions to perform the actual matching. This way it is easy to extend and implement additional matching functions.

function filter() {

    return this.links.filter(function(link) {

        return (
            checkMatchExpression(link)
        &&  checkMatchKeywords(link)
        );
    });
}

Extracted functions which check for expression/keywords match:

function checkMatchExpression(link) {
    // ..
}

function checkMatchKeywords(link) {
    // ..
}

Clearify usage of outer variable

As the functions are using variables from the outer scope, we could also create a IIFE to make this more obvious:

const checkMatchExpression = (function(expression) {
    return function(link) {
        // Use 'expression' variable to perform check
        // ..
    };
})(expression);

In PHP, we would make use of the use language construct:

function checkMatchExpression($link) use ($expression) {
    // Use '$expression' variable to perform check
}

Multiple arrays filter implementation

Filter an item with keywords by an array of given keywords:

var link = {
    keywords: ['CSS', 'Material Design']
};
var filter_keywords = ['CSS', 'UX'];
if (link.keywords && filter_keywords.length > 0) {
    doesMatch = filter_keywords.every(function(keyword) {

        return link.keywords.includes(keyword);
    });
}

Comments

There are no comments yet.

Thanks for your contribution!
Your comment will be visible once it has been approved.

An error occured—please try again.

Add Comment