nxkit
Version:
This is a collection of tools, independent of any other libraries
419 lines (418 loc) • 11.7 kB
JavaScript
;
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2015, xuewen.chu
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of xuewen.chu nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL xuewen.chu BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ***** END LICENSE BLOCK ***** */
Object.defineProperty(exports, "__esModule", { value: true });
const event_1 = require("./event");
const errno_1 = require("./errno");
var id = 10;
var AsyncFunctionConstructor = (async function () { }).constructor;
var scopeLockQueue = new Map();
exports.currentTimezone = new Date().getTimezoneOffset() / -60; // 当前时区
function isAsync(func) {
return func && func.constructor === AsyncFunctionConstructor;
}
exports.isAsync = isAsync;
class obj_constructor {
}
function clone_object(new_obj, obj) {
for (var name of Object.getOwnPropertyNames(obj)) {
var property = Object.getOwnPropertyDescriptor(obj, name);
if (property.writable) {
new_obj[name] = clone(property.value);
} //else {
// Object.defineProperty(new_obj, name, property);
//}
}
return new_obj;
}
function getId() {
return id++;
}
exports.getId = getId;
/**
* @fun clone # 克隆一个Object对像
* @arg obj {Object} # 要复制的Object对像
* @arg {Object}
*/
function clone(obj) {
if (obj && typeof obj == 'object') {
var new_obj = null, i;
switch (obj.constructor) {
case Object:
new_obj = {};
for (i in obj) {
new_obj[i] = clone(obj[i]);
}
return new_obj;
case Array:
new_obj = [];
for (i = 0; i < obj.length; i++) {
new_obj[i] = clone(obj[i]);
}
return new_obj;
case Date:
return new Date(obj.valueOf());
default:
obj_constructor.prototype = obj.constructor.prototype;
new_obj = new obj_constructor();
return clone_object(new_obj, obj);
}
}
return obj;
}
exports.clone = clone;
/**
* @func extend(obj, extd)
*/
function extend(obj, extd, end) {
if (extd.__proto__ && extd.__proto__ !== end)
extend(obj, extd.__proto__, end);
for (var i of Object.getOwnPropertyNames(extd)) {
if (i != 'constructor') {
var desc = Object.getOwnPropertyDescriptor(extd, i);
desc.enumerable = false;
Object.defineProperty(obj, i, desc);
}
}
return obj;
}
exports.extend = extend;
/**
* Empty function
*/
function noop() { }
exports.noop = noop;
/**
* @func isNull(value)
*/
function isNull(value) {
return value === null || value === undefined;
}
exports.isNull = isNull;
/**
* @fun extendClass # EXT class prototype objects
*/
function extendClass(cls, extds, end = Object.prototype) {
var proto = cls.prototype;
var extds_ = Array.isArray(extds) ? extds : [extds];
for (var extd of extds_) {
if (extd instanceof Function) {
extd = extd.prototype;
}
extend(proto, extd, end);
}
return cls;
}
exports.extendClass = extendClass;
async function scopeLockDequeue(mutex) {
var item, queue = scopeLockQueue.get(mutex);
while (item = queue.shift()) {
try {
item.resolve(await item.cb());
}
catch (err) {
item.reject(err);
}
}
scopeLockQueue.delete(mutex);
}
/**
* @func scopeLock(mutex, cb)
*/
function scopeLock(mutex, cb) {
assert(mutex, 'Bad argument');
assert(typeof cb == 'function', 'Bad argument');
return new Promise((resolve, reject) => {
if (scopeLockQueue.has(mutex)) {
scopeLockQueue.get(mutex).push({ resolve, reject, cb });
}
else {
scopeLockQueue.set(mutex, new event_1.List().push({ resolve, reject, cb }).host);
scopeLockDequeue(mutex); // dequeue
}
});
}
exports.scopeLock = scopeLock;
/**
* @fun get(name[,self]) # get object value by name
* @arg name {String}
* @arg [self] {Object}
* @ret {Object}
*/
function get(name, self) {
var names = name.split('.');
var item;
while ((item = names.shift())) {
self = self[item];
if (!self)
return self;
}
return self;
}
exports.get = get;
/**
* @fun set(name,value[,self]) # Setting object value by name
* @arg name {String}
* @arg value {Object}
* @arg [self] {Object}
* @ret {Object}
*/
function set(name, value, self) {
var item = null;
var names = name.split('.');
var _name = names.pop();
while ((item = names.shift())) {
self = self[item] || (self[item] = {});
}
self[_name] = value;
return self;
}
exports.set = set;
/**
* @fun def(name[,self]) # Delete object value by name
* @arg name {String}
* @arg [self] {Object}
*/
function del(name, self) {
var names = name.split('.');
var _name = names.pop();
self = get(names.join('.'), self);
if (self)
delete self[_name];
}
exports.del = del;
/**
* @fun random # 创建随机数字
* @arg [start] {Number} # 开始位置
* @arg [end] {Number} # 结束位置
* @ret {Number}
*/
function random(start = 0, end = 1E8) {
if (start == end)
return start;
var r = Math.random();
start = start || 0;
end = end || (end === 0 ? 0 : 1E8);
return Math.floor(start + r * (end - start + 1));
}
exports.random = random;
/**
* @fun fixRandom # 固定随机值,指定几率返回常数
* @arg args.. {Number} # 输入百分比
* @ret {Number}
*/
function fixRandom(arg, ...args) {
if (!args.length)
return 0;
var total = arg;
var argus = [arg];
var len = args.length;
for (var i = 0; i < len; i++) {
total += args[i];
argus.push(total);
}
var r = random(0, total - 1);
for (var i = 0; (i < len); i++) {
if (r < argus[i])
return i;
}
return 0;
}
exports.fixRandom = fixRandom;
/**
* @fun filter # object filter
* @arg obj {Object}
* @arg exp {Object} # filter exp
* @arg non {Boolean} # take non
* @ret {Object}
*/
function filter(obj, exp, non = false) {
var rev = {};
var isfn = (typeof exp == 'function');
if (isfn || non) {
for (var key in obj) {
var value = obj[key];
var b = isfn ? exp(key, value) : (exp.indexOf(key) != -1);
if (non ? !b : b)
rev[key] = value;
}
}
else {
for (var item of exp) {
item = String(item);
if (item in obj)
rev[item] = obj[item];
}
}
return rev;
}
exports.filter = filter;
/**
* @fun update # update object property value
* @arg obj {Object} # need to be updated for as
* @arg extd {Object} # update object
* @arg {Object}
*/
function update(obj, extd) {
for (var key in extd) {
if (key in obj) {
obj[key] = select(obj[key], extd[key]);
}
}
return obj;
}
exports.update = update;
/**
* @fun select
* @arg default {Object}
* @arg value {Object}
* @reg {Object}
*/
function select(default_, value) {
if (typeof default_ == typeof value) {
return value;
}
else {
return default_;
}
}
exports.select = select;
/**
* @fun equalsClass # Whether this type of sub-types
* @arg baseclass {class}
* @arg subclass {class}
*/
function equalsClass(baseclass, subclass) {
if (!baseclass || !subclass || !subclass.prototype)
return false;
if (baseclass === subclass)
return true;
var prototype = baseclass.prototype;
var subprototype = subclass.prototype;
if (!subprototype)
return false;
var obj = subprototype.__proto__;
while (obj) {
if (prototype === obj)
return true;
obj = obj.__proto__;
}
return false;
}
exports.equalsClass = equalsClass;
/**
* @fun assert
*/
function assert(condition, code, ...args) {
if (condition)
return;
if (Array.isArray(code)) { // ErrnoCode
throw Error.new(code);
}
else {
var errno;
if (typeof code == 'number') {
errno = [code, 'assert fail, unforeseen exceptions'];
}
else {
errno = [-30009, String.format(String(code || 'ERR_ASSERT_ERROR'), ...args)];
}
throw Error.new(errno);
}
}
exports.assert = assert;
/**
* @func sleep()
*/
function sleep(time, defaultValue) {
return new Promise((ok, err) => setTimeout(() => ok(defaultValue), time));
}
exports.sleep = sleep;
function timeout(promise, time) {
if (promise instanceof Promise) {
return new Promise(function (_resolve, _reject) {
var id = setTimeout(function () {
id = 0;
_reject(Error.new(errno_1.default.ERR_EXECUTE_TIMEOUT));
}, time);
var ok = (err, r) => {
if (id) {
clearTimeout(id);
id = 0;
if (err)
_reject(err);
else
_resolve(r);
}
};
promise.then(e => ok(null, e)).catch(ok);
});
}
else {
return Promise.resolve(promise);
}
}
exports.timeout = timeout;
class PromiseNx extends Promise {
constructor(executor) {
var _resolve;
var _reject;
super(function (resolve, reject) {
_resolve = resolve;
_reject = reject;
});
this.m_executor = executor;
try {
var r = this.executor(_resolve, _reject);
if (r instanceof Promise) {
r.catch(_reject);
}
}
catch (err) {
_reject(err);
}
}
executor(resolve, reject) {
if (this.m_executor) {
return this.m_executor(resolve, reject, this);
}
else {
throw Error.new('executor undefined');
}
}
}
exports.PromiseNx = PromiseNx;
/**
* @func promise(executor)
*/
function promise(executor) {
return new PromiseNx(executor);
}
exports.promise = promise;