| 1 |
// Promise aware Array's find |
| 2 |
// Additionally differs from some that it returns *first in order* item that matches constraint |
| 3 |
|
| 4 |
"use strict"; |
| 5 |
|
| 6 |
var assign = require("es5-ext/object/assign") |
| 7 |
, isValue = require("es5-ext/object/is-value") |
| 8 |
, ensureValue = require("es5-ext/object/valid-value") |
| 9 |
, callable = require("es5-ext/object/valid-callable") |
| 10 |
, toNaturalNumber = require("es5-ext/number/to-pos-integer") |
| 11 |
, deferred = require("../../deferred") |
| 12 |
, isPromise = require("../../is-promise") |
| 13 |
, assimilate = require("../../assimilate"); |
| 14 |
|
| 15 |
var call = Function.prototype.call, resolve = deferred.resolve, Find; |
| 16 |
|
| 17 |
Find = function (list, cb, context) { |
| 18 |
this.list = list; |
| 19 |
this.cb = cb; |
| 20 |
this.context = context; |
| 21 |
this.length = toNaturalNumber(list.length); |
| 22 |
|
| 23 |
while (this.current < this.length) { |
| 24 |
if (this.current in list) { |
| 25 |
assign(this, deferred()); |
| 26 |
this.processCb = this.processCb.bind(this); |
| 27 |
this.process(); |
| 28 |
return this.promise; |
| 29 |
} |
| 30 |
++this.current; |
| 31 |
} |
| 32 |
return resolve(undefined); |
| 33 |
}; |
| 34 |
|
| 35 |
Find.prototype = { |
| 36 |
current: 0, |
| 37 |
process: function () { |
| 38 |
var value = assimilate(this.list[this.current]); |
| 39 |
if (isPromise(value)) { |
| 40 |
if (!value.resolved) { |
| 41 |
value.done(this.processCb, this.reject); |
| 42 |
return; |
| 43 |
} |
| 44 |
if (value.failed) { |
| 45 |
this.reject(value.value); |
| 46 |
return; |
| 47 |
} |
| 48 |
value = value.value; |
| 49 |
} |
| 50 |
this.processCb(value); |
| 51 |
}, |
| 52 |
processCb: function (listValue) { |
| 53 |
var value; |
| 54 |
if (this.cb) { |
| 55 |
try { |
| 56 |
value = call.call(this.cb, this.context, listValue, this.current, this.list); |
| 57 |
} catch (e) { |
| 58 |
this.reject(e); |
| 59 |
return; |
| 60 |
} |
| 61 |
value = assimilate(value); |
| 62 |
if (isPromise(value)) { |
| 63 |
if (!value.resolved) { |
| 64 |
value.done(this.processValue.bind(this, listValue), this.reject); |
| 65 |
return; |
| 66 |
} |
| 67 |
if (value.failed) { |
| 68 |
this.reject(value.value); |
| 69 |
return; |
| 70 |
} |
| 71 |
value = value.value; |
| 72 |
} |
| 73 |
} else { |
| 74 |
value = listValue; |
| 75 |
} |
| 76 |
this.processValue(listValue, value); |
| 77 |
}, |
| 78 |
processValue: function (listValue, value) { |
| 79 |
if (value) { |
| 80 |
this.resolve(listValue); |
| 81 |
return; |
| 82 |
} |
| 83 |
while (++this.current < this.length) { |
| 84 |
if (this.current in this.list) { |
| 85 |
this.process(); |
| 86 |
return; |
| 87 |
} |
| 88 |
} |
| 89 |
this.resolve(undefined); |
| 90 |
} |
| 91 |
}; |
| 92 |
|
| 93 |
module.exports = function (cb/*, thisArg*/) { |
| 94 |
ensureValue(this); |
| 95 |
if (isValue(cb)) callable(cb); |
| 96 |
|
| 97 |
return new Find(this, cb, arguments[1]); |
| 98 |
}; |