-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.dart
79 lines (67 loc) · 2.45 KB
/
utils.dart
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
// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// Generic utility functions.
/** Invokes [callback] and returns how long it took to execute in ms. */
num time(callback()) {
final watch = new Stopwatch();
watch.start();
callback();
watch.stop();
return watch.elapsedInMs();
}
/** Turns [name] into something that's safe to use as a file name. */
String sanitize(String name) => name.replaceAll(':', '_').replaceAll('/', '_');
/** Returns the number of times [search] occurs in [text]. */
int countOccurrences(String text, String search) {
int start = 0;
int count = 0;
while (true) {
start = text.indexOf(search, start);
if (start == -1) break;
count++;
// Offsetting by search length means overlapping results are not counted.
start += search.length;
}
return count;
}
/** Repeats [text] [count] times, separated by [separator] if given. */
String repeat(String text, int count, [String separator]) {
// TODO(rnystrom): Should be in corelib.
final buffer = new StringBuffer();
for (int i = 0; i < count; i++) {
buffer.add(text);
if ((i < count - 1) && (separator !== null)) buffer.add(separator);
}
return buffer.toString();
}
/** Removes up to [indentation] leading whitespace characters from [text]. */
String unindent(String text, int indentation) {
var start;
for (start = 0; start < Math.min(indentation, text.length); start++) {
// Stop if we hit a non-whitespace character.
if (text[start] != ' ') break;
}
return text.substring(start);
}
/** Sorts the map by the key, doing a case-insensitive comparison. */
List orderByName(Map<String, Dynamic> map) {
// TODO(rnystrom): it'd be nice to have this in corelib.
List keys = map.getKeys();
keys.sort((x, y) => x.toUpperCase().compareTo(y.toUpperCase()));
final values = [];
for (var k in keys) {
values.add(map[k]);
}
return values;
}
/**
* Joins [items] into a single, comma-separated string using [conjunction].
* E.g. `['A', 'B', 'C']` becomes `"A, B, and C"`.
*/
String joinWithCommas(List<String> items, [String conjunction = 'and']) {
if (items.length == 1) return items[0];
if (items.length == 2) return "${items[0]} $conjunction ${items[1]}";
return Strings.join(items.getRange(0, items.length - 1), ', ') +
', $conjunction ' + items[items.length - 1];
}