string.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /**
  2. * This file is part of Threema Web.
  3. *
  4. * Threema Web is free software: you can redistribute it and/or modify it
  5. * under the terms of the GNU Affero General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or (at
  7. * your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful, but
  10. * WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  12. * General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Affero General Public License
  15. * along with Threema Web. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. export class StringService {
  18. public byteChunk(str: string, byteLength: number, offset: number = null): string[] {
  19. let chars = [...str];
  20. let chunks = [''];
  21. let currentChunkSize = 0;
  22. let chunkIndex = 0;
  23. let offsetChars = [' ', '\r', '\n', '\t', '.'];
  24. let lastSeparator = -1;
  25. chars.forEach ((charString: string) => {
  26. let length = Buffer.byteLength(charString, 'utf8');
  27. if (offset !== null) {
  28. if (offsetChars.indexOf(charString) > -1) {
  29. lastSeparator = currentChunkSize + 1;
  30. }
  31. }
  32. if (currentChunkSize + length > byteLength) {
  33. let appendNewChunk = true;
  34. if (lastSeparator > -1) {
  35. // check if sepeator in offset
  36. if (currentChunkSize - lastSeparator <= offset
  37. && chunks.length >= 1) {
  38. // create new chunk with existing data
  39. chunks.push(chunks[chunkIndex].substr(lastSeparator).trim());
  40. // modify old chunk
  41. chunks[chunkIndex] = chunks[chunkIndex].substr(0, lastSeparator).trim();
  42. appendNewChunk = false;
  43. currentChunkSize -= lastSeparator;
  44. chunkIndex++;
  45. lastSeparator = -1;
  46. }
  47. }
  48. if (appendNewChunk) {
  49. chunkIndex++;
  50. currentChunkSize = 0;
  51. // create a new chunk
  52. chunks.push('');
  53. }
  54. }
  55. chunks[chunkIndex] = (chunks[chunkIndex] + charString);
  56. currentChunkSize += length;
  57. });
  58. return chunks;
  59. }
  60. }