Home > OS >  Returning multiple integers in if-statement javascript/react
Returning multiple integers in if-statement javascript/react

Time:02-19

Im trying to do an if statement that maps a string to a number.

I have a bunch of documents that have a string and a number attached to it. The string "soccer" is attached to numbers 12, 13, 14, 15, 16, 17, 18. My if statement below only allows me to pick the document "soccer" with 12 attached to it.

For example:

if(a === 'soccer') {
   return 12
}

So everytime soccer is selected, it should pick out all the "soccer" doc options with 12. This works fine but wanted to pick out the "soccer" docs that have the other numbers aswell. Is there a way to return a range of integers 12-18 in my if statement? or even examples with >= 12/ <=12

fake examples:

if(a === 'soccer') {
       return > 12
    }
if(a === 'soccer') {
       return 12 - 18
    }

Clearly those dont work but i wanted to know if there was a better way to solve that issue.

Edit: I've also tried using an array but that doesnt seem to print those numbers individually. So my value wont be [12], [13], [14], [15], [16], [17], [18] but instead [12, 13, 14, 15, 16, 17, 18]

ex.

const numRange = Array.from({ length: 7 }, (v, i) => i   12);

if (a === 'soccer') {
          return numRange;
        }

edit #2: A DIFFERENT PERSPECTIVE So initially 'a' is an object in docs.

docs: {
     0: {{ a:1}}
     1: {{ a:2}}
     }

"a" is represented by a number, but i had to convert that number into a string(which are represented by the sports).

ex.

if (a) {
        if (a < 11) {
          return 'Volleyball;
        } if (a < 18) {
          return 'soccer';
        } 
        return 'Football';
      }

Now im trying to filter these docs. Using >=, <=, = to filter "a" which is a number but represented now as a string. So my solution was to have functions that converts "a" into a string and "a" in number aswell. So i have this.

    if (typeof a === 'number') {
        if (a < 11) {
              return 'Volleyball';
            } if (a < 18) {
              return 'Soccer';
            } 
            return 'Football';
      }

if (typeof a === 'string') {
        if (a === 'Volleyball') {
          return 11;
         //which should be 0-11 to match the function above
        }
        if (d === 'Soccer') {
          return 18;
         //which should be 12-18 to match the function above
        }
        if (d === 'Football') {
          return 19
         //which should be >19 to match the function above
        }
      }

These functions work but are wonky because they arent matching each other. How can i rewrite both or one to respresent the other in an opposite way.

Thank you

CodePudding user response:

Updated Answer

After you've updated your question I've got a better impression of what you are trying to achieve.

There is no native data type in JavaScript that represents ranges. But you can define your own structure to represent boundaries. You can even use undefined to represent open ranges.

const ranges = {
  volleyball: { min: undefined, max: 10 },
  soccer: { min: 11, max: 17 }
};

Given your documents look like this.

const documents = {
  0: { a: 14 },
  1: { a: 13 },
  3: { a: -2 }
  // ...
};

You can then utilize the ranges to write both of the functions you are looking for.

function toSport(doc) {
  const entries = Object.entries(ranges);
  for (const [sport, range] of entries) {
    const withinUpperBound = range.max === undefined || doc.a <= range.max;
    const withinLowerBound = range.min === undefined || doc.a >= range.min;

    if (withinUpperBound && withinLowerBound) {
      return sport;
    }
  }

  return undefined;
}

function toRange(sport) {
  return ranges[sport];
}

Have a look into the sandbox to see the updated code.

Previous Answer

As I understood, you start with something like:

const documents = [
    { key: "soccer", value: 12 },
    { key: "soccer", value: 13 },
    { key: "soccer", value: 14 },
    { key: "soccer", value: 15 },
    { key: "soccer", value: 16 },
    { key: "soccer", value: 17 },
    { key: "soccer", value: 18 },
    { key: "tennis", value: 19 },
    { key: "tennis", value: 20 }
    // ...
]

If my assumption is correct your function could look like this:

function getDocumentValues(key) {
    // Loop over all documents
    return documents.reduce((accumulator, doc) => {
        // If the current document doesn't match, proceed by returning previously accumulated values
        if (doc.key !== key) {
            return accumulator;
        }

        // Return the previous accumulator plus the matched number. This will be the accumulator for the next iteration.
        return [
            ...accumulator,
            doc.value
        ]
    }, []) // we start with an empty accumulator
}

Let me know if my assumptions are correct and feel free to give us more information if not.

I've made the code available here: https://codesandbox.io/s/tender-moon-e7tswi?file=/src/index.js

CodePudding user response:

So from what I've understood, what you have initially is something like this:

const data = {
  docs: {
    0: { a: 1 },
    1: { a: 2 },
  }
};

Where a can be either a number or a string, and I assume you would want to maintain the value assigned to a (in your example 1 and 2) and the original keys 0 and 1.

So in order to do this you need the store the converted values in order to be able to convert "both ways". Now obviously this will only work if a is only numbers in the beginning. If there's the possibility of it starting as a string then how to tackle the situation.

This would be my approach:

const documents = [];

// This first call will change your `a` to strings
convertDocs(data.docs);

// This second call will change your `a` to numbers like the original
convertDocs(data.docs);

function convertDocs(docs) {
  const keys = Object.keys(docs);

  for (const mainKey of keys) {
    // returning { a: 1 }
    const value = docs[mainKey];
  
    // returning a
    const key = Object.keys(value)[0];
    const converted = convertKey(key, mainKey);

    docs[mainKey] = { [converted]: value[key] };
  }
}

function convertKey(key, mainKey) {
  const isNumber = !isNaN(key);

  return isNumber ? convertFromNumber(key, mainKey) : convertFromString(key, mainKey);
}

function convertFromNumber(key, mainKey) {
  if (key < 11) {
    documents.push({ key, mainKey, value: "Volleyball" });
    return "Volleyball";
  }

  if (key < 18) {
    documents.push({ key, mainKey, value: "Soccer" });
    return "Soccer";
  }

  // ...etc
}

function convertFromString(key, mainKey) {
  const index = documents.findIndex(doc => doc.mainKey === mainKey && doc.value === key);
  const converted = documents[index].key;
  
  // This is to remove from the array, now it depends if this makes sense for your use case
  documents.splice(index, 1);

  return converted;
}

If this is not what you need, I hope it helped you reach your end goal

  • Related