diff options
| author | cyanos3 <[email protected]> | 2013-11-05 07:09:59 -0700 |
|---|---|---|
| committer | cyanos3 <[email protected]> | 2013-11-05 07:09:59 -0700 |
| commit | be54187b963d527348f6142f04e7d84c54af6ef2 (patch) | |
| tree | 83197e539e8c059cb3c7b26831ea7d3d8a853cf3 /lib | |
| parent | 1bd1d73d29222c4e2f52d63a4282345b63a324df (diff) | |
| download | faker-be54187b963d527348f6142f04e7d84c54af6ef2.tar.xz faker-be54187b963d527348f6142f04e7d84c54af6ef2.zip | |
Add tree:
createTree(depth, width, obj) where
- depth is the distance from the root to the farthest node
- width is the number of children to add to each node
- each property/value pair in obj contains a value that will be evaluated to get the final result. The property that contains the array of child nodes should have the value of "__RECURSE__"
Diffstat (limited to 'lib')
| -rw-r--r-- | lib/tree.js | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/lib/tree.js b/lib/tree.js new file mode 100644 index 00000000..c35851cf --- /dev/null +++ b/lib/tree.js @@ -0,0 +1,67 @@ +var Faker = require('../index'); + +var clone = function clone(obj) { + if (obj == null || typeof(obj) != 'object') + return obj; + + var temp = obj.constructor(); // changed + + for (var key in obj) { + temp[key] = clone(obj[key]); + } + return temp; +}; + + +var createTree = function (depth, width, obj) { + + if (!obj) { + throw { + name: "ObjectError", + message: "there needs to be an object passed in", + toString: function () { + return this.name + ": " + this.message + } + }; + } + + if (width <= 0) { + throw { + name: "TreeParamError", + message: "width must be greater than zero", + toString: function () { + return this.name + ": " + this.message + } + }; + } + + var newObj = clone(obj); + + for (var prop in newObj) { + if (newObj.hasOwnProperty(prop)) { + var value = null; + if (newObj[prop] !== "__RECURSE__") { + value = eval(newObj[prop]); + } + else { + if (depth !== 0) { + value = []; + for (var i = 0; i < width; i++) { + value.push(createTree(depth - 1, width, obj)); + } + } + } + + newObj[prop] = value; + } + } + + return newObj; +}; + +var tree = { + createTree: createTree +}; + + +module.exports = tree; |
