Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move cleanAndTruncate from to Utils #169

Merged
merged 4 commits into from
Nov 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import {Duration} from 'luxon';
import VError from 'verror';

// Max length for free-form description text fields such as issue body
const MAX_TEXT_LENGTH = 1000;

export class Utils {
static urlWithoutTrailingSlashes(url: string): string {
Expand Down Expand Up @@ -116,7 +118,7 @@ export class Utils {
});
}

static toCategoryDetail<EnumType extends {Custom: any}>(
static toCategoryDetail<EnumType extends {Custom: any}>(
enumObject: EnumType & Record<string, any>,
category: string,
categoryMapping: Record<string, string> = {}
Expand All @@ -138,4 +140,28 @@ static toCategoryDetail<EnumType extends {Custom: any}>(
detail: category,
};
}

static cleanAndTruncate(
str?: string,
maxLength?: number
): string | null | undefined {
if (!str) {
return str;
}
const length = maxLength ?? MAX_TEXT_LENGTH;
let result: string;
if (str.length <= length) {
result = str;
} else {
// If the last character is part of a unicode surrogate pair,
// include the next character
const lastChar = str.codePointAt(length - 1) ?? 0;
result =
lastChar > 65535
? str.substring(0, length + 1)
: str.substring(0, length);
}
// eslint-disable-next-line no-control-regex
return result.replace(/\u0000/g, '');
}
}
9 changes: 9 additions & 0 deletions test/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,4 +210,13 @@ describe('parse primary keys', () => {
});
});
});

describe('clean and truncate', () => {
test('should truncate strings', () => {
const str = 'abc123😍\u0000';
expect(sut.Utils.cleanAndTruncate(str)).toEqual('abc123😍');
expect(sut.Utils.cleanAndTruncate(str, 3)).toEqual('abc');
expect(sut.Utils.cleanAndTruncate(str, 7)).toEqual('abc123😍');
});
});
});
Loading