##// END OF EJS Templates
tests
tests

File last commit:

r41:eae7e609c38a di-typescript
r41:eae7e609c38a di-typescript
Show More
safe.ts
306 lines | 9.5 KiB | video/mp2t | TypeScriptLexer
cin
ported IoC container to typescript...
r34 let _nextOid = 0;
cin
tests
r41 const _oid = typeof Symbol === "function" ? Symbol("__oid") : "__oid";
cin
ported IoC container to typescript...
r34
cin
ts code cleanup, linting
r39 export function oid(instance: object): string {
cin
ported IoC container to typescript...
r34 if (isNull(instance))
return null;
if (_oid in instance)
return instance[_oid];
else
return (instance[_oid] = "oid_" + (++_nextOid));
}
cin
core/safe ported to typescript
r16 export function argumentNotNull(arg, name) {
if (arg === null || arg === undefined)
throw new Error("The argument " + name + " can't be null or undefined");
}
export function argumentNotEmptyString(arg, name) {
if (typeof (arg) !== "string" || !arg.length)
throw new Error("The argument '" + name + "' must be a not empty string");
}
export function argumentNotEmptyArray(arg, name) {
if (!(arg instanceof Array) || !arg.length)
throw new Error("The argument '" + name + "' must be a not empty array");
}
export function argumentOfType(arg, type, name) {
if (!(arg instanceof type))
throw new Error("The argument '" + name + "' type doesn't match");
}
export function isNull(arg) {
return (arg === null || arg === undefined);
}
export function isPrimitive(arg) {
return (arg === null || arg === undefined || typeof (arg) === "string" ||
typeof (arg) === "number" || typeof (arg) === "boolean");
}
export function isInteger(arg) {
cin
ported IoC container to typescript...
r34 return parseInt(arg, 10) === arg;
cin
core/safe ported to typescript
r16 }
export function isNumber(arg) {
cin
ported IoC container to typescript...
r34 return parseFloat(arg) === arg;
cin
core/safe ported to typescript
r16 }
export function isString(val) {
cin
ported IoC container to typescript...
r34 return typeof (val) === "string" || val instanceof String;
cin
core/safe ported to typescript
r16 }
cin
ts code cleanup, linting
r39 export function isPromise(val): val is PromiseLike<any> {
return "then" in val && val.then instanceof Function;
}
cin
core/safe ported to typescript
r16 export function isNullOrEmptyString(str) {
if (str === null || str === undefined ||
cin
ported IoC container to typescript...
r34 ((typeof (str) === "string" || str instanceof String) && str.length === 0))
cin
core/safe ported to typescript
r16 return true;
}
cin
minor fixes, code cleanup...
r33 export function isNotEmptyArray(arg): arg is Array<any> {
cin
core/safe ported to typescript
r16 return (arg instanceof Array && arg.length > 0);
}
cin
ported IoC container to typescript...
r34 export function getGlobal() {
return this;
}
export function get(member: string, context?: object) {
argumentNotEmptyString(member, "member");
let that = context || getGlobal();
const parts = member.split(".");
for (const m of parts) {
if (!m)
continue;
if (isNull(that = that[m]))
break;
}
return that;
}
cin
core/safe ported to typescript
r16 /**
* Выполняет метод для каждого элемента массива, останавливается, когда
* либо достигнут конец массива, либо функция <c>cb</c> вернула
* значение.
cin
ported IoC container to typescript...
r34 *
cin
core/safe ported to typescript
r16 * @param {Array | Object} obj массив элементов для просмотра
* @param {Function} cb функция, вызываемая для каждого элемента
* @param {Object} thisArg значение, которое будет передано в качестве
* <c>this</c> в <c>cb</c>.
* @returns Результат вызова функции <c>cb</c>, либо <c>undefined</c>
* если достигнут конец массива.
*/
cin
minor fixes, code cleanup...
r33 export function each(obj, cb, thisArg?) {
cin
core/safe ported to typescript
r16 argumentNotNull(cb, "cb");
if (obj instanceof Array) {
cin
ported IoC container to typescript...
r34 for (let i = 0; i < obj.length; i++) {
const x = cb.call(thisArg, obj[i], i);
cin
core/safe ported to typescript
r16 if (x !== undefined)
return x;
}
} else {
cin
ported IoC container to typescript...
r34 const keys = Object.keys(obj);
for (const k of keys) {
const x = cb.call(thisArg, obj[k], k);
cin
core/safe ported to typescript
r16 if (x !== undefined)
return x;
}
}
}
cin
minor fixes, code cleanup...
r33 /** Copies property values from a source object to the destination and returns
* the destination onject.
cin
ported IoC container to typescript...
r34 *
cin
minor fixes, code cleanup...
r33 * @param dest The destination object into which properties from the source
* object will be copied.
* @param source The source of values which will be copied to the destination
* object.
* @param template An optional parameter specifies which properties should be
* copied from the source and how to map them to the destination. If the
* template is an array it contains the list of property names to copy from the
* source to the destination. In case of object the templates contains the map
* where keys are property names in the source and the values are property
* names in the destination object. If the template isn't specified then the
* own properties of the source are entirely copied to the destination.
cin
ported IoC container to typescript...
r34 *
cin
minor fixes, code cleanup...
r33 */
cin
ported IoC container to typescript...
r34 export function mixin<T, S>(dest: T, source: S, template?: string[] | object): T & S {
cin
minor fixes, code cleanup...
r33 argumentNotNull(dest, "to");
cin
ported IoC container to typescript...
r34 const _res = dest as T & S;
cin
minor fixes, code cleanup...
r33
if (template instanceof Array) {
cin
ts code cleanup, linting
r39 for (const p of template) {
cin
minor fixes, code cleanup...
r33 if (p in source)
_res[p] = source[p];
}
} else if (template) {
cin
ported IoC container to typescript...
r34 const keys = Object.keys(source);
for (const p of keys) {
cin
minor fixes, code cleanup...
r33 if (p in template)
_res[template[p]] = source[p];
}
} else {
cin
ported IoC container to typescript...
r34 const keys = Object.keys(source);
for (const p of keys)
cin
minor fixes, code cleanup...
r33 _res[p] = source[p];
}
return _res;
}
cin
core/safe ported to typescript
r16 /** Wraps the specified function to emulate an asynchronous execution.
* @param{Object} thisArg [Optional] Object which will be passed as 'this' to the function.
* @param{Function|String} fn [Required] Function wich will be wrapped.
*/
cin
minor fixes, code cleanup...
r33 export function async(_fn: (...args: any[]) => any, thisArg): (...args: any[]) => PromiseLike<any> {
cin
core/safe ported to typescript
r16 let fn = _fn;
cin
ported IoC container to typescript...
r34 if (arguments.length === 2 && !(fn instanceof Function))
cin
core/safe ported to typescript
r16 fn = thisArg[fn];
if (fn == null)
throw new Error("The function must be specified");
cin
minor fixes, code cleanup...
r33 function wrapresult(x, e?): PromiseLike<any> {
cin
core/safe ported to typescript
r16 if (e) {
return {
cin
ported IoC container to typescript...
r34 then(cb, eb) {
cin
core/safe ported to typescript
r16 try {
return eb ? wrapresult(eb(e)) : this;
} catch (e2) {
return wrapresult(null, e2);
}
}
};
} else {
if (x && x.then)
return x;
return {
cin
ported IoC container to typescript...
r34 then(cb) {
cin
core/safe ported to typescript
r16 try {
return cb ? wrapresult(cb(x)) : this;
} catch (e2) {
return wrapresult(e2);
}
}
};
}
}
cin
ported IoC container to typescript...
r34 return (...args) => {
cin
core/safe ported to typescript
r16 try {
cin
ported IoC container to typescript...
r34 return wrapresult(fn.apply(thisArg, args));
cin
core/safe ported to typescript
r16 } catch (e) {
return wrapresult(null, e);
}
};
}
cin
ported IoC container to typescript...
r34 type _AnyFn = (...args) => any;
export function delegate<T, K extends keyof T>(target: T, _method: (K | _AnyFn)) {
cin
minor fixes, code cleanup...
r33 let method;
cin
core/safe ported to typescript
r16
if (!(_method instanceof Function)) {
argumentNotNull(target, "target");
method = target[_method];
cin
minor fixes, code cleanup...
r33 if (!(method instanceof Function))
throw new Error("'method' argument must be a Function or a method name");
cin
core/safe ported to typescript
r16 } else {
method = _method;
}
cin
ported IoC container to typescript...
r34 return (...args) => {
return method.apply(target, args);
cin
core/safe ported to typescript
r16 };
}
/**
* Для каждого элемента массива вызывает указанную функцию и сохраняет
* возвращенное значение в массиве результатов.
cin
ported IoC container to typescript...
r34 *
cin
core/safe ported to typescript
r16 * @remarks cb может выполняться асинхронно, при этом одновременно будет
* только одна операция.
cin
ported IoC container to typescript...
r34 *
cin
core/safe ported to typescript
r16 * @async
*/
export function pmap(items, cb) {
argumentNotNull(cb, "cb");
cin
tests
r41 if (isPromise(items))
cin
ts code cleanup, linting
r39 return items.then(data => pmap(data, cb));
cin
core/safe ported to typescript
r16
if (isNull(items) || !items.length)
return items;
cin
ts code cleanup, linting
r39 let i = 0;
const result = [];
cin
core/safe ported to typescript
r16
function next() {
cin
ts code cleanup, linting
r39 let r;
let ri;
cin
core/safe ported to typescript
r16
function chain(x) {
result[ri] = x;
return next();
}
while (i < items.length) {
r = cb(items[i], i);
ri = i;
i++;
cin
ts code cleanup, linting
r39 if (isPromise(r)) {
cin
core/safe ported to typescript
r16 return r.then(chain);
} else {
result[ri] = r;
}
}
return result;
}
return next();
}
/**
* Выбирает первый элемент из последовательности, или обещания, если в
* качестве параметра используется обещание, оно должно вернуть массив.
cin
ts code cleanup, linting
r39 *
cin
core/safe ported to typescript
r16 * @param {Function} cb обработчик результата, ему будет передан первый
* элемент последовательности в случае успеха
* @param {Function} err обработчик исключения, если массив пустой, либо
* не массив
cin
ts code cleanup, linting
r39 *
cin
core/safe ported to typescript
r16 * @remarks Если не указаны ни cb ни err, тогда функция вернет либо
* обещание, либо первый элемент.
* @async
*/
cin
ts code cleanup, linting
r39 export function first(sequence, cb: (x) => any, err: (x) => any) {
cin
core/safe ported to typescript
r16 if (sequence) {
cin
ts code cleanup, linting
r39 if (isPromise(sequence)) {
return sequence.then(res => first(res, cb, err));
cin
core/safe ported to typescript
r16 } else if (sequence && "length" in sequence) {
if (sequence.length === 0) {
if (err)
return err(new Error("The sequence is empty"));
else
throw new Error("The sequence is empty");
}
return cb ? cb(sequence[0]) : sequence[0];
}
}
if (err)
return err(new Error("The sequence is required"));
else
throw new Error("The sequence is required");
cin
Code cleanup,...
r22 }
cin
ts code cleanup, linting
r39 export function destroy(d) {
if (d && "destroy" in d)
cin
Code cleanup,...
r22 d.destroy();
cin
ts code cleanup, linting
r39 }