UNPKG

3.68 kBJavaScriptView Raw
1const errors = require('./Errors');
2
3utils = {}; //utility functions
4
5// ==== OBJECT ORIENTED JAVASCRIPT ===============
6// This is a general purpose library of functions,
7//Parts of this file (consolearr, and createElement) are duplicated in dweb-transport; dweb-transports and dweb-objects repo
8
9// Utility function to print a array of items but just show number and last.
10utils.consolearr = (arr) => ((arr && arr.length >0) ? [arr.length+" items inc:", arr[arr.length-1]] : arr );
11
12utils.stringfrom = function(foo, hints={}) {
13 try {
14 // Generic way to turn anything into a string
15 if (foo.constructor.name === "Url") // Can't use instanceof for some bizarre reason
16 return foo.href;
17 if (typeof foo === "string")
18 return foo;
19 return foo.toString(); // Last chance try and convert to a string based on a method of the object (could check for its existence)
20 } catch (err) {
21 throw new errors.CodingError(`Unable to turn ${foo} into a string ${err.message}`)
22 }
23};
24
25utils.p_timeout = function(promise, ms, errorstr) {
26 /* In a certain period, timeout and reject
27 promise: A promise we want to watch to completion
28 ms: Time in milliseconds to allow it to run
29 errorstr: Error message in reject error
30 throws: TimeoutError on timeout with message = errorstr
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
45utils.createElement = function(tag, attrs, children) { // Note arguments is set to tag, attrs, child1, child2 etc
46 // Note identical version in dweb-transport/js/utils.js and dweb-transports/utils.js and dweb-objects/utils.js
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)) { // e.g. style: {fontSize: "124px"}
60 for (let k in value) {
61 element[attrname][k] = value[k];
62 }
63 } else {
64 // Assume we are really trying to set the value to an object, allow it
65 element[attrname] = value; // Wont let us use setAttribute(attrname, value) unclear if because unknow attribute or object
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++) { // Everything after attrs
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
89exports = module.exports = utils;