##// END OF EJS Templates
core/safe ported to typescript
cin -
r16:638c2fe34531 propose cancellat...
parent child
Show More
@@ -0,0 +1,231
1 export function argumentNotNull(arg, name) {
2 if (arg === null || arg === undefined)
3 throw new Error("The argument " + name + " can't be null or undefined");
4 }
5
6 export function argumentNotEmptyString(arg, name) {
7 if (typeof (arg) !== "string" || !arg.length)
8 throw new Error("The argument '" + name + "' must be a not empty string");
9 }
10
11 export function argumentNotEmptyArray(arg, name) {
12 if (!(arg instanceof Array) || !arg.length)
13 throw new Error("The argument '" + name + "' must be a not empty array");
14 }
15
16 export function argumentOfType(arg, type, name) {
17 if (!(arg instanceof type))
18 throw new Error("The argument '" + name + "' type doesn't match");
19 }
20
21 export function isNull(arg) {
22 return (arg === null || arg === undefined);
23 }
24
25 export function isPrimitive(arg) {
26 return (arg === null || arg === undefined || typeof (arg) === "string" ||
27 typeof (arg) === "number" || typeof (arg) === "boolean");
28 }
29
30 export function isInteger(arg) {
31 return parseInt(arg) == arg;
32 }
33
34 export function isNumber(arg) {
35 return parseFloat(arg) == arg;
36 }
37
38 export function isString(val) {
39 return typeof (val) == "string" || val instanceof String;
40 }
41
42 export function isNullOrEmptyString(str) {
43 if (str === null || str === undefined ||
44 ((typeof (str) == "string" || str instanceof String) && str.length === 0))
45 return true;
46 }
47
48 export function isNotEmptyArray(arg) {
49 return (arg instanceof Array && arg.length > 0);
50 }
51
52 /**
53 * Выполняет метод для каждого элемента массива, останавливается, когда
54 * либо достигнут конец массива, либо функция <c>cb</c> вернула
55 * значение.
56 *
57 * @param {Array | Object} obj массив элементов для просмотра
58 * @param {Function} cb функция, вызываемая для каждого элемента
59 * @param {Object} thisArg значение, которое будет передано в качестве
60 * <c>this</c> в <c>cb</c>.
61 * @returns Результат вызова функции <c>cb</c>, либо <c>undefined</c>
62 * если достигнут конец массива.
63 */
64 export function each(obj, cb, thisArg) {
65 argumentNotNull(cb, "cb");
66 var i, x;
67 if (obj instanceof Array) {
68 for (i = 0; i < obj.length; i++) {
69 x = cb.call(thisArg, obj[i], i);
70 if (x !== undefined)
71 return x;
72 }
73 } else {
74 var keys = Object.keys(obj);
75 for (i = 0; i < keys.length; i++) {
76 var k = keys[i];
77 x = cb.call(thisArg, obj[k], k);
78 if (x !== undefined)
79 return x;
80 }
81 }
82 }
83
84 /** Wraps the specified function to emulate an asynchronous execution.
85 * @param{Object} thisArg [Optional] Object which will be passed as 'this' to the function.
86 * @param{Function|String} fn [Required] Function wich will be wrapped.
87 */
88 export function async(_fn: (...args: any[]) => any, thisArg) : (...args: any[]) => PromiseLike<any> {
89 let fn = _fn;
90
91 if (arguments.length == 2 && !(fn instanceof Function))
92 fn = thisArg[fn];
93
94 if (fn == null)
95 throw new Error("The function must be specified");
96
97 function wrapresult(x, e?) : PromiseLike<any> {
98 if (e) {
99 return {
100 then: function (cb, eb) {
101 try {
102 return eb ? wrapresult(eb(e)) : this;
103 } catch (e2) {
104 return wrapresult(null, e2);
105 }
106 }
107 };
108 } else {
109 if (x && x.then)
110 return x;
111 return {
112 then: function (cb) {
113 try {
114 return cb ? wrapresult(cb(x)) : this;
115 } catch (e2) {
116 return wrapresult(e2);
117 }
118 }
119 };
120 }
121 }
122
123 return function () {
124 try {
125 return wrapresult(fn.apply(thisArg, arguments));
126 } catch (e) {
127 return wrapresult(null, e);
128 }
129 };
130 }
131
132 export function delegate(target, _method: (string | Function)) {
133 let method : Function;
134
135 if (!(_method instanceof Function)) {
136 argumentNotNull(target, "target");
137 method = target[_method];
138 } else {
139 method = _method;
140 }
141
142 if (!(method instanceof Function))
143 throw new Error("'method' argument must be a Function or a method name");
144
145 return function () {
146 return method.apply(target, arguments);
147 };
148 }
149
150 /**
151 * Для каждого элемента массива вызывает указанную функцию и сохраняет
152 * возвращенное значение в массиве результатов.
153 *
154 * @remarks cb может выполняться асинхронно, при этом одновременно будет
155 * только одна операция.
156 *
157 * @async
158 */
159 export function pmap(items, cb) {
160 argumentNotNull(cb, "cb");
161
162 if (items && items.then instanceof Function)
163 return items.then(function (data) {
164 return pmap(data, cb);
165 });
166
167 if (isNull(items) || !items.length)
168 return items;
169
170 var i = 0,
171 result = [];
172
173 function next() {
174 var r, ri;
175
176 function chain(x) {
177 result[ri] = x;
178 return next();
179 }
180
181 while (i < items.length) {
182 r = cb(items[i], i);
183 ri = i;
184 i++;
185 if (r && r.then) {
186 return r.then(chain);
187 } else {
188 result[ri] = r;
189 }
190 }
191 return result;
192 }
193
194 return next();
195 }
196
197 /**
198 * Выбирает первый элемент из последовательности, или обещания, если в
199 * качестве параметра используется обещание, оно должно вернуть массив.
200 *
201 * @param {Function} cb обработчик результата, ему будет передан первый
202 * элемент последовательности в случае успеха
203 * @param {Function} err обработчик исключения, если массив пустой, либо
204 * не массив
205 *
206 * @remarks Если не указаны ни cb ни err, тогда функция вернет либо
207 * обещание, либо первый элемент.
208 * @async
209 */
210 export function first(sequence: any, cb: Function, err: Function) {
211 if (sequence) {
212 if (sequence.then instanceof Function) {
213 return sequence.then(function (res) {
214 return first(res, cb, err);
215 }, err);
216 } else if (sequence && "length" in sequence) {
217 if (sequence.length === 0) {
218 if (err)
219 return err(new Error("The sequence is empty"));
220 else
221 throw new Error("The sequence is empty");
222 }
223 return cb ? cb(sequence[0]) : sequence[0];
224 }
225 }
226
227 if (err)
228 return err(new Error("The sequence is required"));
229 else
230 throw new Error("The sequence is required");
231 } No newline at end of file
@@ -133,7 +133,7
133 },
133 },
134 "minimist": {
134 "minimist": {
135 "version": "0.0.5",
135 "version": "0.0.5",
136 "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.5.tgz",
136 "resolved": "http://registry.npmjs.org/minimist/-/minimist-0.0.5.tgz",
137 "integrity": "sha1-16oye87PUY+RBqxrjwA/o7zqhWY=",
137 "integrity": "sha1-16oye87PUY+RBqxrjwA/o7zqhWY=",
138 "dev": true
138 "dev": true
139 },
139 },
@@ -319,9 +319,9
319 }
319 }
320 },
320 },
321 "requirejs": {
321 "requirejs": {
322 "version": "2.3.5",
322 "version": "2.3.6",
323 "resolved": "https://registry.npmjs.org/requirejs/-/requirejs-2.3.5.tgz",
323 "resolved": "https://registry.npmjs.org/requirejs/-/requirejs-2.3.6.tgz",
324 "integrity": "sha512-svnO+aNcR/an9Dpi44C7KSAy5fFGLtmPbaaCeQaklUz8BQhS64tWWIIlvEA5jrWICzlO/X9KSzSeXFnZdBu8nw==",
324 "integrity": "sha512-ipEzlWQe6RK3jkzikgCupiTbTvm4S0/CAU5GlgptkN5SO6F3u0UD0K18wy6ErDqiCyP4J4YYe1HuAShvsxePLg==",
325 "dev": true
325 "dev": true
326 },
326 },
327 "resolve": {
327 "resolve": {
@@ -413,9 +413,9
413 }
413 }
414 },
414 },
415 "typescript": {
415 "typescript": {
416 "version": "2.9.2",
416 "version": "3.0.3",
417 "resolved": "https://registry.npmjs.org/typescript/-/typescript-2.9.2.tgz",
417 "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.0.3.tgz",
418 "integrity": "sha512-Gr4p6nFNaoufRIY4NMdpQRNmgxVIGMs4Fcu/ujdYk3nAZqk7supzBE9idmvfZIlH/Cuj//dvi+019qEue9lV0w==",
418 "integrity": "sha512-kk80vLW9iGtjMnIv11qyxLqZm20UklzuR2tL0QAnDIygIUIemcZMxlMWudl9OOt76H3ntVzcTiddQ1/pAAJMYg==",
419 "dev": true
419 "dev": true
420 },
420 },
421 "wrappy": {
421 "wrappy": {
@@ -1,9 +1,9
1 import { IObservable, ICancellation, IDestroyable } from "@implab/core/interfaces";
1 import { IObservable, ICancellation, IDestroyable } from "../../build/dist/interfaces";
2 import * as TraceEvent from '@implab/core/log/TraceEvent';
2 import * as TraceEvent from '../../build/dist/log/TraceEvent';
3 import { Cancellation } from "@implab/core/Cancellation";
3 import { Cancellation } from "../../build/dist/Cancellation";
4 import * as TraceSource from "@implab/core/log/TraceSource";
4 import * as TraceSource from "../../build/dist/log/TraceSource";
5 import * as tape from 'tape';
5 import * as tape from 'tape';
6 import { argumentNotNull } from "@implab/core/safe";
6 import { argumentNotNull } from "../../build/dist/safe";
7
7
8 export class TapeWriter implements IDestroyable {
8 export class TapeWriter implements IDestroyable {
9 readonly _tape: tape.Test
9 readonly _tape: tape.Test
@@ -1,6 +1,6
1 import * as TraceSource from '@implab/core/log/TraceSource'
1 import * as TraceSource from '../../build/dist/log/TraceSource'
2 import * as tape from 'tape';
2 import * as tape from 'tape';
3 import * as ConsoleWriter from '@implab/core/log/writers/ConsoleWriter';
3 import * as ConsoleWriter from '../../build/dist/log/writers/ConsoleWriter';
4 import { TapeWriter } from './TestTraits';
4 import { TapeWriter } from './TestTraits';
5
5
6 const sourceId = 'test/TraceSourceTests';
6 const sourceId = 'test/TraceSourceTests';
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now