jeudi 5 décembre 2019

How do I access a variable, created outside of an IF/ELSE scope, update it in the IF statement, and access that update in the ELSE statement?

Sorry, I'm not sure how else to word my question and, as such, am having a hard time finding any relevant solutions.

The Project

I'm creating a script that cleans batches of raw text from an Excel file...

enter image description here

...gathers each "cell" into an array, and pushes each "person" into a new array while attaching their respective bits of info to each person. The text itself contains things like first names, last names, and cities. Some people have multiple cities on new lines...

enter image description here

*All info is randomly generated and any real life comparisons are purely coincidental

The Problem

I'm able to clean the text up and dump the contents of each line to an array without any issues but the problem comes when I try to push "lines" that only have a city to the most recent "full person". For instance:

John Doe has lived in Anchorage, AK; New York, NY; and Des Moines, IA.

New York, NY and Des Moines, IA each end up on their own separate lines with each city being the only item in an array.

When I go to push a city into the new array I get:

Uncaught TypeError: Cannot read property 'city' of undefined

The Code

Here's the code I'm working with. Specifically, my issue is with the mergeSort(a) function:

function sanitize(rawData) { // Accessed from event handler on line 70
  // Split the raw data into "lines"
  const splitByLine = rawData.split("\n");

  // Split each line into an array by "tabs"
  const splitByTab = splitByLine.map(line => {
    return line.split("\t");
  });

  // Trim each array cell and remove any empty cells
  const cleaned = splitByTab.map(function(item) {
    const scrubbed = item.map(chunk => {
      return chunk.trim();
    });

    const trimmed = scrubbed.filter(chunk => {
      return chunk !== "";
    });

    return trimmed;
  });

  // Remove any empty arrays
  const droppedEmpties = cleaned.filter(arrayItem => {
    return arrayItem.length > 0;
  });

  mergeSort(droppedEmpties); // Line 32
}

// Sort cities lived in for each person
function mergeSort(a) {
  console.log(a);

  function Person(firstName, lastName, gender, city, birthday) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.gender = gender;
    this.city = [city];
    this.birthday = birthday;
  }

  const people = [];

  let toggleID = 0;

  a.forEach(person => {
    // If the entry is likely to be a person...
    if (person.length > 1) {
      // Set the ID for the last known person
      toggleID = a.indexOf(person);

      let newPerson = new Person(
        person[0], // firstName
        person[1], // lastName
        person[2], // gender
        person[3], // city
        person[4] // birthday
      );

      people.push(newPerson);
      console.log(people[toggleID]);
    } else { // ...Else assume it's a city and push to the previous person.
      people[toggleID].city.push(person[0]); // THROWS ERROR: Cannot read property of 'city' of undefined
    }
  });
}

// Get form submission
document.getElementById("my-form").addEventListener("submit", function(e) {
  e.preventDefault();
  const textarea = document.getElementById("my-textarea");
  const rawData = textarea.value;
  sanitize(rawData); // Line 1
});
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <form id="my-form">
    <button>Submit</button>
    <textarea id="my-textarea" cols="150" rows="15">
Cynthia Hogsett Female  Grand Rapids, MI        12/6/1983
Jacqueline      Crosborne       Female  Syracuse, NY    3/19/1984
Ricky   Johnson Male    Tioga, ND       4/6/1972
Jimmy   Jessup  Male    Ames, IA        10/27/1993
            Williston, ND       
            Grand Forks, ND     
Andrew  Manchez Male    El Paso, TX     3/1/2001
Sarah   Smith   Female  Seattle, WA     7/19/1981
Esteban Faccin  Male    Gilbert, AZ     1/30/1973
            Spokane, WA 
            Minot, ND   
            James Town, CO      
                </textarea>
  </form>
  <script src="main.js"></script>
</body>

</html>

My guess is that, although I'm defining let toggleID outside of the IF/ELSE scope, I can't mutate the value in the IF statement and access that updated value from within the ELSE statement.

Thanks in advance for any insight!

Aucun commentaire:

Enregistrer un commentaire