Debian Codegraph @

deferred/ext/array/map.js

raw
1 // Promise aware Array's map
2
3 "use strict";
4
5 var assign = require("es5-ext/object/assign")
6 , isValue = require("es5-ext/object/is-value")
7 , ensureValue = require("es5-ext/object/valid-value")
8 , callable = require("es5-ext/object/valid-callable")
9 , toNaturalNumber = require("es5-ext/number/to-pos-integer")
10 , deferred = require("../../deferred")
11 , isPromise = require("../../is-promise")
12 , assimilate = require("../../assimilate");
13
14 var every = Array.prototype.every, call = Function.prototype.call, DMap;
15
16 DMap = function (list, cb, context) {
17 this.list = list;
18 this.cb = cb;
19 this.context = context;
20 this.result = new Array(toNaturalNumber(list.length));
21
22 assign(this, deferred());
23 every.call(list, this.process, this);
24 if (!this.waiting) return this.resolve(this.result);
25 this.initialized = true;
26
27 return this.promise;
28 };
29
30 DMap.prototype = {
31 waiting: 0,
32 initialized: false,
33 process: function (value, index) {
34 ++this.waiting;
35 value = assimilate(value);
36 if (isPromise(value)) {
37 if (!value.resolved) {
38 value.done(this.processCb.bind(this, index), this.reject);
39 return true;
40 }
41 if (value.failed) {
42 this.reject(value.value);
43 return false;
44 }
45 value = value.value;
46 }
47 return this.processCb(index, value);
48 },
49 processCb: function (index, value) {
50 if (this.promise.resolved) return false;
51 if (this.cb) {
52 try {
53 value = call.call(this.cb, this.context, value, index, this.list);
54 } catch (e) {
55 this.reject(e);
56 return false;
57 }
58 value = assimilate(value);
59 if (isPromise(value)) {
60 if (!value.resolved) {
61 value.done(this.processValue.bind(this, index), this.reject);
62 return true;
63 }
64 if (value.failed) {
65 this.reject(value.value);
66 return false;
67 }
68 value = value.value;
69 }
70 }
71 this.processValue(index, value);
72 return true;
73 },
74 processValue: function (index, value) {
75 if (this.promise.resolved) return;
76 this.result[index] = value;
77 if (!--this.waiting && this.initialized) this.resolve(this.result);
78 }
79 };
80
81 module.exports = function (cb/*, thisArg*/) {
82 ensureValue(this);
83 if (isValue(cb)) callable(cb);
84
85 return new DMap(this, cb, arguments[1]);
86 };