JS custom compiler fork

http://stackoverflow.com/questions/30113417/javascript-determine-unknown-array-length-and-map-dynamically

by sujit km

JavaScript

var apiObj = {
    items: [{
        name: "Hammer",
        skus: [{
            num: "12345qwert"
        }]
    }, {
        name: "Bike",
        skus: [{
            num: "asdfghhj"
        }, {
            num: "zxcvbn"
        }]
    }, {
        name: "Fork",
        skus: [{
            num: "0987dfgh"
        }]
    }]
};

var myObj = { //Previously has values
    storeName: "",
    items: [{
        uniqueName: ""
    }],
    outputModel: {
        items: [{
            name: "Hammer"
        }]
    }
};

/** Also works with this **
var myPath = "outputModel.items[].uniqueName";
var apiPath = "items[].name";
*/
var myPath = "outputModel.items[].sku";
var apiPath = "items[].skus[].num";

function make_accessor(program) {

    return function (obj, callback) {
        (function do_segment(obj, segments) {
            var start = segments.shift() // Get first segment
            var pieces = start.match(/(\w+)(\[\])?/); // Get name and [] pieces
            var property = pieces[1];
            var isArray = pieces[2]; // [] on end
            obj = obj[property]; // drill down

            if (!segments.length) { // last segment; callback
                if (isArray) {
                    return obj.forEach(callback);
                } else {
                    return callback(obj);
                }
            } else { // more segments; recurse
                if (isArray) { // array--loop over elts
                    obj.forEach(function (elt) {
                        do_segment(elt, segments.slice());
                    });
                } else {
                    do_segment(obj, segments.slice()); // scalar--continue
                }
            }
        })(obj, program.split('.'));
    };
}

function make_inserter(program) {

    return function (obj, value) {
        (function do_segment(obj, segments) {
            var start = segments.shift() // Get first segment
            var pieces = start.match(/(\w+)(\[\])?/); // Get name and []...