1 | const errors = require('./Errors');
|
2 |
|
3 | utils = {};
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 | utils.consolearr = (arr) => ((arr && arr.length >0) ? [arr.length+" items inc:", arr[arr.length-1]] : arr );
|
11 |
|
12 | utils.stringfrom = function(foo, hints={}) {
|
13 | try {
|
14 |
|
15 | if (foo.constructor.name === "Url")
|
16 | return foo.href;
|
17 | if (typeof foo === "string")
|
18 | return foo;
|
19 | return foo.toString();
|
20 | } catch (err) {
|
21 | throw new errors.CodingError(`Unable to turn ${foo} into a string ${err.message}`)
|
22 | }
|
23 | };
|
24 |
|
25 | utils.p_timeout = function(promise, ms, errorstr) {
|
26 | |
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 | let timer = null;
|
33 |
|
34 | return Promise.race([
|
35 | new Promise((resolve, reject) => {
|
36 | timer = setTimeout(reject, ms, new errors.TimeoutError(errorstr || `Timed out in ${ms}ms`));
|
37 | }),
|
38 | promise.then((value) => {
|
39 | clearTimeout(timer);
|
40 | return value;
|
41 | })
|
42 | ]);
|
43 | }
|
44 |
|
45 | utils.createElement = function(tag, attrs, children) {
|
46 |
|
47 | var element = document.createElement(tag);
|
48 | for (let name in attrs) {
|
49 | let attrname = (name.toLowerCase() === "classname" ? "class" : name);
|
50 | if (name === "dangerouslySetInnerHTML") {
|
51 | element.innerHTML = attrs[name]["__html"];
|
52 | delete attrs.dangerouslySetInnerHTML;
|
53 | }
|
54 | if (attrs.hasOwnProperty(name)) {
|
55 | let value = attrs[name];
|
56 | if (value === true) {
|
57 | element.setAttribute(attrname, name);
|
58 | } else if (typeof value === "object" && !Array.isArray(value)) {
|
59 | if (["style"].includes(attrname)) {
|
60 | for (let k in value) {
|
61 | element[attrname][k] = value[k];
|
62 | }
|
63 | } else {
|
64 |
|
65 | element[attrname] = value;
|
66 | }
|
67 | } else if (value !== false && value != null) {
|
68 | element.setAttribute(attrname, value.toString());
|
69 | }
|
70 | }
|
71 | }
|
72 | for (let i = 2; i < arguments.length; i++) {
|
73 | let child = arguments[i];
|
74 | if (!child) {
|
75 | } else if (Array.isArray(child)) {
|
76 | child.map((c) => element.appendChild(c.nodeType == null ?
|
77 | document.createTextNode(c.toString()) : c))
|
78 | }
|
79 | else {
|
80 | element.appendChild(
|
81 | child.nodeType == null ?
|
82 | document.createTextNode(child.toString()) : child);
|
83 | }
|
84 | }
|
85 | return element;
|
86 | }
|
87 |
|
88 |
|
89 | exports = module.exports = utils;
|