From c8c847415762c9f51f031dcd7d45e51a1bdd5f0f Mon Sep 17 00:00:00 2001 From: Sorrel Bri Date: Wed, 4 Dec 2019 18:13:46 -0800 Subject: [PATCH] add positive phones from add feature to state --- src/reducers/stateReducer.js | 29 +++++++++++++++++++++++- src/reducers/stateReducer.phones.test.js | 28 +++++++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 src/reducers/stateReducer.phones.test.js diff --git a/src/reducers/stateReducer.js b/src/reducers/stateReducer.js index cbe1cc1..a9429bf 100644 --- a/src/reducers/stateReducer.js +++ b/src/reducers/stateReducer.js @@ -4,6 +4,22 @@ const initState = () => { } } +const addPhones = (phones, phone) => { + phone.split('').forEach((graph, index) => { + if (!phones[graph]) phones[graph] = {} + }) + return phones; +} + +const addPositiveFeature = (phones, positivePhone, feature) => { + let node = {} + positivePhone.split('').forEach((graph, index) => { + node = index === 0 ? node = phones[graph] : node = node[graph]; + if (index === positivePhone.split('').length - 1) node.features = {...node.features, [feature]: true} + }) + return phones; +} + const stateReducer = (state, action) => { switch (action.type) { case 'INIT': { @@ -26,7 +42,18 @@ const stateReducer = (state, action) => { case 'ADD_FEATURE': { let newFeature = action.value.feature; - return {...state, features:[...state.features, newFeature]} + let positivePhones = action.value.positivePhones || []; + let negativePhones = action.value.negativePhones || []; + + let newPhoneObject = [ + ...positivePhones, ...negativePhones + ].reduce((phoneObject, phone) => addPhones(phoneObject, phone), state.phones) + + if (positivePhones) positivePhones = positivePhones.reduce( + (phoneObject, positivePhone) => addPositiveFeature(phoneObject, positivePhone, newFeature) + , newPhoneObject); + + return {...state, features:[...state.features, newFeature], phones: newPhoneObject} } default: diff --git a/src/reducers/stateReducer.phones.test.js b/src/reducers/stateReducer.phones.test.js new file mode 100644 index 0000000..76c1ec6 --- /dev/null +++ b/src/reducers/stateReducer.phones.test.js @@ -0,0 +1,28 @@ +import {stateReducer} from './stateReducer'; + +describe('Phones', () => { + const n_phone = {features: {nasal: true}} + const state = { + features: [ + 'nasal' + ], + phones: { n: n_phone } + }; + + + it('phones returned unaltered', () => { + const action = {type: ''}; + expect(stateReducer(state, action)).toBe(state); + }); + + it('feature addition returns new feature list with positive phones updated', () => { + const action = {type: 'ADD_FEATURE', value: {feature: 'anterior', positivePhones: ['n']}}; + expect(stateReducer(state, action)).toEqual( + {...state, + features:[...state.features, action.value.feature], + phones:{...state.phones, n:{...state.phones.n, features: {...state.phones.n.features, anterior: true}}} + } + ) + }) + +}); \ No newline at end of file