Last active
December 19, 2015 20:19
-
-
Save digitalicarus/6012622 to your computer and use it in GitHub Desktop.
recursively execute on an organized nested object where sub objects are identified by '__value' member in a 'relationships' array. Also filter, map and persist opts. TODO: make relationships member a generic option as well as the __value member.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| doSomethingGood() | |
| .then(function (tree) { | |
| // filter and print members with indentation, par example | |
| return execObj(tree, { | |
| exec: function (obj, opts) { | |
| var attrs = obj.someAttrArray; | |
| if (attrs) { | |
| attrs = attrs.filter(function (item) { | |
| return attr.type.match(/wicked|bitchin/i); | |
| }); | |
| } | |
| console.log(opts.indent + obj.title + | |
| // print the first cool attr, also indented | |
| ((attrs && attrs.length > 0) ? '\n' + opts.indent + attrs[0].value : '') | |
| ); | |
| }, | |
| filter: function (obj) { | |
| return obj.formaltype.match(/usiness|ervice/); | |
| }, | |
| augOpts: function (opts) { | |
| var newOpts = aug({}, opts); | |
| newOpts.indent += " "; | |
| return newOpts; | |
| }, | |
| indent: '' | |
| }); | |
| }) | |
| .catch(function (error) { | |
| console.log("In my software there is problem ", error); | |
| }) | |
| .done() | |
| ; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function execObj (tree, opts) { | |
| var i = 0 | |
| , rels = tree.relationships || [] | |
| , deferred = Q.defer() | |
| , childInFlight = 0 | |
| ; | |
| if (opts.filter && typeof opts.filter === 'function') { | |
| rels = rels.filter(function (item) { | |
| return item.__value && typeof item.__value === 'object'; | |
| }); | |
| rels = rels.filter(opts.filter); | |
| } | |
| if (opts.map && typeof opts.map === 'function') { | |
| rels = rels.map(opts.map); | |
| } | |
| opts.exec(tree, opts); | |
| if (opts.augOpts) { | |
| opts = opts.augOpts(opts); | |
| } | |
| if (rels.length < 1) { | |
| setTimeout(function () {deferred.resolve(tree); }, 0); | |
| return deferred.promise; | |
| } | |
| for (; i < rels.length; i++) { | |
| execObj(rels[i].__value, opts) | |
| .then(function () { | |
| childInFlight --; | |
| if (childInFlight === 0) { | |
| deferred.resolve(tree); | |
| } | |
| }); | |
| childInFlight ++; | |
| } | |
| return deferred.promise; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment