##// END OF EJS Templates
fixed safe.mixin typings
cin -
r140:93d9db76884e v1.4.0-rc2 default
parent child
Show More
@@ -1,32 +1,32
1 package org.implab.gradle.hg;
1 package org.implab.gradle.hg;
2
2
3 import org.gradle.api.Plugin;
3 import org.gradle.api.Plugin;
4 import org.gradle.api.Project;
4 import org.gradle.api.Project;
5
5
6 public class MercurialPlugin implements Plugin<Project> {
6 public class MercurialPlugin implements Plugin<Project> {
7 public void apply(Project project) {
7 public void apply(Project project) {
8 if (!project.version) {
8 if (!project.version) {
9
9
10 def rev = ["hg", "log", "-r", ".", "--template", "{latesttag('re:^v') % '{tag}-{distance}'}"].execute().text.trim();
10 def rev = ["hg", "log", "-r", ".", "--template", "{latesttag('re:^v') % '{tag}-{distance}'}"].execute().text.trim();
11
11
12 def tagVersion;
12 def tagVersion;
13 def tagDistance;
13 def tagDistance;
14
14
15 def match = (rev =~ /^v(\d+\.\d+\.\d+).*-(\d+)$/);
15 def match = (rev =~ /^v(\d+\.\d+\.\d+(?:-\w+)?).*-(\d+)$/);
16
16
17 if (match.size()) {
17 if (match.size()) {
18 tagVersion = match[0][1];
18 tagVersion = match[0][1];
19 tagDistance = match[0][2].toInteger();
19 tagDistance = match[0][2].toInteger();
20 } else {
20 } else {
21 throw new Exception("A version must be specied");
21 throw new Exception("A version must be specied");
22 }
22 }
23
23
24 project.version = tagVersion;
24 project.version = tagVersion;
25
25
26 if (tagDistance > 0)
26 if (tagDistance > 0)
27 project.version++;
27 project.version++;
28 } else {
28 } else {
29 println "explicit version: $project.version";
29 println "explicit version: $project.version";
30 }
30 }
31 }
31 }
32 } No newline at end of file
32 }
@@ -1,502 +1,502
1 import { ICancellable, Constructor, IDestroyable, PromiseOrValue } from "./interfaces";
1 import { ICancellable, Constructor, IDestroyable, PromiseOrValue } from "./interfaces";
2 import { Cancellation } from "./Cancellation";
2 import { Cancellation } from "./Cancellation";
3
3
4 let _nextOid = 0;
4 let _nextOid = 0;
5 const _oid = typeof Symbol === "function" ?
5 const _oid = typeof Symbol === "function" ?
6 Symbol("__implab__oid__") :
6 Symbol("__implab__oid__") :
7 "__implab__oid__";
7 "__implab__oid__";
8
8
9 export function oid(instance: null | undefined): undefined;
9 export function oid(instance: null | undefined): undefined;
10 export function oid(instance: NonNullable<any>): string;
10 export function oid(instance: NonNullable<any>): string;
11 export function oid(instance: any): string | undefined {
11 export function oid(instance: any): string | undefined {
12 if (isNull(instance))
12 if (isNull(instance))
13 return undefined;
13 return undefined;
14
14
15 if (_oid in instance)
15 if (_oid in instance)
16 return instance[_oid];
16 return instance[_oid];
17 else
17 else
18 return (instance[_oid] = "oid_" + (++_nextOid));
18 return (instance[_oid] = "oid_" + (++_nextOid));
19 }
19 }
20
20
21 export function keys<T>(arg: T): (Extract<keyof T, string>)[] {
21 export function keys<T>(arg: T): (Extract<keyof T, string>)[] {
22 return isObject(arg) && arg ? Object.keys(arg) as (Extract<keyof T, string>)[] : [];
22 return isObject(arg) && arg ? Object.keys(arg) as (Extract<keyof T, string>)[] : [];
23 }
23 }
24
24
25 export function isKeyof<T>(k: string, target: T): k is Extract<keyof T, string> {
25 export function isKeyof<T>(k: string, target: T): k is Extract<keyof T, string> {
26 return target && typeof target === "object" && k in target;
26 return target && typeof target === "object" && k in target;
27 }
27 }
28
28
29 export function argumentNotNull(arg: any, name: string) {
29 export function argumentNotNull(arg: any, name: string) {
30 if (arg === null || arg === undefined)
30 if (arg === null || arg === undefined)
31 throw new Error("The argument " + name + " can't be null or undefined");
31 throw new Error("The argument " + name + " can't be null or undefined");
32 }
32 }
33
33
34 export function argumentNotEmptyString(arg: any, name: string) {
34 export function argumentNotEmptyString(arg: any, name: string) {
35 if (typeof (arg) !== "string" || !arg.length)
35 if (typeof (arg) !== "string" || !arg.length)
36 throw new Error("The argument '" + name + "' must be a not empty string");
36 throw new Error("The argument '" + name + "' must be a not empty string");
37 }
37 }
38
38
39 export function argumentNotEmptyArray(arg: any, name: string) {
39 export function argumentNotEmptyArray(arg: any, name: string) {
40 if (!(arg instanceof Array) || !arg.length)
40 if (!(arg instanceof Array) || !arg.length)
41 throw new Error("The argument '" + name + "' must be a not empty array");
41 throw new Error("The argument '" + name + "' must be a not empty array");
42 }
42 }
43
43
44 export function argumentOfType(arg: any, type: Constructor<{}>, name: string) {
44 export function argumentOfType(arg: any, type: Constructor<{}>, name: string) {
45 if (!(arg instanceof type))
45 if (!(arg instanceof type))
46 throw new Error("The argument '" + name + "' type doesn't match");
46 throw new Error("The argument '" + name + "' type doesn't match");
47 }
47 }
48
48
49 export function isObject(val: any): val is object {
49 export function isObject(val: any): val is object {
50 return typeof val === "object";
50 return typeof val === "object";
51 }
51 }
52
52
53 export function isNull(val: any): val is null | undefined {
53 export function isNull(val: any): val is null | undefined {
54 return (val === null || val === undefined);
54 return (val === null || val === undefined);
55 }
55 }
56
56
57 export type primitive = symbol | string | number | boolean | undefined | null;
57 export type primitive = symbol | string | number | boolean | undefined | null;
58
58
59 export function isPrimitive(val: any): val is primitive {
59 export function isPrimitive(val: any): val is primitive {
60 return (val === null || val === undefined || typeof (val) === "string" ||
60 return (val === null || val === undefined || typeof (val) === "string" ||
61 typeof (val) === "number" || typeof (val) === "boolean");
61 typeof (val) === "number" || typeof (val) === "boolean");
62 }
62 }
63
63
64 export function isInteger(val: any): val is number {
64 export function isInteger(val: any): val is number {
65 return parseInt(val, 10) === val;
65 return parseInt(val, 10) === val;
66 }
66 }
67
67
68 export function isNumber(val: any): val is number {
68 export function isNumber(val: any): val is number {
69 return parseFloat(val) === val;
69 return parseFloat(val) === val;
70 }
70 }
71
71
72 export function isString(val: any): val is string {
72 export function isString(val: any): val is string {
73 return typeof (val) === "string" || val instanceof String;
73 return typeof (val) === "string" || val instanceof String;
74 }
74 }
75
75
76 export function isPromise<T = any>(val: any): val is PromiseLike<T> {
76 export function isPromise<T = any>(val: any): val is PromiseLike<T> {
77 return val && typeof val.then === "function";
77 return val && typeof val.then === "function";
78 }
78 }
79
79
80 export function isCancellable(val: any): val is ICancellable {
80 export function isCancellable(val: any): val is ICancellable {
81 return val && typeof val.cancel === "function";
81 return val && typeof val.cancel === "function";
82 }
82 }
83
83
84 export function isNullOrEmptyString(val: any): val is ("" | null | undefined) {
84 export function isNullOrEmptyString(val: any): val is ("" | null | undefined) {
85 return (val === null || val === undefined ||
85 return (val === null || val === undefined ||
86 ((typeof (val) === "string" || val instanceof String) && val.length === 0));
86 ((typeof (val) === "string" || val instanceof String) && val.length === 0));
87 }
87 }
88
88
89 export function isNotEmptyArray<T = any>(arg: any): arg is T[] {
89 export function isNotEmptyArray<T = any>(arg: any): arg is T[] {
90 return (arg instanceof Array && arg.length > 0);
90 return (arg instanceof Array && arg.length > 0);
91 }
91 }
92
92
93 function _isStrictMode(this: any) {
93 function _isStrictMode(this: any) {
94 return !this;
94 return !this;
95 }
95 }
96
96
97 function _getNonStrictGlobal(this: any) {
97 function _getNonStrictGlobal(this: any) {
98 return this;
98 return this;
99 }
99 }
100
100
101 export function getGlobal() {
101 export function getGlobal() {
102 // in es3 we can't use indirect call to eval, since it will
102 // in es3 we can't use indirect call to eval, since it will
103 // be executed in the current call context.
103 // be executed in the current call context.
104 if (!_isStrictMode()) {
104 if (!_isStrictMode()) {
105 return _getNonStrictGlobal();
105 return _getNonStrictGlobal();
106 } else {
106 } else {
107 // tslint:disable-next-line:no-eval
107 // tslint:disable-next-line:no-eval
108 return eval.call(null, "this");
108 return eval.call(null, "this");
109 }
109 }
110 }
110 }
111
111
112 export function get(member: string, context?: object) {
112 export function get(member: string, context?: object) {
113 argumentNotEmptyString(member, "member");
113 argumentNotEmptyString(member, "member");
114 let that = context || getGlobal();
114 let that = context || getGlobal();
115 const parts = member.split(".");
115 const parts = member.split(".");
116 for (const m of parts) {
116 for (const m of parts) {
117 if (!m)
117 if (!m)
118 continue;
118 continue;
119 if (isNull(that = that[m]))
119 if (isNull(that = that[m]))
120 break;
120 break;
121 }
121 }
122 return that;
122 return that;
123 }
123 }
124
124
125 /**
125 /**
126 * ВыполняСт ΠΌΠ΅Ρ‚ΠΎΠ΄ для ΠΊΠ°ΠΆΠ΄ΠΎΠ³ΠΎ элСмСнта массива, останавливаСтся, ΠΊΠΎΠ³Π΄Π°
126 * ВыполняСт ΠΌΠ΅Ρ‚ΠΎΠ΄ для ΠΊΠ°ΠΆΠ΄ΠΎΠ³ΠΎ элСмСнта массива, останавливаСтся, ΠΊΠΎΠ³Π΄Π°
127 * Π»ΠΈΠ±ΠΎ достигнут ΠΊΠΎΠ½Π΅Ρ† массива, Π»ΠΈΠ±ΠΎ функция <c>cb</c> Π²Π΅Ρ€Π½ΡƒΠ»Π°
127 * Π»ΠΈΠ±ΠΎ достигнут ΠΊΠΎΠ½Π΅Ρ† массива, Π»ΠΈΠ±ΠΎ функция <c>cb</c> Π²Π΅Ρ€Π½ΡƒΠ»Π°
128 * Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅.
128 * Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅.
129 *
129 *
130 * @param {Array | Object} obj массив элСмСнтов для просмотра
130 * @param {Array | Object} obj массив элСмСнтов для просмотра
131 * @param {Function} cb функция, вызываСмая для ΠΊΠ°ΠΆΠ΄ΠΎΠ³ΠΎ элСмСнта
131 * @param {Function} cb функция, вызываСмая для ΠΊΠ°ΠΆΠ΄ΠΎΠ³ΠΎ элСмСнта
132 * @param {Object} thisArg Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅, ΠΊΠΎΡ‚ΠΎΡ€ΠΎΠ΅ Π±ΡƒΠ΄Π΅Ρ‚ ΠΏΠ΅Ρ€Π΅Π΄Π°Π½ΠΎ Π² качСствС
132 * @param {Object} thisArg Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅, ΠΊΠΎΡ‚ΠΎΡ€ΠΎΠ΅ Π±ΡƒΠ΄Π΅Ρ‚ ΠΏΠ΅Ρ€Π΅Π΄Π°Π½ΠΎ Π² качСствС
133 * <c>this</c> Π² <c>cb</c>.
133 * <c>this</c> Π² <c>cb</c>.
134 * @returns {void}
134 * @returns {void}
135 */
135 */
136 export function each<T>(obj: T, cb: <X extends keyof T>(v: NonNullable<T[X]>, k: X) => void): void;
136 export function each<T>(obj: T, cb: <X extends keyof T>(v: NonNullable<T[X]>, k: X) => void): void;
137 export function each<T>(array: T[], cb: (v: T, i: number) => void): void;
137 export function each<T>(array: T[], cb: (v: T, i: number) => void): void;
138 export function each(obj: any, cb: any, thisArg?: any): any;
138 export function each(obj: any, cb: any, thisArg?: any): any;
139 export function each(obj: any, cb: any, thisArg?: any) {
139 export function each(obj: any, cb: any, thisArg?: any) {
140 argumentNotNull(cb, "cb");
140 argumentNotNull(cb, "cb");
141 if (obj instanceof Array) {
141 if (obj instanceof Array) {
142 let v: any;
142 let v: any;
143 for (let i = 0; i < obj.length; i++) {
143 for (let i = 0; i < obj.length; i++) {
144 v = obj[i];
144 v = obj[i];
145 if (v !== undefined)
145 if (v !== undefined)
146 cb.call(thisArg, v, i);
146 cb.call(thisArg, v, i);
147 }
147 }
148 } else {
148 } else {
149 Object.keys(obj).forEach(k => obj[k] !== undefined && cb.call(thisArg, obj[k], k));
149 Object.keys(obj).forEach(k => obj[k] !== undefined && cb.call(thisArg, obj[k], k));
150 }
150 }
151 }
151 }
152
152
153 /** Copies property values from a source object to the destination and returns
153 /** Copies property values from a source object to the destination and returns
154 * the destination onject.
154 * the destination onject.
155 *
155 *
156 * @param dest The destination object into which properties from the source
156 * @param dest The destination object into which properties from the source
157 * object will be copied.
157 * object will be copied.
158 * @param source The source of values which will be copied to the destination
158 * @param source The source of values which will be copied to the destination
159 * object.
159 * object.
160 * @param template An optional parameter specifies which properties should be
160 * @param template An optional parameter specifies which properties should be
161 * copied from the source and how to map them to the destination. If the
161 * copied from the source and how to map them to the destination. If the
162 * template is an array it contains the list of property names to copy from the
162 * template is an array it contains the list of property names to copy from the
163 * source to the destination. In case of object the templates contains the map
163 * source to the destination. In case of object the templates contains the map
164 * where keys are property names in the source and the values are property
164 * where keys are property names in the source and the values are property
165 * names in the destination object. If the template isn't specified then the
165 * names in the destination object. If the template isn't specified then the
166 * own properties of the source are entirely copied to the destination.
166 * own properties of the source are entirely copied to the destination.
167 *
167 *
168 */
168 */
169 export function mixin<T extends object, S extends object>(dest: T, source: S, template?: keyof S[]): T & S;
169 export function mixin<T extends object, S extends object>(dest: T, source: S, template?: (keyof S)[]): T & S;
170 export function mixin<T extends object, S extends object, R extends object = T>(dest: T, source: S, template: { [p in keyof S]?: keyof R; }): T & R;
170 export function mixin<T extends object, S extends object, R extends object = T>(dest: T, source: S, template: { [p in keyof S]?: keyof R; }): T & R;
171 export function mixin<T extends object, S extends object>(dest: T, source: S, template?: any): any {
171 export function mixin<T extends object, S extends object>(dest: T, source: S, template?: any): any {
172 argumentNotNull(dest, "dest");
172 argumentNotNull(dest, "dest");
173 const _res: any = dest as any;
173 const _res: any = dest as any;
174
174
175 if (isPrimitive(source))
175 if (isPrimitive(source))
176 return _res;
176 return _res;
177
177
178 if (template instanceof Array) {
178 if (template instanceof Array) {
179 template.forEach(p => {
179 template.forEach(p => {
180 if (isKeyof(p, source))
180 if (isKeyof(p, source))
181 _res[p] = source[p];
181 _res[p] = source[p];
182 });
182 });
183 } else if (template) {
183 } else if (template) {
184 keys(source).forEach(p => {
184 keys(source).forEach(p => {
185 if (isKeyof(p, template))
185 if (isKeyof(p, template))
186 _res[template[p]] = source[p];
186 _res[template[p]] = source[p];
187 });
187 });
188 } else {
188 } else {
189 keys(source).forEach(p => _res[p] = source[p]);
189 keys(source).forEach(p => _res[p] = source[p]);
190 }
190 }
191
191
192 return _res;
192 return _res;
193 }
193 }
194
194
195 /** Wraps the specified function to emulate an asynchronous execution.
195 /** Wraps the specified function to emulate an asynchronous execution.
196 * @param{Object} thisArg [Optional] Object which will be passed as 'this' to the function.
196 * @param{Object} thisArg [Optional] Object which will be passed as 'this' to the function.
197 * @param{Function|String} fn [Required] Function wich will be wrapped.
197 * @param{Function|String} fn [Required] Function wich will be wrapped.
198 */
198 */
199 export function async<T, F extends (...args: any[]) => T | PromiseLike<T>>(
199 export function async<T, F extends (...args: any[]) => T | PromiseLike<T>>(
200 fn: F,
200 fn: F,
201 thisArg?: ThisParameterType<F>
201 thisArg?: ThisParameterType<F>
202 ): (...args: Parameters<F>) => PromiseLike<T>;
202 ): (...args: Parameters<F>) => PromiseLike<T>;
203 export function async<T, M extends string, O extends { [m in M]?: (...args: any[]) => T | PromiseLike<T> }>(
203 export function async<T, M extends string, O extends { [m in M]?: (...args: any[]) => T | PromiseLike<T> }>(
204 fn: M,
204 fn: M,
205 thisArg: O
205 thisArg: O
206 ): (...args: Parameters<NonNullable<O[M]>>) => PromiseLike<T>;
206 ): (...args: Parameters<NonNullable<O[M]>>) => PromiseLike<T>;
207 export function async(_fn: any, thisArg: any): (...args: any[]) => PromiseLike<any> {
207 export function async(_fn: any, thisArg: any): (...args: any[]) => PromiseLike<any> {
208 let fn = _fn;
208 let fn = _fn;
209
209
210 if (arguments.length === 2 && !(fn instanceof Function))
210 if (arguments.length === 2 && !(fn instanceof Function))
211 fn = thisArg[fn];
211 fn = thisArg[fn];
212
212
213 if (fn == null)
213 if (fn == null)
214 throw new Error("The function must be specified");
214 throw new Error("The function must be specified");
215
215
216 function wrapresult(x: any, e?: any): PromiseLike<any> {
216 function wrapresult(x: any, e?: any): PromiseLike<any> {
217 if (e) {
217 if (e) {
218 return {
218 return {
219 then(cb, eb) {
219 then(cb, eb) {
220 try {
220 try {
221 return eb ? wrapresult(eb(e)) : this;
221 return eb ? wrapresult(eb(e)) : this;
222 } catch (e2) {
222 } catch (e2) {
223 return wrapresult(null, e2);
223 return wrapresult(null, e2);
224 }
224 }
225 }
225 }
226 };
226 };
227 } else {
227 } else {
228 if (x && x.then)
228 if (x && x.then)
229 return x;
229 return x;
230 return {
230 return {
231 then(cb) {
231 then(cb) {
232 try {
232 try {
233 return cb ? wrapresult(cb(x)) : this;
233 return cb ? wrapresult(cb(x)) : this;
234 } catch (e2) {
234 } catch (e2) {
235 return wrapresult(e2);
235 return wrapresult(e2);
236 }
236 }
237 }
237 }
238 };
238 };
239 }
239 }
240 }
240 }
241
241
242 return (...args) => {
242 return (...args) => {
243 try {
243 try {
244 return wrapresult(fn.apply(thisArg, args));
244 return wrapresult(fn.apply(thisArg, args));
245 } catch (e) {
245 } catch (e) {
246 return wrapresult(null, e);
246 return wrapresult(null, e);
247 }
247 }
248 };
248 };
249 }
249 }
250
250
251 export function delegate<T extends object, F extends (this: T, ...args: any[]) => any>(
251 export function delegate<T extends object, F extends (this: T, ...args: any[]) => any>(
252 target: T,
252 target: T,
253 method: F
253 method: F
254 ): OmitThisParameter<F>;
254 ): OmitThisParameter<F>;
255 export function delegate<M extends string, T extends { [m in M]?: (...args: any[]) => any; }>(
255 export function delegate<M extends string, T extends { [m in M]?: (...args: any[]) => any; }>(
256 target: T,
256 target: T,
257 method: M
257 method: M
258 ): OmitThisParameter<T[M]>;
258 ): OmitThisParameter<T[M]>;
259 export function delegate(target: any, _method: any): (...args: any[]) => any {
259 export function delegate(target: any, _method: any): (...args: any[]) => any {
260 let method: any;
260 let method: any;
261 if (!(_method instanceof Function)) {
261 if (!(_method instanceof Function)) {
262 argumentNotNull(target, "target");
262 argumentNotNull(target, "target");
263 method = target[_method];
263 method = target[_method];
264 if (!(method instanceof Function))
264 if (!(method instanceof Function))
265 throw new Error("'method' argument must be a Function or a method name");
265 throw new Error("'method' argument must be a Function or a method name");
266 } else {
266 } else {
267 method = _method;
267 method = _method;
268 }
268 }
269
269
270 return (...args) => {
270 return (...args) => {
271 return method.apply(target, args);
271 return method.apply(target, args);
272 };
272 };
273 }
273 }
274
274
275 export function delay(timeMs: number, ct = Cancellation.none) {
275 export function delay(timeMs: number, ct = Cancellation.none) {
276 ct.throwIfRequested();
276 ct.throwIfRequested();
277 return new Promise((resolve, reject) => {
277 return new Promise((resolve, reject) => {
278 const h = ct.register(e => {
278 const h = ct.register(e => {
279 clearTimeout(id);
279 clearTimeout(id);
280 reject(e);
280 reject(e);
281 // we don't nedd to unregister h, since ct is already disposed
281 // we don't nedd to unregister h, since ct is already disposed
282 });
282 });
283 const id = setTimeout(() => {
283 const id = setTimeout(() => {
284 h.destroy();
284 h.destroy();
285 resolve();
285 resolve();
286 }, timeMs);
286 }, timeMs);
287
287
288 });
288 });
289 }
289 }
290
290
291 /** Returns resolved promise, awaiting this method will cause the asynchronous
291 /** Returns resolved promise, awaiting this method will cause the asynchronous
292 * completion of the rest of the code.
292 * completion of the rest of the code.
293 */
293 */
294 export function fork() {
294 export function fork() {
295 return Promise.resolve();
295 return Promise.resolve();
296 }
296 }
297
297
298 /** Always throws Error, can be used as a stub for the methods which should be
298 /** Always throws Error, can be used as a stub for the methods which should be
299 * assigned later and are required to be not null.
299 * assigned later and are required to be not null.
300 */
300 */
301 export function notImplemented(): never {
301 export function notImplemented(): never {
302 throw new Error("Not implemeted");
302 throw new Error("Not implemeted");
303 }
303 }
304 /**
304 /**
305 * Iterates over the specified array of items and calls the callback `cb`, if
305 * Iterates over the specified array of items and calls the callback `cb`, if
306 * the result of the callback is a promise the next item from the array will be
306 * the result of the callback is a promise the next item from the array will be
307 * proceeded after the promise is resolved.
307 * proceeded after the promise is resolved.
308 *
308 *
309 */
309 */
310 export function pmap<T, T2>(
310 export function pmap<T, T2>(
311 items: ArrayLike<T> | PromiseLike<ArrayLike<T>>,
311 items: ArrayLike<T> | PromiseLike<ArrayLike<T>>,
312 cb: (item: T, i: number) => T2 | PromiseLike<T2>
312 cb: (item: T, i: number) => T2 | PromiseLike<T2>
313 ): T2[] | PromiseLike<T2[]> {
313 ): T2[] | PromiseLike<T2[]> {
314 argumentNotNull(cb, "cb");
314 argumentNotNull(cb, "cb");
315
315
316 if (isPromise(items)) {
316 if (isPromise(items)) {
317 return items.then(data => pmap(data, cb));
317 return items.then(data => pmap(data, cb));
318 } else {
318 } else {
319
319
320 if (isNull(items) || !items.length)
320 if (isNull(items) || !items.length)
321 return [];
321 return [];
322
322
323 let i = 0;
323 let i = 0;
324 const result = new Array<T2>();
324 const result = new Array<T2>();
325
325
326 const next = (): any => {
326 const next = (): any => {
327 while (i < items.length) {
327 while (i < items.length) {
328 const r = cb(items[i], i);
328 const r = cb(items[i], i);
329 const ri = i;
329 const ri = i;
330 i++;
330 i++;
331 if (isPromise(r)) {
331 if (isPromise(r)) {
332 return r.then(x => {
332 return r.then(x => {
333 result[ri] = x;
333 result[ri] = x;
334 return next();
334 return next();
335 });
335 });
336 } else {
336 } else {
337 result[ri] = r;
337 result[ri] = r;
338 }
338 }
339 }
339 }
340 return result;
340 return result;
341 };
341 };
342
342
343 return next();
343 return next();
344 }
344 }
345 }
345 }
346
346
347 export function pfor<T>(
347 export function pfor<T>(
348 items: ArrayLike<T> | PromiseLike<ArrayLike<T>>,
348 items: ArrayLike<T> | PromiseLike<ArrayLike<T>>,
349 cb: (item: T, i: number) => any
349 cb: (item: T, i: number) => any
350 ): void | PromiseLike<void> {
350 ): void | PromiseLike<void> {
351 argumentNotNull(cb, "cb");
351 argumentNotNull(cb, "cb");
352
352
353 if (isPromise(items)) {
353 if (isPromise(items)) {
354 return items.then(data => pfor(data, cb));
354 return items.then(data => pfor(data, cb));
355 } else {
355 } else {
356 if (isNull(items) || !items.length)
356 if (isNull(items) || !items.length)
357 return;
357 return;
358
358
359 let i = 0;
359 let i = 0;
360
360
361 const next = (): any => {
361 const next = (): any => {
362 while (i < items.length) {
362 while (i < items.length) {
363 const r = cb(items[i], i);
363 const r = cb(items[i], i);
364 i++;
364 i++;
365 if (isPromise(r))
365 if (isPromise(r))
366 return r.then(next);
366 return r.then(next);
367 }
367 }
368 };
368 };
369
369
370 return next();
370 return next();
371 }
371 }
372 }
372 }
373
373
374 export function first<T>(sequence: ArrayLike<T>): T;
374 export function first<T>(sequence: ArrayLike<T>): T;
375 export function first<T>(sequence: PromiseLike<ArrayLike<T>>): PromiseLike<T>;
375 export function first<T>(sequence: PromiseLike<ArrayLike<T>>): PromiseLike<T>;
376 export function first<T>(
376 export function first<T>(
377 sequence: ArrayLike<T> | PromiseLike<ArrayLike<T>>,
377 sequence: ArrayLike<T> | PromiseLike<ArrayLike<T>>,
378 cb?: (x: T) => void,
378 cb?: (x: T) => void,
379 err?: (x: Error) => void
379 err?: (x: Error) => void
380 ): void;
380 ): void;
381 /**
381 /**
382 * Π’Ρ‹Π±ΠΈΡ€Π°Π΅Ρ‚ ΠΏΠ΅Ρ€Π²Ρ‹ΠΉ элСмСнт ΠΈΠ· ΠΏΠΎΡΠ»Π΅Π΄ΠΎΠ²Π°Ρ‚Π΅Π»ΡŒΠ½ΠΎΡΡ‚ΠΈ, ΠΈΠ»ΠΈ обСщания, Ссли Π²
382 * Π’Ρ‹Π±ΠΈΡ€Π°Π΅Ρ‚ ΠΏΠ΅Ρ€Π²Ρ‹ΠΉ элСмСнт ΠΈΠ· ΠΏΠΎΡΠ»Π΅Π΄ΠΎΠ²Π°Ρ‚Π΅Π»ΡŒΠ½ΠΎΡΡ‚ΠΈ, ΠΈΠ»ΠΈ обСщания, Ссли Π²
383 * качСствС ΠΏΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€Π° ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΡƒΠ΅Ρ‚ΡΡ ΠΎΠ±Π΅Ρ‰Π°Π½ΠΈΠ΅, ΠΎΠ½ΠΎ Π΄ΠΎΠ»ΠΆΠ½ΠΎ Π²Π΅Ρ€Π½ΡƒΡ‚ΡŒ массив.
383 * качСствС ΠΏΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€Π° ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΡƒΠ΅Ρ‚ΡΡ ΠΎΠ±Π΅Ρ‰Π°Π½ΠΈΠ΅, ΠΎΠ½ΠΎ Π΄ΠΎΠ»ΠΆΠ½ΠΎ Π²Π΅Ρ€Π½ΡƒΡ‚ΡŒ массив.
384 *
384 *
385 * @param {Function} cb ΠΎΠ±Ρ€Π°Π±ΠΎΡ‚Ρ‡ΠΈΠΊ Ρ€Π΅Π·ΡƒΠ»ΡŒΡ‚Π°Ρ‚Π°, Π΅ΠΌΡƒ Π±ΡƒΠ΄Π΅Ρ‚ ΠΏΠ΅Ρ€Π΅Π΄Π°Π½ ΠΏΠ΅Ρ€Π²Ρ‹ΠΉ
385 * @param {Function} cb ΠΎΠ±Ρ€Π°Π±ΠΎΡ‚Ρ‡ΠΈΠΊ Ρ€Π΅Π·ΡƒΠ»ΡŒΡ‚Π°Ρ‚Π°, Π΅ΠΌΡƒ Π±ΡƒΠ΄Π΅Ρ‚ ΠΏΠ΅Ρ€Π΅Π΄Π°Π½ ΠΏΠ΅Ρ€Π²Ρ‹ΠΉ
386 * элСмСнт ΠΏΠΎΡΠ»Π΅Π΄ΠΎΠ²Π°Ρ‚Π΅Π»ΡŒΠ½ΠΎΡΡ‚ΠΈ Π² случаС успСха
386 * элСмСнт ΠΏΠΎΡΠ»Π΅Π΄ΠΎΠ²Π°Ρ‚Π΅Π»ΡŒΠ½ΠΎΡΡ‚ΠΈ Π² случаС успСха
387 * @param {Function} err ΠΎΠ±Ρ€Π°Π±ΠΎΡ‚Ρ‡ΠΈΠΊ ΠΈΡΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΡ, Ссли массив пустой, Π»ΠΈΠ±ΠΎ
387 * @param {Function} err ΠΎΠ±Ρ€Π°Π±ΠΎΡ‚Ρ‡ΠΈΠΊ ΠΈΡΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΡ, Ссли массив пустой, Π»ΠΈΠ±ΠΎ
388 * нС массив
388 * нС массив
389 *
389 *
390 * @remarks Если Π½Π΅ ΡƒΠΊΠ°Π·Π°Π½Ρ‹ Π½ΠΈ cb Π½ΠΈ err, Ρ‚ΠΎΠ³Π΄Π° функция Π²Π΅Ρ€Π½Π΅Ρ‚ Π»ΠΈΠ±ΠΎ
390 * @remarks Если Π½Π΅ ΡƒΠΊΠ°Π·Π°Π½Ρ‹ Π½ΠΈ cb Π½ΠΈ err, Ρ‚ΠΎΠ³Π΄Π° функция Π²Π΅Ρ€Π½Π΅Ρ‚ Π»ΠΈΠ±ΠΎ
391 * ΠΎΠ±Π΅Ρ‰Π°Π½ΠΈΠ΅, Π»ΠΈΠ±ΠΎ ΠΏΠ΅Ρ€Π²Ρ‹ΠΉ элСмСнт.
391 * ΠΎΠ±Π΅Ρ‰Π°Π½ΠΈΠ΅, Π»ΠΈΠ±ΠΎ ΠΏΠ΅Ρ€Π²Ρ‹ΠΉ элСмСнт.
392 * @async
392 * @async
393 */
393 */
394 export function first<T>(
394 export function first<T>(
395 sequence: ArrayLike<T> | PromiseLike<ArrayLike<T>>,
395 sequence: ArrayLike<T> | PromiseLike<ArrayLike<T>>,
396 cb?: (x: T) => void,
396 cb?: (x: T) => void,
397 err?: (x: Error) => void
397 err?: (x: Error) => void
398 ) {
398 ) {
399 if (isPromise(sequence)) {
399 if (isPromise(sequence)) {
400 return sequence.then(res => first(res, cb as any /* force to pass undefined cb */, err));
400 return sequence.then(res => first(res, cb as any /* force to pass undefined cb */, err));
401 } else if (sequence && "length" in sequence) {
401 } else if (sequence && "length" in sequence) {
402 if (sequence.length === 0) {
402 if (sequence.length === 0) {
403 if (err)
403 if (err)
404 return err(new Error("The sequence is empty"));
404 return err(new Error("The sequence is empty"));
405 else
405 else
406 throw new Error("The sequence is empty");
406 throw new Error("The sequence is empty");
407 } else if (cb) {
407 } else if (cb) {
408 return cb(sequence[0]);
408 return cb(sequence[0]);
409 } else {
409 } else {
410 return sequence[0];
410 return sequence[0];
411 }
411 }
412 } else {
412 } else {
413 if (err)
413 if (err)
414 return err(new Error("The sequence is required"));
414 return err(new Error("The sequence is required"));
415 else
415 else
416 throw new Error("The sequence is required");
416 throw new Error("The sequence is required");
417 }
417 }
418 }
418 }
419
419
420 export function firstWhere<T>(
420 export function firstWhere<T>(
421 sequence: ArrayLike<T>,
421 sequence: ArrayLike<T>,
422 predicate: (x: T) => boolean
422 predicate: (x: T) => boolean
423 ): T;
423 ): T;
424 export function firstWhere<T>(
424 export function firstWhere<T>(
425 sequence: PromiseLike<ArrayLike<T>>,
425 sequence: PromiseLike<ArrayLike<T>>,
426 predicate: (x: T) => boolean
426 predicate: (x: T) => boolean
427 ): PromiseLike<T>;
427 ): PromiseLike<T>;
428 export function firstWhere<T>(
428 export function firstWhere<T>(
429 sequence: ArrayLike<T> | PromiseLike<ArrayLike<T>>,
429 sequence: ArrayLike<T> | PromiseLike<ArrayLike<T>>,
430 predicate: (x: T) => boolean,
430 predicate: (x: T) => boolean,
431 cb: (x: T) => void,
431 cb: (x: T) => void,
432 err?: (x: Error) => void
432 err?: (x: Error) => void
433 ): void;
433 ): void;
434
434
435 export function firstWhere<T>(
435 export function firstWhere<T>(
436 sequence: ArrayLike<T> | PromiseLike<ArrayLike<T>>,
436 sequence: ArrayLike<T> | PromiseLike<ArrayLike<T>>,
437 predicate?: (x: T) => boolean,
437 predicate?: (x: T) => boolean,
438 cb?: (x: T) => any,
438 cb?: (x: T) => any,
439 err?: (x: Error) => any
439 err?: (x: Error) => any
440 ) {
440 ) {
441 if (isPromise(sequence)) {
441 if (isPromise(sequence)) {
442 return sequence.then(res => firstWhere(
442 return sequence.then(res => firstWhere(
443 res,
443 res,
444 predicate as any /* force to pass undefined predicate */,
444 predicate as any /* force to pass undefined predicate */,
445 cb as any /* force to pass undefined cb */,
445 cb as any /* force to pass undefined cb */,
446 err)
446 err)
447 );
447 );
448 } else if (sequence && "length" in sequence) {
448 } else if (sequence && "length" in sequence) {
449 if (sequence.length === 0) {
449 if (sequence.length === 0) {
450 if (err)
450 if (err)
451 err(new Error("The sequence is empty"));
451 err(new Error("The sequence is empty"));
452 else
452 else
453 throw new Error("The sequence is empty");
453 throw new Error("The sequence is empty");
454 } else {
454 } else {
455 if (!predicate) {
455 if (!predicate) {
456 return cb ? cb(sequence[0]) && void (0) : sequence[0];
456 return cb ? cb(sequence[0]) && void (0) : sequence[0];
457 } else {
457 } else {
458 for (let i = 0; i < sequence.length; i++) {
458 for (let i = 0; i < sequence.length; i++) {
459 const v = sequence[i];
459 const v = sequence[i];
460 if (predicate(v))
460 if (predicate(v))
461 return cb ? cb(v) : v;
461 return cb ? cb(v) : v;
462 }
462 }
463 if (err)
463 if (err)
464 err(new Error("The sequence doesn't contain matching items"));
464 err(new Error("The sequence doesn't contain matching items"));
465 else
465 else
466 throw new Error("The sequence doesn't contain matching items");
466 throw new Error("The sequence doesn't contain matching items");
467 }
467 }
468 }
468 }
469 } else {
469 } else {
470 if (err)
470 if (err)
471 err(new Error("The sequence is required"));
471 err(new Error("The sequence is required"));
472 else
472 else
473 throw new Error("The sequence is required");
473 throw new Error("The sequence is required");
474 }
474 }
475 }
475 }
476
476
477 export function isDestroyable(d: any): d is IDestroyable {
477 export function isDestroyable(d: any): d is IDestroyable {
478 if (d && "destroy" in d && typeof (destroy) === "function")
478 if (d && "destroy" in d && typeof (destroy) === "function")
479 return true;
479 return true;
480 return false;
480 return false;
481 }
481 }
482
482
483 export function destroy(d: any) {
483 export function destroy(d: any) {
484 if (d && "destroy" in d)
484 if (d && "destroy" in d)
485 d.destroy();
485 d.destroy();
486 }
486 }
487
487
488 /**
488 /**
489 * Used to mark that the async operation isn't awaited intentionally.
489 * Used to mark that the async operation isn't awaited intentionally.
490 * @param p The promise which represents the async operation.
490 * @param p The promise which represents the async operation.
491 */
491 */
492 export function nowait(p: Promise<any>) {
492 export function nowait(p: Promise<any>) {
493 }
493 }
494
494
495 /** represents already destroyed object.
495 /** represents already destroyed object.
496 */
496 */
497 export const destroyed = {
497 export const destroyed = {
498 /** Calling to this method doesn't affect anything, noop.
498 /** Calling to this method doesn't affect anything, noop.
499 */
499 */
500 destroy() {
500 destroy() {
501 }
501 }
502 };
502 };
General Comments 0
You need to be logged in to leave comments. Login now