From 069644a2e4b45c1127da7e4ffbe56a27680a826b Mon Sep 17 00:00:00 2001 From: Alan Plum Date: Fri, 1 Aug 2014 16:52:53 +0200 Subject: [PATCH] Added flatten method. --- js/common/bootstrap/module-internal.js | 72 ++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/js/common/bootstrap/module-internal.js b/js/common/bootstrap/module-internal.js index c32093c5ed..8aa8935e03 100644 --- a/js/common/bootstrap/module-internal.js +++ b/js/common/bootstrap/module-internal.js @@ -1341,6 +1341,78 @@ // --SECTION-- public printing functions // ----------------------------------------------------------------------------- +//////////////////////////////////////////////////////////////////////////////// +/// @brief flatten +//////////////////////////////////////////////////////////////////////////////// + + var hasOwnProperty = Function.prototype.call.bind(Object.prototype.hasOwnProperty); + + exports.flatten = function (obj, seen) { + 'use strict'; + + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + return obj; + } + + if (obj instanceof Date) { + return obj.toJSON(); + } + + if (!seen) { + seen = []; + } + + var result = Object.create(null), + src = obj, + keys, + i, + key, + val; + + if (typeof obj === 'function') { + result.__exec = String(obj); + } + + while (src) { + if ( + seen.indexOf(src) !== -1 + || (obj.constructor && src === obj.constructor.prototype) + ) { + break; + } + seen.push(src); + keys = Object.getOwnPropertyNames(src); + for (i = 0; i < keys.length; i++) { + key = keys[i]; + if (typeof src !== 'function' || ( + key !== 'arguments' && key !== 'caller' && key !== 'callee' + )) { + if (key.charAt(0) !== '_' && !hasOwnProperty(result, key)) { + val = obj[key]; + if (seen.indexOf(val) !== -1 && ( + typeof val === 'object' || typeof val === 'function' + )) { + result[key] = '[Circular]'; + } else { + result[key] = exports.flatten(val, seen); + } + } + } + } + src = Object.getPrototypeOf(src); + } + + if (obj.constructor && obj.constructor.name) { + if (obj instanceof Error && obj.name === Error.name) { + result.name = obj.constructor.name; + } else if (!hasOwnProperty(result, 'constructor')) { + result.constructor = {name: obj.constructor.name}; + } + } + + return result; + }; + //////////////////////////////////////////////////////////////////////////////// /// @brief inspect ////////////////////////////////////////////////////////////////////////////////