Skip to content

Commit

Permalink
[ML] Fix getNestedProperty for falsey values.
Browse files Browse the repository at this point in the history
  • Loading branch information
walterra committed Mar 9, 2020
1 parent 7b8af7f commit 760ae8a
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 1 deletion.
70 changes: 70 additions & 0 deletions x-pack/plugins/transform/common/utils/object_utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import { getNestedProperty } from './object_utils';

describe('object_utils', () => {
test('getNestedProperty()', () => {
const testObj = {
the: {
nested: {
value: 'the-nested-value',
},
},
};

const falseyObj = {
the: {
nested: {
value: false,
},
other_nested: {
value: 0,
},
},
};

const test1 = getNestedProperty(testObj, 'the');
expect(typeof test1).toBe('object');
expect(Object.keys(test1)).toStrictEqual(['nested']);

const test2 = getNestedProperty(testObj, 'the$');
expect(typeof test2).toBe('undefined');

const test3 = getNestedProperty(testObj, 'the$', 'the-default-value');
expect(typeof test3).toBe('string');
expect(test3).toBe('the-default-value');

const test4 = getNestedProperty(testObj, 'the.neSted');
expect(typeof test4).toBe('undefined');

const test5 = getNestedProperty(testObj, 'the.nested');
expect(typeof test5).toBe('object');
expect(Object.keys(test5)).toStrictEqual(['value']);

const test6 = getNestedProperty(testObj, 'the.nested.vaLue');
expect(typeof test6).toBe('undefined');

const test7 = getNestedProperty(testObj, 'the.nested.value');
expect(typeof test7).toBe('string');
expect(test7).toBe('the-nested-value');

const test8 = getNestedProperty(testObj, 'the.nested.value.doesntExist');
expect(typeof test8).toBe('undefined');

const test9 = getNestedProperty(testObj, 'the.nested.value.doesntExist', 'the-default-value');
expect(typeof test9).toBe('string');
expect(test9).toBe('the-default-value');

const test10 = getNestedProperty(falseyObj, 'the.nested.value');
expect(typeof test10).toBe('boolean');
expect(test10).toBe(false);

const test11 = getNestedProperty(falseyObj, 'the.other_nested.value');
expect(typeof test11).toBe('number');
expect(test11).toBe(0);
});
});
6 changes: 5 additions & 1 deletion x-pack/plugins/transform/common/utils/object_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,9 @@ export const getNestedProperty = (
accessor: string,
defaultValue?: any
) => {
return accessor.split('.').reduce((o, i) => o?.[i], obj) || defaultValue;
const value = accessor.split('.').reduce((o, i) => o?.[i], obj);

if (value === undefined) return defaultValue;

return value;
};

0 comments on commit 760ae8a

Please sign in to comment.