diff --git a/src/scripts/choices.ts b/src/scripts/choices.ts index 73c8308..d2f0d5e 100644 --- a/src/scripts/choices.ts +++ b/src/scripts/choices.ts @@ -46,6 +46,7 @@ import { isType, sortByScore, strToEl, + parseCustomProperties, } from './lib/utils'; import { defaultState } from './reducers'; import Store from './store/store'; @@ -290,7 +291,9 @@ class Choices implements Choices { disabled: option.disabled || option.parentNode.disabled, placeholder: option.value === '' || option.hasAttribute('placeholder'), - customProperties: this._parseCustomProperties(option.dataset['customProperties']), + customProperties: parseCustomProperties( + option.dataset.customProperties, + ), }); }); } @@ -2429,17 +2432,6 @@ class Choices implements Choices { return null; } - - _parseCustomProperties(customProperties): any { - if(typeof customProperties !== 'undefined') { - try { - return JSON.parse(customProperties) - } catch(e) { - return customProperties - } - } - return {} - } } export default Choices; diff --git a/src/scripts/lib/utils.test.ts b/src/scripts/lib/utils.test.ts index b618237..022a2cf 100644 --- a/src/scripts/lib/utils.test.ts +++ b/src/scripts/lib/utils.test.ts @@ -15,6 +15,7 @@ import { sanitise, sortByAlpha, sortByScore, + parseCustomProperties, } from './utils'; describe('utils', () => { @@ -256,4 +257,25 @@ describe('utils', () => { expect(output).to.deep.equal(['baz']); }); }); + + describe('_parseCustomProperties', () => { + describe('when custom properties are valid json', () => { + it('returns the properties as object', () => { + const customProperties = '{"description": "foo", "bar": "foo"}'; + const result = { description: 'foo', bar: 'foo' }; + + const value = parseCustomProperties(customProperties); + expect(value).to.eql(result); + }); + }); + describe('when custom properties are undefined', () => { + it('returns an empty object', () => { + const customProperties = undefined; + const result = {}; + + const value = parseCustomProperties(customProperties); + expect(value).to.eql(result); + }); + }); + }); }); diff --git a/src/scripts/lib/utils.ts b/src/scripts/lib/utils.ts index e34b737..ba587bc 100644 --- a/src/scripts/lib/utils.ts +++ b/src/scripts/lib/utils.ts @@ -180,3 +180,15 @@ export const diff = ( return aKeys.filter((i) => bKeys.indexOf(i) < 0); }; + +export const parseCustomProperties = (customProperties): any => { + if (typeof customProperties !== 'undefined') { + try { + return JSON.parse(customProperties); + } catch (e) { + return customProperties; + } + } + + return {}; +};