Transformations: Fix bug in convert fields boolean to number (#60277)

* fix bug in convert fields boolean to number

* check for string outside of loop
This commit is contained in:
Brendan O'Handley 2022-12-14 13:00:10 -05:00 committed by GitHub
parent d5d07894b1
commit 286af5a53b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 32 additions and 3 deletions

View File

@ -121,6 +121,26 @@ it('can convert strings with commas to numbers', () => {
});
});
it('converts booleans to numbers', () => {
const options = { targetField: 'booleans', destinationType: FieldType.number };
const stringyNumbers = {
name: 'booleans',
type: FieldType.boolean,
values: new ArrayVector([true, false]),
config: {},
};
const numbers = convertFieldType(stringyNumbers, options);
expect(numbers).toEqual({
name: 'booleans',
type: FieldType.number,
values: new ArrayVector([1, 0]),
config: {},
});
});
describe('field convert types transformer', () => {
beforeAll(() => {
mockTransformationsRegistry([convertFieldTypeTransformer]);

View File

@ -141,10 +141,19 @@ export function fieldToTimeField(field: Field, dateFormat?: string): Field {
function fieldToNumberField(field: Field): Field {
const numValues = field.values.toArray().slice();
const valuesAsStrings = numValues.some((v) => typeof v === 'string');
for (let n = 0; n < numValues.length; n++) {
let toBeConverted = numValues[n];
if (valuesAsStrings) {
// some numbers returned from datasources have commas
// strip the commas, coerce the string to a number
const number = +numValues[n].replace(/,/g, '');
toBeConverted = toBeConverted.replace(/,/g, '');
}
const number = +toBeConverted;
numValues[n] = Number.isFinite(number) ? number : null;
}