utils.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. 'use strict';
  2. var test = require('tape');
  3. var utils = require('../lib/utils');
  4. test('merge()', function (t) {
  5. t.deepEqual(utils.merge(null, true), [null, true], 'merges true into null');
  6. t.deepEqual(utils.merge(null, [42]), [null, 42], 'merges null into an array');
  7. t.deepEqual(utils.merge({ a: 'b' }, { a: 'c' }), { a: ['b', 'c'] }, 'merges two objects with the same key');
  8. var oneMerged = utils.merge({ foo: 'bar' }, { foo: { first: '123' } });
  9. t.deepEqual(oneMerged, { foo: ['bar', { first: '123' }] }, 'merges a standalone and an object into an array');
  10. var twoMerged = utils.merge({ foo: ['bar', { first: '123' }] }, { foo: { second: '456' } });
  11. t.deepEqual(twoMerged, { foo: { 0: 'bar', 1: { first: '123' }, second: '456' } }, 'merges a standalone and two objects into an array');
  12. var sandwiched = utils.merge({ foo: ['bar', { first: '123', second: '456' }] }, { foo: 'baz' });
  13. t.deepEqual(sandwiched, { foo: ['bar', { first: '123', second: '456' }, 'baz'] }, 'merges an object sandwiched by two standalones into an array');
  14. var nestedArrays = utils.merge({ foo: ['baz'] }, { foo: ['bar', 'xyzzy'] });
  15. t.deepEqual(nestedArrays, { foo: ['baz', 'bar', 'xyzzy'] });
  16. var noOptionsNonObjectSource = utils.merge({ foo: 'baz' }, 'bar');
  17. t.deepEqual(noOptionsNonObjectSource, { foo: 'baz', bar: true });
  18. t.test(
  19. 'avoids invoking array setters unnecessarily',
  20. { skip: typeof Object.defineProperty !== 'function' },
  21. function (st) {
  22. var setCount = 0;
  23. var getCount = 0;
  24. var observed = [];
  25. Object.defineProperty(observed, 0, {
  26. get: function () {
  27. getCount += 1;
  28. return { bar: 'baz' };
  29. },
  30. set: function () { setCount += 1; }
  31. });
  32. utils.merge(observed, [null]);
  33. st.equal(setCount, 0);
  34. st.equal(getCount, 1);
  35. observed[0] = observed[0]; // eslint-disable-line no-self-assign
  36. st.equal(setCount, 1);
  37. st.equal(getCount, 2);
  38. st.end();
  39. }
  40. );
  41. t.end();
  42. });
  43. test('assign()', function (t) {
  44. var target = { a: 1, b: 2 };
  45. var source = { b: 3, c: 4 };
  46. var result = utils.assign(target, source);
  47. t.equal(result, target, 'returns the target');
  48. t.deepEqual(target, { a: 1, b: 3, c: 4 }, 'target and source are merged');
  49. t.deepEqual(source, { b: 3, c: 4 }, 'source is untouched');
  50. t.end();
  51. });