index.js 700 B

123456789101112131415161718192021222324252627282930
  1. 'use strict';
  2. var isObject = require('is-extendable');
  3. var union = require('arr-union');
  4. var get = require('get-value');
  5. var set = require('set-value');
  6. module.exports = function unionValue(obj, prop, value) {
  7. if (!isObject(obj)) {
  8. throw new TypeError('union-value expects the first argument to be an object.');
  9. }
  10. if (typeof prop !== 'string') {
  11. throw new TypeError('union-value expects `prop` to be a string.');
  12. }
  13. var arr = arrayify(get(obj, prop));
  14. set(obj, prop, union(arr, arrayify(value)));
  15. return obj;
  16. };
  17. function arrayify(val) {
  18. if (val === null || typeof val === 'undefined') {
  19. return [];
  20. }
  21. if (Array.isArray(val)) {
  22. return val;
  23. }
  24. return [val];
  25. }