forked from pietervdvn/MapComplete
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUtils.ts
793 lines (696 loc) · 27.3 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
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
import * as colors from "./assets/colors.json"
export class Utils {
/**
* In the 'deploy'-step, some code needs to be run by ts-node.
* However, ts-node crashes when it sees 'document'. When running from console, we flag this and disable all code where document is needed.
* This is a workaround and yet another hack
*/
public static runningFromConsole = typeof window === "undefined";
public static readonly assets_path = "./assets/svg/";
public static externalDownloadFunction: (url: string, headers?: any) => Promise<any>;
public static Special_visualizations_tagsToApplyHelpText = `These can either be a tag to add, such as \`amenity=fast_food\` or can use a substitution, e.g. \`addr:housenumber=$number\`.
This new point will then have the tags \`amenity=fast_food\` and \`addr:housenumber\` with the value that was saved in \`number\` in the original feature.
If a value to substitute is undefined, empty string will be used instead.
This supports multiple values, e.g. \`ref=$source:geometry:type/$source:geometry:ref\`
Remark that the syntax is slightly different then expected; it uses '$' to note a value to copy, followed by a name (matched with \`[a-zA-Z0-9_:]*\`). Sadly, delimiting with \`{}\` as these already mark the boundaries of the special rendering...
Note that these values can be prepare with javascript in the theme by using a [calculatedTag](calculatedTags.md#calculating-tags-with-javascript)
`
public static readonly imageExtensions = new Set(["jpg", "png", "svg", "jpeg", ".gif"])
public static readonly special_visualizations_importRequirementDocs = `#### Importing a dataset into OpenStreetMap: requirements
If you want to import a dataset, make sure that:
1. The dataset to import has a suitable license
2. The community has been informed of the import
3. All other requirements of the [import guidelines](https://wiki.openstreetmap.org/wiki/Import/Guidelines) have been followed
There are also some technicalities in your theme to keep in mind:
1. The new feature will be added and will flow through the program as any other new point as if it came from OSM.
This means that there should be a layer which will match the new tags and which will display it.
2. The original feature from your geojson layer will gain the tag '_imported=yes'.
This should be used to change the appearance or even to hide it (eg by changing the icon size to zero)
3. There should be a way for the theme to detect previously imported points, even after reloading.
A reference number to the original dataset is an excellent way to do this
4. When importing ways, the theme creator is also responsible of avoiding overlapping ways.
#### Disabled in unofficial themes
The import button can be tested in an unofficial theme by adding \`test=true\` or \`backend=osm-test\` as [URL-paramter](URL_Parameters.md).
The import button will show up then. If in testmode, you can read the changeset-XML directly in the web console.
In the case that MapComplete is pointed to the testing grounds, the edit will be made on https://master.apis.dev.openstreetmap.org`
private static knownKeys = ["addExtraTags", "and", "calculatedTags", "changesetmessage", "clustering", "color", "condition", "customCss", "dashArray", "defaultBackgroundId", "description", "descriptionTail", "doNotDownload", "enableAddNewPoints", "enableBackgroundLayerSelection", "enableGeolocation", "enableLayers", "enableMoreQuests", "enableSearch", "enableShareScreen", "enableUserBadge", "freeform", "hideFromOverview", "hideInAnswer", "icon", "iconOverlays", "iconSize", "id", "if", "ifnot", "isShown", "key", "language", "layers", "lockLocation", "maintainer", "mappings", "maxzoom", "maxZoom", "minNeededElements", "minzoom", "multiAnswer", "name", "or", "osmTags", "passAllFeatures", "presets", "question", "render", "roaming", "roamingRenderings", "rotation", "shortDescription", "socialImage", "source", "startLat", "startLon", "startZoom", "tagRenderings", "tags", "then", "title", "titleIcons", "type", "version", "wayHandling", "widenFactor", "width"]
private static extraKeys = ["nl", "en", "fr", "de", "pt", "es", "name", "phone", "email", "amenity", "leisure", "highway", "building", "yes", "no", "true", "false"]
private static injectedDownloads = {}
private static _download_cache = new Map<string, { promise: Promise<any>, timestamp: number }>()
/**
* Parses the arguments for special visualisations
*/
public static ParseVisArgs(specs: { name: string, defaultValue?: string }[], args: string[]): any {
const parsed = {};
if (args.length > specs.length) {
throw "To much arguments for special visualization: got " + args.join(",") + " but expected only " + args.length + " arguments"
}
for (let i = 0; i < specs.length; i++) {
const spec = specs[i];
let arg = args[i]?.trim();
if (arg === undefined || arg === "") {
arg = spec.defaultValue
}
parsed[spec.name] = arg
}
return parsed;
}
static EncodeXmlValue(str) {
if (typeof str !== "string") {
str = "" + str
}
return str.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
}
/**
* Gives a clean float, or undefined if parsing fails
* @param str
*/
static asFloat(str): number {
if (str) {
const i = parseFloat(str);
if (isNaN(i)) {
return undefined;
}
return i;
}
return undefined;
}
public static Upper(str: string) {
return str.substr(0, 1).toUpperCase() + str.substr(1);
}
public static TwoDigits(i: number) {
if (i < 10) {
return "0" + i;
}
return "" + i;
}
public static Round(i: number) {
if (i < 0) {
return "-" + Utils.Round(-i);
}
const j = "" + Math.floor(i * 10);
if (j.length == 1) {
return "0." + j;
}
return j.substr(0, j.length - 1) + "." + j.substr(j.length - 1, j.length);
}
public static Times(f: ((i: number) => string), count: number): string {
let res = "";
for (let i = 0; i < count; i++) {
res += f(i);
}
return res;
}
public static TimesT<T>(count: number, f: ((i: number) => T)): T[] {
let res: T[] = [];
for (let i = 0; i < count; i++) {
res.push(f(i));
}
return res;
}
public static NoNull<T>(array: T[]): T[] {
return array?.filter(o => o !== undefined && o !== null)
}
public static Hist(array: string[]): Map<string, number> {
const hist = new Map<string, number>();
for (const s of array) {
hist.set(s, 1 + (hist.get(s) ?? 0))
}
return hist;
}
public static NoEmpty(array: string[]): string[] {
const ls: string[] = [];
for (const t of array) {
if (t === "") {
continue;
}
ls.push(t);
}
return ls;
}
public static EllipsesAfter(str: string, l: number = 100) {
if (str === undefined || str === null) {
return undefined;
}
if (str.length <= l) {
return str;
}
return str.substr(0, l - 3) + "...";
}
public static Dedup(arr: string[]): string[] {
if (arr === undefined) {
return undefined;
}
const newArr = [];
for (const string of arr) {
if (newArr.indexOf(string) < 0) {
newArr.push(string);
}
}
return newArr;
}
public static Dupiclates(arr: string[]): string[] {
if (arr === undefined) {
return undefined;
}
const newArr = [];
const seen = new Set<string>();
for (const string of arr) {
if (seen.has(string)) {
newArr.push(string)
}
seen.add(string)
}
return newArr;
}
public static Identical<T>(t1: T[], t2: T[], eq?: (t: T, t0: T) => boolean): boolean {
if (t1.length !== t2.length) {
return false
}
eq = (a, b) => a === b
for (let i = 0; i < t1.length; i++) {
if (!eq(t1[i], t2[i])) {
return false
}
}
return true;
}
public static MergeTags(a: any, b: any) {
const t = {};
for (const k in a) {
t[k] = a[k];
}
for (const k in b) {
t[k] = b[k];
}
return t;
}
public static SplitFirst(a: string, sep: string): string[] {
const index = a.indexOf(sep);
if (index < 0) {
return [a];
}
return [a.substr(0, index), a.substr(index + sep.length)];
}
/**
* Given a piece of text, will replace any key occuring in 'tags' by the corresponding value
* @param txt
* @param tags
* @param useLang
* @constructor
*/
public static SubstituteKeys(txt: string | undefined, tags: any, useLang?: string): string | undefined {
if (txt === undefined) {
return undefined
}
const regex = /.*{([^}]*)}.*/
let match = txt.match(regex)
while (match) {
const key = match[1]
let v = tags[key]
if (v !== undefined) {
if (v["toISOString"] != undefined) {
// This is a date, probably the timestamp of the object
// @ts-ignore
const date: Date = el;
v = date.toISOString()
}
if (useLang !== undefined && v?.translations !== undefined) {
v = v.translations[useLang] ?? v.translations["*"] ?? (v.textFor !== undefined ? v.textFor(useLang) : v);
}
if (v.InnerConstructElement !== undefined) {
console.warn("SubstituteKeys received a BaseUIElement to substitute in - this is probably a bug and will be downcast to a string\nThe key is", key, "\nThe value is", v)
v = (<HTMLElement>v.InnerConstructElement())?.innerText
}
if (typeof v !== "string") {
v = "" + v
}
v = v.replace(/\n/g, "<br/>")
} else {
// v === undefined
v = ""
}
txt = txt.replace("{" + key + "}", v)
match = txt.match(regex)
}
return txt;
}
public static LoadCustomCss(location: string) {
const head = document.getElementsByTagName('head')[0];
const link = document.createElement('link');
link.id = "customCss";
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = location;
link.media = 'all';
head.appendChild(link);
console.log("Added custom css file ", location)
}
/**
* Copies all key-value pairs of the source into the target. This will change the target
* If the key starts with a '+', the values of the list will be appended to the target instead of overwritten
* @param source
* @param target
* @constructor
* @return the second parameter as is
*/
static Merge(source: any, target: any) {
if (target === null) {
return source
}
for (const key in source) {
if (!source.hasOwnProperty(key)) {
continue
}
if (key.startsWith("=")) {
const trimmedKey = key.substr(1);
target[trimmedKey] = source[key]
continue
}
if (key.startsWith("+") || key.endsWith("+")) {
const trimmedKey = key.replace("+", "");
const sourceV = source[key];
const targetV = (target[trimmedKey] ?? [])
let newList: any[];
if (key.startsWith("+")) {
newList = sourceV.concat(targetV)
} else {
newList = targetV.concat(sourceV)
}
target[trimmedKey] = newList;
continue;
}
const sourceV = source[key]
const targetV = target[key]
if (typeof sourceV === "object") {
if (sourceV === null) {
target[key] = null
} else if (targetV === undefined) {
target[key] = sourceV;
} else {
Utils.Merge(sourceV, targetV);
}
} else {
target[key] = sourceV;
}
}
return target;
}
/**
* Walks the specified path into the object till the end.
*
* If a list is encountered, this is tranparently walked recursively on every object.
*
* The leaf objects are replaced by the function
*/
public static WalkPath(path: string[], object: any, replaceLeaf: ((leaf: any, travelledPath: string[]) => any), travelledPath: string[] = []) {
const head = path[0]
if (path.length === 1) {
// We have reached the leaf
const leaf = object[head];
if (leaf !== undefined) {
if (Array.isArray(leaf)) {
object[head] = leaf.map(o => replaceLeaf(o, travelledPath))
} else {
object[head] = replaceLeaf(leaf, travelledPath)
}
}
return
}
const sub = object[head]
if (sub === undefined) {
return;
}
if (typeof sub !== "object") {
return;
}
if (Array.isArray(sub)) {
sub.forEach((el, i) => Utils.WalkPath(path.slice(1), el, replaceLeaf, [...travelledPath, head, "" + i]))
return;
}
Utils.WalkPath(path.slice(1), sub, replaceLeaf, [...travelledPath, head])
}
/**
* Walks the specified path into the object till the end.
* If a list is encountered, this is tranparently walked recursively on every object.
*
* The leaf objects are collected in the list
*/
public static CollectPath(path: string[], object: any, collectedList: { leaf: any, path: string[] }[] = [], travelledPath: string[] = []): { leaf: any, path: string[] }[] {
if (object === undefined || object === null) {
return collectedList;
}
const head = path[0]
travelledPath = [...travelledPath, head]
if (path.length === 1) {
// We have reached the leaf
const leaf = object[head];
if (leaf === undefined || leaf === null) {
return collectedList
}
if (Array.isArray(leaf)) {
for (let i = 0; i < (<any[]>leaf).length; i++){
const l = (<any[]>leaf)[i];
collectedList.push({leaf: l, path: [...travelledPath, ""+i]})
}
} else {
collectedList.push({leaf, path: travelledPath})
}
return collectedList
}
const sub = object[head]
if (sub === undefined || sub === null) {
return collectedList;
}
if (Array.isArray(sub)) {
sub.forEach((el, i) => Utils.CollectPath(path.slice(1), el, collectedList, [...travelledPath, "" + i]))
return collectedList;
}
if (typeof sub !== "object") {
return collectedList;
}
return Utils.CollectPath(path.slice(1), sub, collectedList, travelledPath)
}
/**
* Apply a function on every leaf of the JSON; used to rewrite parts of the JSON
* @param json
* @param f
* @constructor
*/
static WalkJson(json: any, f: (v: number | string | boolean | undefined) => any) {
if (json === undefined) {
return f(undefined)
}
const jtp = typeof json
if (jtp === "boolean" || jtp === "string" || jtp === "number") {
return f(json)
}
if (json.map !== undefined) {
return json.map(sub => {
return Utils.WalkJson(sub, f);
})
}
const cp = {...json}
for (const key in json) {
cp[key] = Utils.WalkJson(json[key], f)
}
return cp
}
static getOrSetDefault<K, V>(dict: Map<K, V>, k: K, v: () => V) {
let found = dict.get(k);
if (found !== undefined) {
return found;
}
dict.set(k, v());
return dict.get(k);
}
public static MinifyJSON(stringified: string): string {
stringified = stringified.replace(/\|/g, "||");
const keys = Utils.knownKeys.concat(Utils.extraKeys);
for (let i = 0; i < keys.length; i++) {
const knownKey = keys[i];
let code = i;
if (i >= 124) {
code += 1; // Character 127 is our 'escape' character |
}
let replacement = "|" + String.fromCharCode(code)
stringified = stringified.replace(new RegExp(`\"${knownKey}\":`, "g"), replacement);
}
return stringified;
}
public static UnMinify(minified: string): string {
if (minified === undefined || minified === null) {
return undefined;
}
const parts = minified.split("|");
let result = parts.shift();
const keys = Utils.knownKeys.concat(Utils.extraKeys);
for (const part of parts) {
if (part == "") {
// Empty string => this was a || originally
result += "|"
continue
}
const i = part.charCodeAt(0);
result += "\"" + keys[i] + "\":" + part.substring(1)
}
return result;
}
public static injectJsonDownloadForTests(url: string, data) {
Utils.injectedDownloads[url] = data
}
public static download(url: string, headers?: any): Promise<string> {
if (this.externalDownloadFunction !== undefined) {
return this.externalDownloadFunction(url, headers)
}
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = () => {
if (xhr.status == 200) {
resolve(xhr.response)
} else if (xhr.status === 509 || xhr.status === 429) {
reject("rate limited")
} else {
reject(xhr.statusText)
}
};
xhr.open('GET', url);
if (headers !== undefined) {
for (const key in headers) {
xhr.setRequestHeader(key, headers[key])
}
}
xhr.send();
xhr.onerror = reject
}
)
}
public static upload(url: string, data, headers?: any): Promise<string> {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = () => {
if (xhr.status == 200) {
resolve(xhr.response)
} else if (xhr.status === 509 || xhr.status === 429) {
reject("rate limited")
} else {
reject(xhr.statusText)
}
};
xhr.open('POST', url);
if (headers !== undefined) {
for (const key in headers) {
xhr.setRequestHeader(key, headers[key])
}
}
xhr.send(data);
xhr.onerror = reject
}
)
}
public static async downloadJsonCached(url: string, maxCacheTimeMs: number, headers?: any): Promise<any> {
const cached = Utils._download_cache.get(url)
if (cached !== undefined) {
if ((new Date().getTime() - cached.timestamp) <= maxCacheTimeMs) {
return cached.promise
}
}
const promise = /*NO AWAIT as we work with the promise directly */Utils.downloadJson(url, headers)
Utils._download_cache.set(url, {promise, timestamp: new Date().getTime()})
return await promise
}
public static async downloadJson(url: string, headers?: any): Promise<any> {
const injected = Utils.injectedDownloads[url]
if (injected !== undefined) {
console.log("Using injected resource for test for URL", url)
return new Promise((resolve, _) => resolve(injected))
}
const data = await Utils.download(url, Utils.Merge({"accept": "application/json"}, headers ?? {}))
try {
if (typeof data === "string") {
return JSON.parse(data)
}
return data
} catch (e) {
console.error("Could not parse ", data, "due to", e, "\n", e.stack)
throw e;
}
}
/**
* Triggers a 'download file' popup which will download the contents
*/
public static offerContentsAsDownloadableFile(contents: string | Blob, fileName: string = "download.txt",
options?: { mimetype: string }) {
const element = document.createElement("a");
let file;
if (typeof (contents) === "string") {
file = new Blob([contents], {type: options?.mimetype ?? 'text/plain'});
} else {
file = contents;
}
element.href = URL.createObjectURL(file);
element.download = fileName;
document.body.appendChild(element); // Required for this to work in FireFox
element.click();
}
public static ColourNameToHex(color: string): string {
return colors[color.toLowerCase()] ?? color;
}
public static HexToColourName(hex: string): string {
hex = hex.toLowerCase()
if (!hex.startsWith("#")) {
return hex;
}
const c = Utils.color(hex);
let smallestDiff = Number.MAX_VALUE;
let bestColor = undefined;
for (const color in colors) {
if (!colors.hasOwnProperty(color)) {
continue;
}
const foundhex = colors[color];
if (typeof foundhex !== "string") {
continue
}
if (foundhex === hex) {
return color
}
const diff = this.colorDiff(Utils.color(foundhex), c)
if (diff > 50) {
continue;
}
if (diff < smallestDiff) {
smallestDiff = diff;
bestColor = color;
}
}
return bestColor ?? hex;
}
static sortKeys(o: any) {
const copy = {}
let keys = Object.keys(o)
keys = keys.sort()
for (const key of keys) {
let v = o[key]
if (typeof v === "object") {
v = Utils.sortKeys(v)
}
copy[key] = v
}
return copy
}
public static async waitFor(timeMillis: number): Promise<void> {
return new Promise((resolve) => {
window.setTimeout(resolve, timeMillis);
})
}
public static toHumanTime(seconds): string {
seconds = Math.floor(seconds)
let minutes = Math.floor(seconds / 60)
seconds = seconds % 60
let hours = Math.floor(minutes / 60)
minutes = minutes % 60
let days = Math.floor(hours / 24)
hours = hours % 24
if (days > 0) {
return days + "days" + " " + hours + "h"
}
return hours + ":" + Utils.TwoDigits(minutes) + ":" + Utils.TwoDigits(seconds)
}
public static DisableLongPresses() {
// Remove all context event listeners on mobile to prevent long presses
window.addEventListener('contextmenu', (e) => { // Not compatible with IE < 9
if (e.target["nodeName"] === "INPUT") {
return;
}
e.preventDefault();
return false;
}, false);
}
public static OsmChaLinkFor(daysInThePast, theme = undefined): string {
const now = new Date()
const lastWeek = new Date(now.getTime() - daysInThePast * 24 * 60 * 60 * 1000)
const date = lastWeek.getFullYear() + "-" + Utils.TwoDigits(lastWeek.getMonth() + 1) + "-" + Utils.TwoDigits(lastWeek.getDate())
let osmcha_link = `"date__gte":[{"label":"${date}","value":"${date}"}],"editor":[{"label":"mapcomplete","value":"mapcomplete"}]`
if (theme !== undefined) {
osmcha_link = osmcha_link + "," + `"comment":[{"label":"#${theme}","value":"#${theme}"}]`
}
return "https://osmcha.org/?filters=" + encodeURIComponent("{" + osmcha_link + "}")
}
/**
* Deepclone an object by serializing and deserializing it
* @param x
* @constructor
*/
static Clone<T>(x: T): T {
if (x === undefined) {
return undefined;
}
return JSON.parse(JSON.stringify(x));
}
public static ParseDate(str: string): Date {
if (str.endsWith(" UTC")) {
str = str.replace(" UTC", "+00")
}
return new Date(str)
}
public static levenshteinDistance(str1: string, str2: string) {
const track = Array(str2.length + 1).fill(null).map(() =>
Array(str1.length + 1).fill(null));
for (let i = 0; i <= str1.length; i += 1) {
track[0][i] = i;
}
for (let j = 0; j <= str2.length; j += 1) {
track[j][0] = j;
}
for (let j = 1; j <= str2.length; j += 1) {
for (let i = 1; i <= str1.length; i += 1) {
const indicator = str1[i - 1] === str2[j - 1] ? 0 : 1;
track[j][i] = Math.min(
track[j][i - 1] + 1, // deletion
track[j - 1][i] + 1, // insertion
track[j - 1][i - 1] + indicator, // substitution
);
}
}
return track[str2.length][str1.length];
}
private static colorDiff(c0: { r: number, g: number, b: number }, c1: { r: number, g: number, b: number }) {
return Math.abs(c0.r - c1.r) + Math.abs(c0.g - c1.g) + Math.abs(c0.b - c1.b);
}
private static color(hex: string): { r: number, g: number, b: number } {
if (hex.startsWith == undefined) {
console.trace("WUT?", hex)
throw "wut?"
}
if (!hex.startsWith("#")) {
return undefined;
}
if (hex.length === 4) {
return {
r: parseInt(hex.substr(1, 1), 16),
g: parseInt(hex.substr(2, 1), 16),
b: parseInt(hex.substr(3, 1), 16),
}
}
return {
r: parseInt(hex.substr(1, 2), 16),
g: parseInt(hex.substr(3, 2), 16),
b: parseInt(hex.substr(5, 2), 16),
}
}
public static MapToObj<T>(d : Map<string, T>, onValue: ((t:T, key: string) => any) = undefined): object{
const o = {}
d.forEach((value, key) => {
if(onValue !== undefined){
value = onValue(value, key)
}
o[key] = value;
})
return o
}
}