/
util.js
executable file
·490 lines (435 loc) · 10.8 KB
/
util.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
/* ***** 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 ***** */
var _pkg = require('pkg');
var _util = process.binding('ngui_util');
/**************************************************************************/
var currentTimezone = new Date().getTimezoneOffset() / -60; // 当前时区
var default_throw = Function.prototype.throw;
var id = 10;
var extendEntries = _pkg.extendEntries;
var assign = Object.assign;
var AsyncFunctionConstructor = (async function() {}).constructor;
function is_async(func) {
return func && func.constructor === AsyncFunctionConstructor;
}
//
// util
// ======
//
function obj_constructor() { }
function clone_object(new_obj, obj) {
var names = Object.getOwnPropertyNames(obj);
for (var i = 0, len = names.length; i < len; i++) {
var name = names[i];
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 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;
}
function extend(obj, extd) {
if (extd.__proto__ && extd.__proto__ !== Object.prototype) {
extend(obj, extd.__proto__);
}
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;
}
/**
* @fun nextTick # Next tick exec
* @arg [self] {Object}
* @arg cb {Function} # callback function
* @arg [...] {Object} # call args
*/
function next_tick(cb) {
var self = null;
var args = Array.toArray(arguments, 1);
if (typeof cb != 'function') {
self = cb;
cb = args.shift();
}
if (typeof cb != 'function')
throw new Error('arguments error');
process.nextTick(function () {
cb.apply(self, args);
});
}
exports = module.exports = {
// @func fatal()
// @func hashCode()
// @func hash()
// @func version()
// @func addNativeEventListener()
// @func removeNativeEventListener()
// @func garbageCollection()
// @func runScript()
// @func transformJsx()
// @func transformJs()
// @func executable()
// @func documents()
// @func temp()
// @func resources()
// @func fallbackPath()
// @func cwd()
// @func chdir()
// @func log()
/**
* @current timezone
*/
timezone: currentTimezone,
/**
* @has dev mode
*/
dev: !!_pkg.options.dev,
/**
* @start argv options
*/
options: _pkg.options,
/**
* @func resolve(...args)
*/
resolve: _pkg.resolve,
/**
* @func isAbsolute(path)
*/
isAbsolute: _pkg.isAbsolute,
/**
* Empty function
*/
noop: function() { },
/**
* @func isAsync(func)
*/
isAsync: function(func) {
return is_async(func);
},
/**
* @func nextTick(cb)
*/
nextTick: next_tick,
/**
*
* @fun assign(ext, ...) `Object.assign` Extended attribute from obj to extd
* @arg obj {Object}
* @arg extd {Object}
* @ret {Object}
*/
assign: assign,
/**
* @func extend(obj, extd)
*/
extend: extend,
/**
* @func extendEntries(obj, extd)
*/
extendEntries: extendEntries,
/**
* @get id
*/
get id() {
return id++;
},
/**
* @fun err # create error object
* @arg e {Object}
* @arg [code] {Number}
* @ret {Error}
*/
err: function(e, code) {
return Error.new(e, code);
},
/**
* @fun cb # return default callback
* @ret {Function}
*/
cb: function(cb) {
return cb || function () { };
},
/**
* @fun throw # 抛出异常
* @arg err {Object}
* @arg [cb] {Function} # 异步回调
*/
throw: function(err, cb) {
exports.cb(cb).throw(exports.err(err));
},
/**
* @func isDefaultThrow
*/
isDefaultThrow: function(func) {
return default_throw === func.throw;
},
/**
* @fun get(name[,self]) # get object value by name
* @arg name {String}
* @arg [self] {Object}
* @ret {Object}
*/
get: function(name, self) {
var names = name.split('.');
var item;
self = self || global;
while ( (item = names.shift()) ) {
self = self[item];
if (!self)
return self;
}
return self;
},
/**
* @fun set(name,value[,self]) # Setting object value by name
* @arg name {String}
* @arg value {Object}
* @arg [self] {Object}
* @ret {Object}
*/
set: function(name, value, self) {
self = self || global;
var item = null;
var names = name.split('.');
name = names.pop();
while ( (item = names.shift()) ){
self = self[item] || (self[item] = {});
}
self[name] = value;
return self;
},
/**
* @fun def(name[,self]) # Delete object value by name
* @arg name {String}
* @arg [self] {Object}
*/
del: function(name, self) {
var names = name.split('.');
name = names.pop();
self = exports.get(names.join('.'), self || global);
if (self)
delete self[name];
},
/**
* @fun random # 创建随机数字
* @arg [start] {Number} # 开始位置
* @arg [end] {Number} # 结束位置
* @ret {Number}
*/
random: function(start, end) {
var r = Math.random();
start = start || 0;
end = end || 1E8;
return Math.floor(start + r * (end - start + 1));
},
/**
* @fun fixRandom # 固定随机值,指定几率返回常数
* @arg args.. {Number} # 输入百分比
* @ret {Number}
*/
fixRandom: function() {
var total = 0;
var argus = [];
var i = 0;
var len = arguments.length;
for (; (i < len); i++) {
var e = arguments[i];
total += e;
argus.push(total);
}
var r = exports.random(0, total - 1);
for (i = 0; (i < len); i++) {
if (r < argus[i])
return i;
}
},
/**
* @fun clone # 克隆一个Object对像
* @arg obj {Object} # 要复制的Object对像
* @arg {Object}
*/
clone: clone,
/**
* @fun wrap
* @ret {Object}
*/
wrap: function(o) { return { __proto__: o } },
/**
* @fun filter # object filter
* @arg obj {Object}
* @arg exp {Object} # filter exp
* @arg non {Boolean} # take non
* @ret {Object}
*/
filter: function(obj, exp, non) {
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 {
exp.forEach(function (item) {
item = String(item);
if (item in obj)
rev[item] = obj[item];
});
}
return rev;
},
/**
* @fun update # update object property value
* @arg obj {Object} # need to be updated for as
* @arg extd {Object} # update object
* @arg {Object}
*/
update: function(obj, extd) {
for (var key in extd) {
if (key in obj) {
obj[key] = exports.select(obj[key], extd[key]);
}
}
return obj;
},
/**
* @fun select
* @arg default {Object}
* @arg value {Object}
* @reg {Object}
*/
select: function(default_, value) {
if ( typeof default_ == typeof value ) {
return value;
} else {
return default_;
}
},
/**
* @fun extendClass # EXT class prototype objects
*/
extendClass: function(cls, ...extds) {
var proto = cls.prototype;
for (var extd of extds) {
if (extd instanceof Function) {
extd = extd.prototype;
}
extend(proto, extd);
}
},
/**
* @fun equalsClass # Whether this type of sub-types
* @arg baseclass {class}
* @arg subclass {class}
*/
equalsClass: function(baseclass, subclass) {
if (!baseclass || !subclass) return false;
if (baseclass === subclass) return true;
var prototype = baseclass.prototype;
var obj = subclass.prototype.__proto__;
while (obj) {
if (prototype === obj)
return true;
obj = obj.__proto__;
}
return false;
},
/**
* @fun assert
*/
assert: function(is, code) {
if (is) {
return;
}
if (Array.isArray(code)) {
throw Error.new(code);
} else {
var args = Array.toArray(arguments);
if (typeof code == 'number') {
args = args.slice(2);
} else {
args = args.slice(1);
code = -2;
}
if (args.length) {
throw Error.new(String.format.apply(null, args), code);
} else {
throw Error.new('assert fail, unforeseen exceptions', code);
}
}
},
/**
* @get config
*/
get config() {
return _pkg.config;
},
/**
* @func sleep()
*/
sleep: function(time, defaultValue) {
return new Promise((ok, err)=>setTimeout(e=>ok(defaultValue), time));
},
// @end
};
exports.__proto__ = _util;