map.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. for (idx = 0; idx < length; idx++) {
  24. var key = keys[idx];
  25. next(key);
  26. }
  27. function next(key) {
  28. var value = values[key];
  29. var storage = exts.create(value, key) || {};
  30. exts.before(storage);
  31. iterator(value, key, once(handler));
  32. function handler(err, result) {
  33. if (err) {
  34. exts.error(err, storage);
  35. return done(err, results);
  36. }
  37. exts.after(result, storage);
  38. results[key] = result;
  39. if (--count === 0) {
  40. done(err, results);
  41. }
  42. }
  43. }
  44. }
  45. module.exports = map;