JSFiddle - React, Tailwind, and code Playground

by kmturley

JavaScript

(function(){
    var module = {
        name: 'IndexCompress',
        pack: function(items, type) {
            if (items) {
                // create a new object and turn data into set of keys and their references
                var data = { k: [], d: [] };
                if (type === 'string') { items = items.split(' '); }
                data.d = this.process(items, data.k, this.set, type);
                return data;
            }
        },
        unpack: function(items, type) {
            if (items) {
                // grab the references and return the key values
                var data = this.process(items.d, items.k, this.get, type);
                if (type == 'string') { return data.join(' '); }
                else { return data; }
            }
        },
        process: function(items, keys, func, type) {
            // loop through a list and run a function on its keys and values
            var list = [],
                obj = {}

            for (var i=0; i<items.length; ++i) {
                obj = {};
                if (typeof items[i] === 'object') {
                    for (var item in items[i]) {
                        obj[func(item, keys)] = func(items[i][item], keys);
                    }
                }
                else {
                    obj = func(items[i], keys);
                }
                list.push(obj);
            }
            return list;
        },
        set: function(item, items) {
            // set a key and return its index
            for (var i=0; i<items.length; ++i) {
                if (item == items[i]) { return i; }
            }
            items.push(item);
            return items.length-1;
        },
        get: function(item, items) {
            // get a key value by its index
            return items[parseInt(item, 10)];
        }
    }
    window[module.name] = module;
})();

// test data

var json = [
    {
        surname: 'Jones',
        age: 15,
        gender: 'Male',
     ...