From 6a27a4058e34e186f685f1d6adf49fdb7c39e9e5 Mon Sep 17 00:00:00 2001 From: Jerry Jalava Date: Tue, 11 Dec 2007 20:00:28 +0200 Subject: [PATCH] Added pretty print helper --- js/ajatus.utils.js | 81 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) diff --git a/js/ajatus.utils.js b/js/ajatus.utils.js index faff75e..6394e60 100644 --- a/js/ajatus.utils.js +++ b/js/ajatus.utils.js @@ -41,6 +41,87 @@ return false; }; + + /** + * Renders pretty printed version from given value + * Original pretty_print function by Damien Katz + * Modified to work with Ajatus by Jerry Jalava + * @param {Mixed} val Value to render + * @param {Number} indent Current indent level (Default: 4) + * @param {String} linesep Line break to be used (Default: "\n") + * @param {Number} depth Current line depth (Default: 1) + * @returns Pretty printed value + * @type String + */ + $.ajatus.utils.pretty_print = function(val, indent, linesep, depth) { + var indent = typeof indent != 'undefined' ? indent : 4; + var linesep = typeof linesep != 'undefined' ? linesep : "\n"; + var depth = typeof depth != 'undefined' ? depth : 1; + + var propsep = linesep.length ? "," + linesep : ", "; + + var tab = []; + + for (var i = 0; i < indent * depth; i++) { + tab.push("") + }; + tab = tab.join(" "); + + switch (typeof val) { + case "boolean": + case "number": + case "string": + return $.ajatus.converter.toJSON(val); + case "object": + if (val === null) { + return "null" + } + if (val.constructor == Date) { + return $.ajatus.converter.toJSON(val); + } + + var buf = []; + if (val.constructor == Array) { + buf.push("["); + for (var index = 0; index < val.length; index++) { + buf.push(index > 0 ? propsep : linesep); + buf.push( + tab, $.ajatus.utils.pretty_print(val[index], indent, linesep, depth + 1) + ); + } + + if (index >= 0) { + buf.push(linesep, tab.substr(indent)) + }; + + buf.push("]"); + } else { + buf.push("{"); + var index = 0; + for (var key in val) { + if (!val.hasOwnProperty(key)) { + continue + }; + + buf.push(index > 0 ? propsep : linesep); + buf.push( + tab, $.ajatus.converter.toJSON(key), ": ", + $.ajatus.utils.pretty_print(val[key], indent, linesep, depth + 1) + ); + index++; + } + + if (index >= 0) { + buf.push(linesep, tab.substr(indent)) + }; + + buf.push("}"); + } + + return buf.join(""); + break; + } + }; $.ajatus.utils.array = { has_match: function(needles, haystack) { -- 2.11.4.GIT