JSFiddle - React, Tailwind, and code Playground

by CodeRenaissance

JavaScript

//returns an observable array of matching items.
ko.observableArray.fn.get = function (fnMatch) {
    var matchingItems = ko.observableArray([]);
    var updater = ko.computed({
        read: function () {
            var allItems = this();
            matchingItems([]);
            for (var i = 0; i < allItems.length; i++) {
                var current = allItems[i];
                if (fnMatch(current)) matchingItems.push(current);
            }
        },
        //deferEvaluation: true,
        owner: this
    });

    return matchingItems;
}

//returns the first matching item
ko.observableArray.fn.getFirst = function (fnMatch) {
    fnMatch = fnMatch || function () { return true; };
    return ko.computed({
        read: function () {
            var match, allItems = this();
            for (var i = 0; i < allItems.length; i++) {
                var current = allItems[i];
                if (fnMatch(current)) return current;
            }
        },
        //deferEvaluation: true,
        owner: this
    });
}

//returns an observable array of items base on items in the existing array
ko.observableArray.fn.map = function (fnMatch) {
    var mappedItems = ko.observableArray([]);
    mappedItems.__updater__ = ko.computed({
        read: function () {
            var allItems = this();
            mappedItems([]);
            for (var i = 0; i < allItems.length; i++) {
                var current = allItems[i],
                    result = fnMatch(current, i);
                if (result != undefined) mappedItems.push(result);
            }
        },
        //deferEvaluation: true,
        owner: this
    });

    return mappedItems;
}