Problem when ordering queries entered by the user

3

I am creating a program that captures data on a page using JavaScript. I inserted the QuickSort sorting method for general queries, however, only one query is displayed on the screen even if I entered more than one.

This is my code:

var menu;
var opccon;
var opccan;
var activo = [];
var activo = new Array();
var nombre = [];
var x = 0;
var y = 0;
var i = 0;
var xnum;
var Tr = 1;
var num = [];
var num = new Array();
var renglon = 0;
var encontro = 0;
var min = 0;

do {
  menu = prompt("MENU PRINCIPAL \n 1.-Captura \n2.-Consulta \n3.-Actualizaciones \n4.-Cancelaciones \n5.-Salida");
  if (menu == 1) {
    activo = 0;
    xnum = prompt("Ingrese su Numero contable");
    for (x = 1; x <= renglon; x++) {
      if (xnum == num[x]) {
        encontro = 1;
      }
    }
    if (encontro == 0) {
      renglon = 0;
      for (x = 1; x <= renglon; x++) {
        if (num[x] != null) {
          renglon = renglon + 1;
        }
      }
      renglon = renglon + 1;
      num[renglon] = xnum;
      nombre[renglon] = prompt("Ingrese su NOMBRE");
      activo[renglon] = 1;
    }
    if (encontro == 1) {
      alert("Registro ya existente intente con otro registro");
    }
  }
  
  if (menu == 2) {
    do {
      opccon = prompt("MENU PRINCIPAL \n 1.-Registro \n2.-General \n3.-Regresar");
      if (opccon == 1) {
        encontro;
        xnum = prompt("Ingresa el numero de cuenta que desea encontrar")
        for (x = 1; x <= renglon; x++) {
          if (xnum == num[x]) {
            encontro = 1;
            alert("Nombre " + nombre[x] + " Numero de cuenta " + num[x]);
          }
        }
        if (encontro == 0) {
          alert("Disculpe el numero que ingreso no esta en la base de datos ");
        }
      }

      if (opccon == 2) {
        function stableSort(v, f) {
          if (f === undefined) {
            f = function(a, b) {
              a = "" + a;
              b = "" + b;
              return a < b ? -1 : (a > b ? 1 : 0);
            }
          }
          var dv = [];
          for (var i = 0; i < v.length; i++) {
            dv[i] = [v[i], i];
          }
          dv.sort(function(a, b) {
            return f(a[0], b[0]) || (a[1] - b[1]);
          });
          for (var i = 0; i < v.length; i++) {
            v[i] = dv[i][0];
          }
        }
        num.sort();
        for (x = 1; x <= renglon; x++) {
          alert("Clave: " + num + "\n" + "Nombre: " + nombre);
        }
      }
    } while (opccon != 3);
  }
  
  if (menu == 3) {
    encontro = 1;
    xnum = prompt("Ingresa el numero de cuenta que desea encontrar");
    for (x = 1; x <= renglon; x++) {
      if (xnum == num[x]) {
        encontro = 1;
        alert("Nombre: " + nombre[x] + " Numero de cuenta: " + num[x]);
        nombre[x] = prompt("Digite de nuevo el Nombre");
        alert("Nombre cambiado");
      }
    }

    if (encontro == 0)
    {
      alert("Disculpe el numero que ingreso no esta en la base de datos");
    }
  }
  if (menu == 4) {
    do {
      opccan = prompt("MENU \n 1.-Fisicas \n2.-Logicas \n3.-Reinstalaciones \n4.-Regresar");
      if (opccan == 1) {
        encontro = 0;
        xnum = prompt("Ingrese número");
        for (x = 1; x <= renglon; x++) {
          if (xnum == num[x]) {
            encontro = 1;
            alert("Nombre " + nombre[x] + " Numero de cuenta " + num[x] + "será eliminado");
            num[x] = 0;
            nombre[x] = null;
            xnum[x] = null;
            activo[x] = 0;
          }
        }
        if (encontro == 0) {
          alert("No se encontro el registro ingresado ");
        }
      }

      if (opccan == 2) {
        xnum = prompt("Ingrese número");
        for (x = 1; x <= renglon; x++) {
          if (xnum == num[x]) {
            alert("Nombre " + nombre[x] + " Numero de cuenta " + num[x] + " será eliminado");
            activo[x] = 0;
          }
        }
      }
      
      if (opccan == 3) {
        xnum = prompt("Ingrese número");
        for (x = 1; x <= 10; x++) {
          if (xnum == num[x]) {
            if (activo[x] == 0) {
              activo[x] = 1;
            }
          }
        }
      }
    } while (opccan != 4);
  }
} while (menu != 5);
<title>Documento sin t&iacute;tulo</title>
    
asked by Stephanie B Bautista 16.06.2017 в 16:45
source

1 answer

0

You have a lot of problems in your code.

In what you mention of the ordering function, you include it in the code but you do not call it at any time. At no point in the code is the function stableSort called.

On the other hand if you keep the data in 3 different arrays ( num , nombre and activo ), and you want to sort the information, the problem is that you would have to keep the 3 arrays synchronized. If you order only one of them you will not be able to find the correspondence of the data. It is better to use a single array and in each position of the array store all the information of a record.

There are also other changes you could make to your code, such as:

Use switch instead of multiple if (I think it would bring clarity to the code).

