JsonTransformer.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. var Class = require('./Class');
  2. var safeSet = require('./safeSet');
  3. var safeGet = require('./safeGet');
  4. var map = require('./map');
  5. var filter = require('./filter');
  6. var isFn = require('./isFn');
  7. var safeDel = require('./safeDel');
  8. var toArr = require('./toArr');
  9. var each = require('./each');
  10. exports = Class({
  11. className: 'JsonTransformer',
  12. initialize: function(data) {
  13. this._data = data || {};
  14. },
  15. set: function(key, val) {
  16. if (arguments.length === 1) {
  17. this._data = key;
  18. return this;
  19. }
  20. safeSet(this._data, key, val);
  21. return this;
  22. },
  23. get: function(key) {
  24. if (key == null) return this._data;
  25. return safeGet(this._data, key);
  26. },
  27. map: function(from, to, fn) {
  28. if (isFn(from)) return this.set(map(this._data, from, this));
  29. if (isFn(to)) {
  30. fn = to;
  31. to = from;
  32. }
  33. return this.set(to, map(this.get(from), fn, this));
  34. },
  35. filter: function(from, to, fn) {
  36. if (isFn(from)) return this.set(filter(this._data, from, this));
  37. if (isFn(to)) {
  38. fn = to;
  39. to = from;
  40. }
  41. return this.set(to, filter(this.get(from), fn, this));
  42. },
  43. remove: function(keys) {
  44. keys = toArr(keys);
  45. var data = this._data;
  46. each(keys, function(key) {
  47. safeDel(data, key);
  48. });
  49. return this;
  50. },
  51. compute: function(from, to, fn) {
  52. if (isFn(from)) return this.set(from.call(this, this._data));
  53. if (isFn(to)) return this.set(from, to.call(this, this.get(from)));
  54. from = map(
  55. toArr(from),
  56. function(key) {
  57. return safeGet(this._data, key);
  58. },
  59. this
  60. );
  61. return this.set(to, fn.apply(this, from));
  62. },
  63. toString: function() {
  64. return JSON.stringify(this._data);
  65. }
  66. });
  67. module.exports = exports;