token.ts 465 B

12345678910111213141516171819202122
  1. export function estimateTokenLength(input: string): number {
  2. let tokenLength = 0;
  3. for (let i = 0; i < input.length; i++) {
  4. const charCode = input.charCodeAt(i);
  5. if (charCode < 128) {
  6. // ASCII character
  7. if (charCode <= 122 && charCode >= 65) {
  8. // a-Z
  9. tokenLength += 0.25;
  10. } else {
  11. tokenLength += 0.5;
  12. }
  13. } else {
  14. // Unicode character
  15. tokenLength += 1.5;
  16. }
  17. }
  18. return tokenLength;
  19. }