Use local variables within each block of code defined with let (also for a matter of cleanliness and clarity).

Extract to repeated code functions such as the request of a key or a name to the user.

Although I have maintained the interface using prompt and alert in my example it is not recommended (as you have already pointed out in the comments) to maintain this interface as definitive. For multiple reasons: the browsers tend to block them, it is unfriendly (I would say even annoying) for the user, it does not give flexibility or possibility of personalization, etc.

Here I leave you a modification of your code applying these ideas:

function stableSort(v, f) {
    if (f === undefined) {
        f = function (a, b) {
            a = "" + a;
            b = "" + b;
            return a < b ? -1 : (a > b ? 1 : 0);
        }
    }
    let dv = [];
    for (let i = 0; i < v.length; i++) {
        dv[i] = [v[i], i];
    }
    dv.sort(function (a, b) {
        return f(a[0], b[0]) || (a[1] - b[1]);
    });
    for (let i = 0; i < v.length; i++) {
        v[i] = dv[i][0];
    }
}

function preguntarClave() {
    const xnum = prompt('Ingrese su Número contable');
    const num = parseInt(xnum);
    if (isNaN(num) || num <= 0) {
        // Número no válido
        alert('Número no válido');
        return null;
    }
    return num;
}

function preguntarNombre(msg) {
    let nombre = prompt((msg ? msg + '\n' : '') + 'Ingrese su NOMBRE');
    if (nombre && (nombre = nombre.trim())) {
        return nombre;
    }
    // Nombre vacío o sólo espacios
    alert('No ha introducido un nombre correcto');
    return null;
}

var nombres = [];
var menu;

do {
    menu = prompt(
        "MENU PRINCIPAL\n1.-Captura\n2.-Consulta\n3.-Actualizaciones\n4.-Cancelaciones\n5.-Salida");
    switch (menu) {
    case '1':
        {
            let num = preguntarClave();
            if (num != null) {

                if (nombres.findIndex(x => x.Num === num) >= 0) {
                    // El registro ya existe
                    alert('Registro ya existente intente con otro registro');
                    break;
                }
                let nombre = preguntarNombre();
                if (nombre) {
                    nombres.push({ Num: num, Nombre: nombre, Activo: true });
                }
            }
        }
        break;
    case '2':
        {
            let opccon;
            do {
                opccon = prompt('MENU PRINCIPAL\n1.-Registro\n2.-General\n3.-Regresar');
                switch (opccon) {
                case '1':
                    {
                        let num = preguntarClave();
                        let encontro = nombres.find(x => x.Num === num && x.Activo);
                        if (encontro) {
                            alert('Nombre: ${encontro.Nombre}\nNúmero de cuenta: ${encontro.Num}');
                        } else {
                            alert('Disculpe el número que ingresó no está en la base de datos');
                        }
                    }
                    break;
                case '2':
                    {
                        stableSort(nombres, (a, b) => a.Nombre < b.Nombre ? -1 : (a.Nombre > b.Nombre ? 1 : 0));
                        let lista = nombres.filter(x => x.Activo).reduce(
                            (prev, current) => prev + 'Clave: ' + current.Num + ' Nombre: ' + current.Nombre + '\n',
                            '');
                        alert(lista);
                    }
                    break;
                }
            } while (opccon !== '3');
        }
        break;
    case '3':
        {
            let num = preguntarClave();
            let encontro = nombres.find(x => x.Num === num && x.Activo);
            if (!encontro) {
                alert('Disculpe el número que ingresó no está en la base de datos');
                break;
            }

            let nombre = preguntarNombre('Nombre: ${encontro.Nombre} Número de cuenta: ${encontro.Num}');
            if (nombre) {
                encontro.Nombre = nombre;
                alert('Nombre cambiado');
            }
        }
        break;
    case '4':
        {
            let opccan;
            do {
                opccan = prompt('MENU\n1.-Físicas\n2.-Lógicas\n3.-Reinstalaciones\n4.-Regresar');
                switch (opccan) {
                case '1':
                    {
                        let num = preguntarClave();
                        let index = nombres.findIndex(x => x.Num === num);
                        if (index < 0) {
                            alert('No se encontró el registro ingresado');
                            break;
                        }
                        alert('Nombre :${nombres[index].Nombre}\nNúmero de cuenta: ${nombres[index].Num}\nEl registro será eliminado');
                        nombres.splice(index, 1);
                    }
                    break;
                case '2':
                    {
                        let num = preguntarClave();
                        let encontro = nombres.find(x => x.Num === num && x.Activo);
                        if (!encontro) {
                            alert('El registro ${num} no existe');
                            break;
                        }
                        alert('Nombre :${encontro.Nombre}\nNúmero de cuenta: ${encontro.Num}\nEl registro será eliminado');
                        encontro.Activo = false;
                    }
                    break;
                case '3':
                {
                    let num = preguntarClave();
                    let encontro = nombres.find(x => x.Num === num);
                    if (!encontro) {
                        alert('El registro ${num} no existe');
                        break;
                    }
                    encontro.Activo = true;
                    alert('Nombre :${encontro.Nombre}\nNúmero de cuenta: ${encontro.Num}\nEl registro se ha restituido');

                }
                }
            } while (opccan !== '4')
        }
        break;
    }
} while (menu !== '5');
    
answered by 08.12.2017 в 13:01