Skip to content

Commit 244d8d5

Browse files
author
Esben Sparre Andreasen
committed
JS: introduce truncate utility
1 parent 2565b35 commit 244d8d5

3 files changed

Lines changed: 15 additions & 1 deletion

File tree

javascript/ql/src/semmle/javascript/Util.qll

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,14 @@ string pluralize(string noun, int n) {
2323
result = noun
2424
else
2525
result = noun + "s"
26-
}
26+
}
27+
28+
/**
29+
* Gets `str` or a truncated version of `str` with `explanation` appended if its length exceeds `maxLength`.
30+
*
31+
* For example, the truncation of `"long_string"` for `maxLength = 5` and explanation `" ..."` is `"long_ ..."`.
32+
*/
33+
bindingset[str, maxLength, explanation]
34+
string truncate(string str, int maxLength, string explanation) {
35+
if str.length() > maxLength then result = str.prefix(maxLength) + explanation else result = str
36+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
| y | | X | XX | XXy |
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import semmle.javascript.Util
2+
3+
select truncate("X", 0, "y"), truncate("", 2, "y"), truncate("X", 2, "y"), truncate("XX", 2, "y"), truncate("XXX", 2, "y")

0 commit comments

Comments
 (0)