deno.land / std@0.167.0 / collections / join_to_string.ts

join_to_string.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
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.// This module is browser compatible.
/** * Options for joinToString */export type JoinToStringOptions = { separator?: string; prefix?: string; suffix?: string; limit?: number; truncated?: string;};
/** * Transforms the elements in the given array to strings using the given * selector. Joins the produced strings into one using the given `separator` * and applying the given `prefix` and `suffix` to the whole string afterwards. * If the array could be huge, you can specify a non-negative value of `limit`, * in which case only the first `limit` elements will be appended, followed by * the `truncated` string. Returns the resulting string. * * @example * ```ts * import { joinToString } from "https://deno.land/std@$STD_VERSION/collections/join_to_string.ts"; * import { assertEquals } from "https://deno.land/std@$STD_VERSION/testing/asserts.ts"; * * const users = [ * { name: "Kim" }, * { name: "Anna" }, * { name: "Tim" }, * ]; * * const message = joinToString(users, (it) => it.name, { * suffix: " are winners", * prefix: "result: ", * separator: " and ", * limit: 1, * truncated: "others", * }); * * assertEquals(message, "result: Kim and others are winners"); * ``` */export function joinToString<T>( array: readonly T[], selector: (el: T) => string, { separator = ",", prefix = "", suffix = "", limit = -1, truncated = "...", }: Readonly<JoinToStringOptions> = {},): string { let result = "";
let index = -1; while (++index < array.length) { const el = array[index];
if (index > 0) { result += separator; }
if (limit > -1 && index >= limit) { result += truncated; break; }
result += selector(el); }
result = prefix + result + suffix;
return result;}
std

Version Info

Tagged at
a year ago