fixed.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /**
  2. * Copyright (c) 2017 molio contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. import { Column, ColumnType, createAndFillArray } from '../../column'
  7. import { trimStr, Tokens } from '../tokenizer'
  8. import { parseIntSkipLeadingWhitespace, parseFloatSkipLeadingWhitespace } from '../number-parser'
  9. import StringPool from '../../../../utils/short-string-pool'
  10. export default function FixedColumnProvider(lines: Tokens) {
  11. return function<T extends ColumnType>(offset: number, width: number, type: T) {
  12. return FixedColumn(lines, offset, width, type);
  13. }
  14. }
  15. export function FixedColumn<T extends ColumnType>(lines: Tokens, offset: number, width: number, type: T): Column<T['@type']> {
  16. const { data, indices, count: rowCount } = lines;
  17. const { kind } = type;
  18. const pool = kind === 'pooled-str' ? StringPool.create() : void 0;
  19. const value: Column<T['@type']>['value'] = kind === 'str' ? row => {
  20. let s = indices[2 * row] + offset, le = indices[2 * row + 1];
  21. if (s >= le) return '';
  22. let e = s + width;
  23. if (e > le) e = le;
  24. return trimStr(data, s, e);
  25. } : kind === 'pooled-str' ? row => {
  26. let s = indices[2 * row] + offset, le = indices[2 * row + 1];
  27. if (s >= le) return '';
  28. let e = s + width;
  29. if (e > le) e = le;
  30. return StringPool.get(pool!, trimStr(data, s, e));
  31. } : kind === 'int' ? row => {
  32. const s = indices[2 * row] + offset;
  33. if (s > indices[2 * row + 1]) return 0;
  34. return parseIntSkipLeadingWhitespace(data, s, s + width);
  35. } : row => {
  36. const s = indices[2 * row] + offset;
  37. if (s > indices[2 * row + 1]) return 0;
  38. return parseFloatSkipLeadingWhitespace(data, s, s + width);
  39. };
  40. return {
  41. isDefined: true,
  42. rowCount,
  43. value,
  44. isValueDefined: row => true,
  45. toArray: params => createAndFillArray(rowCount, value, params),
  46. stringEquals: (row, v) => value(row) === v,
  47. areValuesEqual: (rowA, rowB) => value(rowA) === value(rowB)
  48. };
  49. }