/
utils.ts
83 lines (70 loc) · 1.87 KB
/
utils.ts
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
"use strict";
import { isEmpty } from "lodash/lang";
export function makeID(title: string): string {
return title.split(" ").join("-");
}
export function valForForm(val) {
if (typeof val === "boolean") {
return val ? "True" : "False";
} else {
return val;
}
}
export function hasServerErrors(errorsWarnings: {
[msect: string]: { errors: { [paramName: string]: any } };
}): boolean {
if (errorsWarnings) {
for (const [msect, ew] of Object.entries(errorsWarnings)) {
if (!isEmpty(ew.errors)) {
return true;
}
}
}
return false;
}
export function imgDims(url: string): [number, number] {
let img = new Image();
img.src = url;
let [height, width] = [img.height, img.width];
let factor = 1;
if (height > width) {
factor = height / 600;
} else {
factor = width / 600;
}
height = Math.floor(height / factor);
width = Math.floor(width / factor);
return [width, height];
}
// https://github.com/segmentio/is-url
let protocolAndDomainRE = /^(?:\w+:)?\/\/(\S+)$/;
let localhostDomainRE = /^localhost[\:?\d]*(?:[^\:?\d]\S*)?$/;
let nonLocalhostDomainRE = /^[^\s\.]+\.\S{2,}$/;
export function isUrl(string: string): boolean {
if (typeof string !== "string") {
return false;
}
let match = string.match(protocolAndDomainRE);
if (!match) {
return false;
}
let everythingAfterProtocol = match[1];
if (!everythingAfterProtocol) {
return false;
}
if (
localhostDomainRE.test(everythingAfterProtocol) ||
nonLocalhostDomainRE.test(everythingAfterProtocol)
) {
return true;
}
return false;
}
//github.com/developit/dlv/blob/master/index.js
export function dlv(obj: any, key: string, def?: any, p?: any, undef?: any) {
const splitKey = key.split ? key.split(".") : key;
for (p = 0; p < splitKey.length; p++) {
obj = obj ? obj[splitKey[p]] : undef;
}
return obj === undef ? def : obj;
}