Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,4 @@ dist

# Editor settings
.idea
.vscode
33 changes: 33 additions & 0 deletions src/scalar/text.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { DataType } from '@apache-arrow/esnext-esm';
import test from 'ava';

import { Text } from './text.js';

// eslint-disable-next-line unicorn/no-null
[null, undefined].forEach((v) => {
test(`should set values to empty string when ${v} is passed`, (t) => {
const s = new Text(v);
t.is(s.value, '');
t.is(s.valid, false);
t.true(DataType.isUtf8(s.dataType));
});
});

[
{ value: '', expected: '' },
{ value: 'test string', expected: 'test string' },
{ value: String('new string object'), expected: 'new string object' },
{ value: new Text('new text object'), expected: 'new text object' },
{ value: new TextEncoder().encode('test'), expected: 'test' },
].forEach(({ value, expected }, index) => {
test(`valid strings: '${value}' (${index})`, (t) => {
const s = new Text(value);
t.is(s.valid, true);
t.is(s.value, expected);
t.true(DataType.isUtf8(s.dataType));
});
});

test('should throw when unable to set value', (t) => {
t.throws(() => new Text({ value: {} }), { message: "Unable to set '[object Object]' as Text" });
});
61 changes: 61 additions & 0 deletions src/scalar/text.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { Utf8 as ArrowString } from '@apache-arrow/esnext-esm';

import { Scalar } from './scalar.js';
import { isInvalid, NULL_VALUE } from './util.js';

export class Text implements Scalar<string> {
private _valid = false;
private _value = '';

public constructor(v: unknown) {
this.value = v;
return this;
}

public get dataType() {
return new ArrowString();
}

public get valid(): boolean {
return this._valid;
}

public get value(): string {
return this._value;
}

public set value(value: unknown) {
if (isInvalid(value)) {
this._valid = false;
return;
}

if (typeof value === 'string') {
this._value = value;
this._valid = true;
return;
}

if (value instanceof Uint8Array) {
this._value = new TextDecoder().decode(value);
this._valid = true;
return;
}

if (typeof value!.toString === 'function' && value!.toString !== Object.prototype.toString) {
this._value = value!.toString();
this._valid = true;
return;
}

throw new Error(`Unable to set '${value}' as Text`);
}

public toString() {
if (this._valid) {
return this._value.toString();
}

return NULL_VALUE;
}
}