0

I have a dynamic layout within a React Native view - that changes based on provided data for the particular data set. Ie there could be a provided Guide, Inventory, or Observation list that need displaying - but there may just be a combination of one, two or 3 of these things provided within any dataset.

I need to supply conditional styles / display object throughout the view based on the state of each provided data type.

Currently I have a series of checks that return true if the state is populated i.e:

const hasSiteGuide = () => {
  if (!this.isEmpty(this.state.locationSiteGuidePdf)) {
    return true;
  }
}; 

I then have a series of functions that determine how many items are supplied and provide the relevant style - here are the logic checks:

 const layout_full = () => {
  if (hasSiteGuide() && hasInventoryItems() && hasObservations()) {
    return true;
  }
};
const layout_one = () => {
  if (!hasSiteGuide() && !hasInventoryItems() && !hasObservations()) {
    return true;
  }
};

const layout_two = () => {
      if (!hasSiteGuide() || !hasInventoryItems() !hasObservations()) {
        if (hasSiteGuide() || hasInventoryItems()) {
          return true;
        }
      }
    };

the checks are used to display conditional styles in multiple areas - for example:

 <View
              style={[
                layout_full() && RP_Styles.btnWrap,
                layout_three() && RP_Styles.btnWrap_three,
                layout_two() && RP_Styles.btnWrap_two,
                layout_one() && RP_Styles.btnWrap_one,
              ]}>

My question is - i'm sure that there is a better way to do this.. particularly as i'm about to implement a 4th possibility - I was wondering if there is a way that I could use just one function to count how many true statements are in a list and return the relevant condition

ie:

returnTrueCount(hasSiteGuide(), hasInventoryItems(), hasObservations()). - is this possible? Or has anybody got an idea for a better approach please? Thanks very much

isherwood
  • 58,414
  • 16
  • 114
  • 157
Dancer
  • 17,035
  • 38
  • 129
  • 206

2 Answers2

1

If you want do something like this : returnTrueCount(hasSiteGuide(), hasInventoryItems(), hasObservations()) then I think the following solution would would work.

const a = () => true;
const b = () => true;
const c = () => false;
const d = () => true;

function returnTrueCount(...funcs) {
  return funcs.reduce((a, f) => a + +f(), 0);
}

console.log(returnTrueCount(a, b, c, d));
h-sifat
  • 1,455
  • 3
  • 19
1

This worked for me:

    const returnTrueCount = (array, value) => {
      return array.filter((v) => v === value).length;
    };

called with a basic array and the value to check.

Dancer
  • 17,035
  • 38
  • 129
  • 206