Created
November 24, 2023 15:47
-
-
Save tolotrasmile/fdd7703b9c5effb0be671badcbfe3c07 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const enum PadOrder { | |
Ascending, | |
Descending, | |
} | |
export function pad( | |
value: string, | |
paddingChar: string, | |
totalLength: number, | |
accumulator: (p: string, v: string) => string | |
): string { | |
if (paddingChar && paddingChar.length > 0) { | |
while (value.length < totalLength) { | |
value = accumulator(paddingChar, value) | |
} | |
} | |
return value | |
} | |
export function padLeft( | |
value: string, | |
paddingChar: string, | |
totalLength: number | |
): string { | |
return pad(value, paddingChar, totalLength, (p, v) => p + v) | |
} | |
export function padRight( | |
value: string, | |
paddingChar: string, | |
totalLength: number | |
): string { | |
return pad(value, paddingChar, totalLength, (p, v) => v + p) | |
} | |
export function getLeftPaddedNumbers( | |
leastNumber: number, | |
greatestNumber: number, | |
order: PadOrder | |
): string[] { | |
switch (order) { | |
case PadOrder.Ascending: | |
return getLeftPaddedNumbersAscending(leastNumber, greatestNumber) | |
case PadOrder.Descending: | |
return getLeftPaddedNumbersDescending(leastNumber, greatestNumber) | |
} | |
} | |
export function getLeftPaddedNumbersAscending( | |
leastNumber: number, | |
greatestNumber: number | |
): string[] { | |
const result: string[] = [] | |
const length = greatestNumber.toString().length | |
for (let i = leastNumber; i <= greatestNumber; i++) { | |
result.push(padLeft(i.toString(), '0', length)) | |
} | |
return result | |
} | |
export function getLeftPaddedNumbersDescending( | |
leastNumber: number, | |
greatestNumber: number | |
): string[] { | |
const result: string[] = [] | |
const length = greatestNumber.toString().length | |
for (let i = greatestNumber; i >= leastNumber; i--) { | |
result.push(padLeft(i.toString(), '0', length)) | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment