schema.spec.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 * as Data from '../data'
  7. import * as Schema from '../schema'
  8. function Field(values: any[]): Data.Field {
  9. return {
  10. isDefined: true,
  11. str: row => '' + values[row],
  12. int: row => +values[row] || 0,
  13. float: row => +values[row] || 0,
  14. bin: row => null,
  15. presence: row => Data.ValuePresence.Present,
  16. areValuesEqual: (rowA, rowB) => values[rowA] === values[rowB],
  17. stringEquals: (row, value) => '' + values[row] === value,
  18. toStringArray: (startRow, endRowExclusive, ctor) => {
  19. const count = endRowExclusive - startRow;
  20. const ret = ctor(count) as any;
  21. for (let i = 0; i < count; i++) { ret[i] = values[startRow + i]; }
  22. return ret;
  23. },
  24. toNumberArray: (startRow, endRowExclusive, ctor) => {
  25. const count = endRowExclusive - startRow;
  26. const ret = ctor(count) as any;
  27. for (let i = 0; i < count; i++) { ret[i] = +values[startRow + i]; }
  28. return ret;
  29. }
  30. }
  31. }
  32. class Category implements Data.Category {
  33. getField(name: string) { return this.fields[name]; }
  34. constructor(public rowCount: number, private fields: any) { }
  35. }
  36. class Block implements Data.Block {
  37. constructor(public categories: { readonly [name: string]: Data.Category }, public header?: string) { }
  38. }
  39. const testBlock = new Block({
  40. 'atoms': new Category(2, {
  41. x: Field([1, 2]),
  42. name: Field(['C', 'O'])
  43. })
  44. });
  45. namespace TestSchema {
  46. export const atoms = { x: Schema.Field.float(), name: Schema.Field.str() }
  47. export const schema = { atoms }
  48. }
  49. describe('schema', () => {
  50. const data = Schema.apply(TestSchema.schema, testBlock);
  51. it('property access', () => {
  52. const { x, name } = data.atoms;
  53. expect(x.value(0)).toBe(1);
  54. expect(name.value(1)).toBe('O');
  55. });
  56. it('toArray', () => {
  57. const ret = data.atoms.x.toArray(0, 2, (s) => new Int32Array(s))!;
  58. expect(ret.length).toBe(2);
  59. expect(ret[0]).toBe(1);
  60. expect(ret[1]).toBe(2);
  61. })
  62. });