Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 1.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. var hasProp = Object.prototype.hasOwnProperty;
  2. function throwsMessage(err) {
  3. return '[Throws: ' + (err ? err.message : '?') + ']';
  4. }
  5. function safeGetValueFromPropertyOnObject(obj, property) {
  6. if (hasProp.call(obj, property)) {
  7. try {
  8. return obj[property];
  9. }
  10. catch (err) {
  11. return throwsMessage(err);
  12. }
  13. }
  14. return obj[property];
  15. }
  16. function ensureProperties(obj) {
  17. var seen = [ ]; // store references to objects we have seen before
  18. function visit(obj) {
  19. if (obj === null || typeof obj !== 'object') {
  20. return obj;
  21. }
  22. if (seen.indexOf(obj) !== -1) {
  23. return '[Circular]';
  24. }
  25. seen.push(obj);
  26. if (typeof obj.toJSON === 'function') {
  27. try {
  28. var fResult = visit(obj.toJSON());
  29. seen.pop();
  30. return fResult;
  31. } catch(err) {
  32. return throwsMessage(err);
  33. }
  34. }
  35. if (Array.isArray(obj)) {
  36. var aResult = obj.map(visit);
  37. seen.pop();
  38. return aResult;
  39. }
  40. var result = Object.keys(obj).reduce(function(result, prop) {
  41. // prevent faulty defined getter properties
  42. result[prop] = visit(safeGetValueFromPropertyOnObject(obj, prop));
  43. return result;
  44. }, {});
  45. seen.pop();
  46. return result;
  47. };
  48. return visit(obj);
  49. }
  50. module.exports = function(data, replacer, space) {
  51. return JSON.stringify(ensureProperties(data), replacer, space);
  52. }
  53. module.exports.ensureProperties = ensureProperties;