pluck.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. "use strict";
  2. var map_1 = require('./map');
  3. /**
  4. * Maps each source value (an object) to its specified nested property.
  5. *
  6. * <span class="informal">Like {@link map}, but meant only for picking one of
  7. * the nested properties of every emitted object.</span>
  8. *
  9. * <img src="./img/pluck.png" width="100%">
  10. *
  11. * Given a list of strings describing a path to an object property, retrieves
  12. * the value of a specified nested property from all values in the source
  13. * Observable. If a property can't be resolved, it will return `undefined` for
  14. * that value.
  15. *
  16. * @example <caption>Map every click to the tagName of the clicked target element</caption>
  17. * var clicks = Rx.Observable.fromEvent(document, 'click');
  18. * var tagNames = clicks.pluck('target', 'tagName');
  19. * tagNames.subscribe(x => console.log(x));
  20. *
  21. * @see {@link map}
  22. *
  23. * @param {...string} properties The nested properties to pluck from each source
  24. * value (an object).
  25. * @return {Observable} A new Observable of property values from the source values.
  26. * @method pluck
  27. * @owner Observable
  28. */
  29. function pluck() {
  30. var properties = [];
  31. for (var _i = 0; _i < arguments.length; _i++) {
  32. properties[_i - 0] = arguments[_i];
  33. }
  34. var length = properties.length;
  35. if (length === 0) {
  36. throw new Error('list of properties cannot be empty.');
  37. }
  38. return function (source) { return map_1.map(plucker(properties, length))(source); };
  39. }
  40. exports.pluck = pluck;
  41. function plucker(props, length) {
  42. var mapper = function (x) {
  43. var currentProp = x;
  44. for (var i = 0; i < length; i++) {
  45. var p = currentProp[props[i]];
  46. if (typeof p !== 'undefined') {
  47. currentProp = p;
  48. }
  49. else {
  50. return undefined;
  51. }
  52. }
  53. return currentProp;
  54. };
  55. return mapper;
  56. }
  57. //# sourceMappingURL=pluck.js.map