-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
43 lines (35 loc) · 1.05 KB
/
index.js
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
var shortenedURLLength = 27;
var ellipsis = '\u2026';
function truncateToTweet(opts) {
var maxTweetMessageLength = 280;
if (!opts || !opts.text) {
throw new Error('No text supplied in opts.');
}
if (opts.maxTweetMessageLength) {
maxTweetMessageLength = opts.maxTweetMessageLength;
}
var truncated = opts.text;
var maxTextLength = maxTweetMessageLength;
var urlDelimiter = ' ';
if (opts.delimiter) {
urlDelimiter = opts.delimiter;
}
if (opts.urlsToAdd && opts.urlsToAdd.length > 0) {
// 20 chars for each url.
maxTextLength -= shortenedURLLength * opts.urlsToAdd.length;
// Space between urls.
maxTextLength -= opts.urlsToAdd.length;
}
if (truncated.length > maxTextLength) {
// Make space for the ellipsis.
var startTruncateAt = maxTextLength - 1;
truncated = truncated.slice(0, startTruncateAt) + ellipsis;
}
if (opts.urlsToAdd) {
opts.urlsToAdd.forEach(function appendURL(url) {
truncated += (urlDelimiter + url);
});
}
return truncated;
}
module.exports = truncateToTweet;