feat(StringWrapper): add support for JS slice method to string

This commit is contained in:
Lenny
2015-08-30 17:04:15 -07:00
committed by vsavkin
parent bced3aaa17
commit 0808eeaa0c
3 changed files with 48 additions and 1 deletions

View File

@ -94,6 +94,14 @@ class StringWrapper {
return s.startsWith(start);
}
static String slice(String s, [int start = 0, int end]) {
//in JS if start > end an empty string is returned
if(end != null && start > end) {
return "";
}
return s.substring(_startOffset(s, start), _endOffset(s, end));
}
static String substring(String s, int start, [int end]) {
return s.substring(start, end);
}
@ -107,6 +115,21 @@ class StringWrapper {
}
static int compare(String a, String b) => a.compareTo(b);
// JS slice function can take start < 0 which indicates a position relative to
// the end of the string
static int _startOffset(String s, int start) {
int len = s.length;
return start = start < 0 ? math.max(len + start, 0) : math.min(start, len);
}
// JS slice function can take end < 0 which indicates a position relative to
// the end of the string
static int _endOffset(String s, int end) {
int len = s.length;
if (end == null) return len;
return end < 0 ? math.max(len + end, 0) : math.min(end, len);
}
}
class StringJoiner {

View File

@ -151,6 +151,10 @@ export class StringWrapper {
return s.replace(from, replace);
}
static slice<T>(s: string, from: number = 0, to: number = null): string {
return s.slice(from, to === null ? undefined : to);
}
static toUpperCase(s: string): string { return s.toUpperCase(); }
static toLowerCase(s: string): string { return s.toLowerCase(); }