map.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. 'use strict';
  2. var once = require('once');
  3. var helpers = require('./helpers');
  4. function map(values, iterator, extensions, done) {
  5. // Allow for extensions to not be specified
  6. if (typeof extensions === 'function') {
  7. done = extensions;
  8. extensions = {};
  9. }
  10. // Handle no callback case
  11. if (typeof done !== 'function') {
  12. done = helpers.noop;
  13. }
  14. done = once(done);
  15. // Will throw if non-object
  16. var keys = Object.keys(values);
  17. var length = keys.length;
  18. var count = length;
  19. var idx = 0;
  20. // Return the same type as passed in
  21. var results = helpers.initializeResults(values);
  22. var exts = helpers.defaultExtensions(extensions);
  23. if (length === 0) {
  24. return done(null, results);
  25. }
  26. for (idx = 0; idx < length; idx++) {
  27. var key = keys[idx];
  28. next(key);
  29. }
  30. function next(key) {
  31. var value = values[key];
  32. var storage = exts.create(value, key) || {};
  33. exts.before(storage);
  34. iterator(value, key, once(handler));
  35. function handler(err, result) {
  36. if (err) {
  37. exts.error(err, storage);
  38. return done(err, results);
  39. }
  40. exts.after(result, storage);
  41. results[key] = result;
  42. if (--count === 0) {
  43. done(err, results);
  44. }
  45. }
  46. }
  47. }
  48. module.exports = map;