replacer.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. var test = require('tape');
  2. var stringify = require('../');
  3. test('replace root', function (t) {
  4. t.plan(1);
  5. var obj = { a: 1, b: 2, c: false };
  6. var replacer = function(key, value) { return 'one'; };
  7. t.equal(stringify(obj, { replacer: replacer }), '"one"');
  8. });
  9. test('replace numbers', function (t) {
  10. t.plan(1);
  11. var obj = { a: 1, b: 2, c: false };
  12. var replacer = function(key, value) {
  13. if(value === 1) return 'one';
  14. if(value === 2) return 'two';
  15. return value;
  16. };
  17. t.equal(stringify(obj, { replacer: replacer }), '{"a":"one","b":"two","c":false}');
  18. });
  19. test('replace with object', function (t) {
  20. t.plan(1);
  21. var obj = { a: 1, b: 2, c: false };
  22. var replacer = function(key, value) {
  23. if(key === 'b') return { d: 1 };
  24. if(value === 1) return 'one';
  25. return value;
  26. };
  27. t.equal(stringify(obj, { replacer: replacer }), '{"a":"one","b":{"d":"one"},"c":false}');
  28. });
  29. test('replace with undefined', function (t) {
  30. t.plan(1);
  31. var obj = { a: 1, b: 2, c: false };
  32. var replacer = function(key, value) {
  33. if(value === false) return;
  34. return value;
  35. };
  36. t.equal(stringify(obj, { replacer: replacer }), '{"a":1,"b":2}');
  37. });
  38. test('replace with array', function (t) {
  39. t.plan(1);
  40. var obj = { a: 1, b: 2, c: false };
  41. var replacer = function(key, value) {
  42. if(key === 'b') return ['one', 'two'];
  43. return value;
  44. };
  45. t.equal(stringify(obj, { replacer: replacer }), '{"a":1,"b":["one","two"],"c":false}');
  46. });
  47. test('replace array item', function (t) {
  48. t.plan(1);
  49. var obj = { a: 1, b: 2, c: [1,2] };
  50. var replacer = function(key, value) {
  51. if(value === 1) return 'one';
  52. if(value === 2) return 'two';
  53. return value;
  54. };
  55. t.equal(stringify(obj, { replacer: replacer }), '{"a":"one","b":"two","c":["one","two"]}');
  56. });