TravBot-v3/src/core/lib.ts

62 lines
1.9 KiB
TypeScript
Raw Normal View History

// Library for pure functions
2020-12-15 01:44:28 +00:00
/**
* Pluralises a word and chooses a suffix attached to the root provided.
* - pluralise("credit", "s") = credit/credits
* - pluralise("part", "ies", "y") = party/parties
* - pluralise("sheep") = sheep
2020-12-15 01:44:28 +00:00
*/
export function pluralise(value: number, word: string, plural = "", singular = "", excludeNumber = false): string {
let result = excludeNumber ? "" : `${value} `;
2020-12-15 01:44:28 +00:00
if (value === 1) result += word + singular;
else result += word + plural;
2020-12-15 01:44:28 +00:00
return result;
}
/**
* Pluralises a word for changes.
* - (-1).pluraliseSigned() = '-1 credits'
* - (0).pluraliseSigned() = '+0 credits'
* - (1).pluraliseSigned() = '+1 credit'
2020-12-15 01:44:28 +00:00
*/
export function pluraliseSigned(
value: number,
word: string,
plural = "",
singular = "",
excludeNumber = false
): string {
const sign = value >= 0 ? "+" : "";
return `${sign}${pluralise(value, word, plural, singular, excludeNumber)}`;
2020-12-15 01:44:28 +00:00
}
export function replaceAll(text: string, before: string, after: string): string {
while (text.indexOf(before) !== -1) text = text.replace(before, after);
return text;
2020-12-15 01:44:28 +00:00
}
export function toTitleCase(text: string): string {
return text.replace(/([^\W_]+[^\s-]*) */g, (txt) => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase());
2020-12-15 01:44:28 +00:00
}
/** Returns a random element from this array. */
export function random<T>(array: T[]): T {
return array[Math.floor(Math.random() * array.length)];
2020-12-15 01:44:28 +00:00
}
/**
* Splits up this array into a specified length.
* `$([1,2,3,4,5,6,7,8,9,10]).split(3)` = `[[1,2,3],[4,5,6],[7,8,9],[10]]`
*/
export function split<T>(array: T[], lengthOfEachSection: number): T[][] {
const amountOfSections = Math.ceil(array.length / lengthOfEachSection);
const sections = new Array<T[]>(amountOfSections);
2020-12-15 01:44:28 +00:00
for (let index = 0; index < amountOfSections; index++)
sections[index] = array.slice(index * lengthOfEachSection, (index + 1) * lengthOfEachSection);
2020-12-15 01:44:28 +00:00
return sections;
2020-12-15 01:44:28 +00:00
}