-
Notifications
You must be signed in to change notification settings - Fork 6.8k
Expand file tree
/
Copy pathstring-array.ts
More file actions
40 lines (37 loc) · 1.34 KB
/
string-array.ts
File metadata and controls
40 lines (37 loc) · 1.34 KB
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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* Coerces a value to an array of trimmed non-empty strings.
* Any input that is not an array, `null` or `undefined` will be turned into a string
* via `toString()` and subsequently split with the given separator.
* `null` and `undefined` will result in an empty array.
* This results in the following outcomes:
* - `null` -> `[]`
* - `[null]` -> `["null"]`
* - `["a", "b ", " "]` -> `["a", "b"]`
* - `[1, [2, 3]]` -> `["1", "2,3"]`
* - `[{ a: 0 }]` -> `["[object Object]"]`
* - `{ a: 0 }` -> `["[object", "Object]"]`
*
* Useful for defining CSS classes or table columns.
* @param value the value to coerce into an array of strings
* @param separator split-separator if value isn't an array
*/
export function coerceStringArray(value: unknown, separator: string | RegExp = /\s+/): string[] {
const result = [];
if (value != null) {
const sourceValues = Array.isArray(value) ? value : String(value).split(separator);
for (const sourceValue of sourceValues) {
const trimmedString = String(sourceValue).trim();
if (trimmedString) {
result.push(trimmedString);
}
}
}
return result;
}