0

I have the data array and I want to sort them, and it's run OK.

Now I need pass by parameter the values, but if the user put some 'parameter' which doesn't exists, I show the error message using TRY/CATCH. But I don't know why, can you help me please?

const data = [
    {
        "color": "Blue",
        "door": 3,
        "wheel": 3,
        "year": 2005,
        "brand": "GMC",
        "sold": false,
        "owner": "Chalmers Boobyer",
        "motor": 1.7,
        "assembled": "09/08/2022"
    },
    {
        "color": "Indigo",
        "door": 4,
        "wheel": 4,
        "year": 1996,
        "brand": "Lincoln",
        "sold": true,
        "owner": "Morten Coffin",
        "motor": 1.7,
        "assembled": "26/08/2021"
    }
];

function bubbleSort(arr, ord, prop){
    try{
    if(ord === 'asc'){
        for(let i = 0; i < arr.length; i++){
            for(let j = 0; j < arr.length - 1 - i; j++){
                if(arr[j][prop] > arr[j+1][prop]){
                    let temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
            }
        }
    } else if(ord === 'desc'){
        for(let i = 0; i < arr.length; i++){
            for(let j = 0; j < arr.length - 1 - i; j++){
                if(arr[j][prop] < arr[j+1][prop]){
                    let temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
            }
        }
    }
    return (arr);
}   catch(err){
    console.log(err);
}
}

console.log(bubbleSort(data, 'asc', 'wheel'));
Kurt
  • 678
  • 1
  • 7
  • 24
eduardo
  • 11
  • 4
  • you don't know why what? no one will be able to understand your question. it doesn't make a lot of sense. – dqhendricks Sep 30 '22 at 00:29
  • idk what I do wrong in my try/catch – eduardo Sep 30 '22 at 00:32
  • my code alwayys sort even if I put a parameter that doesn't exist – eduardo Sep 30 '22 at 00:34
  • what is wrong with your try/catch? what does the code do, what do you expect it to do instead? - give example of parameter that should not work - the code in the question would work, so ... not really showing the issue you are having – Jaromanda X Sep 30 '22 at 00:34
  • ahh ... so if you put `someRandomString` as the prop, you think it should go to catch ... thing is `arr[n]['someRandomString']` is `undefined` - so it won't throw an error trying to access it – Jaromanda X Sep 30 '22 at 00:36
  • Javascript won't raise an error if you try to access a non-existent property, it will simply return `undefined`. You should test for `prop in arr[0]` instead – Nick Sep 30 '22 at 00:37
  • for example: if I try run this: console.log(bubbleSort(data, 'asc', 'TEST-TEST')); my code run – eduardo Sep 30 '22 at 00:37
  • But see: the property TEST-TEST in my objct doesn't exists – eduardo Sep 30 '22 at 00:38
  • You could force an error using the answer to [this question](https://stackoverflow.com/questions/6511542/force-javascript-exception-error-when-reading-an-undefined-object-property) – Nick Sep 30 '22 at 00:38
  • But how I can solve this, forcing error – eduardo Sep 30 '22 at 00:41
  • Probably the simplest way would be `try { if (prop not in arr[0]) throw new ReferenceError(\`Property '${property}' is not defined\`); ... } catch (err) { ... }` – Nick Sep 30 '22 at 03:42

1 Answers1

0

let data = [
  {
    "color": "Blue",
    "door": 3,
    "wheel": 3,
    "year": 2005,
    "brand": "GMC",
    "sold": false,
    "owner": "Chalmers Boobyer",
    "motor": 1.7,
    "assembled": "09/08/2022"
  },
  {
    "color": "Indigo",
    "door": 4,
    "wheel": 4,
    "year": 1996,
    "brand": "Lincoln",
    "sold": true,
    "owner": "Morten Coffin",
    "motor": 1.7,
    "assembled": "26/08/2021"
  }
];

/**
 * Swaps two object present in Arry arr of index index1 and index 2 respectively
 * @param {*} arr>[]: The array whose object needs to be swapped
 * @param {*} index1>Number: the index of the first object
 * @param {*} index2>number: index of the second object
 * @returns {*}  undefined
 */
function swap(arr, index1, index2) {
  let temp = arr[index1];
  arr[index1] = arr[index2];
  arr[index2] = temp;
}

/**
 * 
 * @param {*} arr>[]: the array of objects
 * @param {*} index>number: the index at which the object is present used for printing error details
 * @param {*} prop>string: the name of the property to check for existance in the object
 * @returns Boolean | Throws Exception
 */
function propertyExsists(arr, index, prop) {
  if (arr[index][prop] !== undefined) {
    return true;
  }
  throw new ReferenceError(`Property: ${prop} does not exsist in arr[${index}]`);
}

/**
 * 
 * @param {*} ord -> string: values are 'asc' or 'desc'
 * @returns {*} (arr, index1, index2, prop) => {}: compare the array objects present in index1 and index2 on property prop
 */
function getCompareFunc(ord) {
  if (ord === 'asc') {
    return (arr, index1, index2, prop) => { 
      return arr[index1][prop] > arr[index2][prop];
    }
  } else if (ord === 'desc') {
   return (arr, index1, index2, prop) => {
    return arr[index1][prop] < arr[index2][prop];
  }
  } else {
    throw `Invalid parameter for getComparator`;
  }
}


function bubbleSort(arr, ord, prop) {
  try {
    const compareArrayObjects = getCompareFunc(ord);
    for (let i = 0; i < arr.length; i++) {
      for (let j = 0; j < arr.length - 1 - i; j++) {
        propertyExsists(arr, j, prop);
        propertyExsists(arr, j+1, prop);
        if (compareArrayObjects(arr, j, j+1, prop)) {
          swap(arr, j, j+1);
        }
      }
    }
    return data;
  } catch (err) {
    console.log(err);
  }
}


console.log(bubbleSort(data, 'desc', 'wheel'));
console.log(bubbleSort(data, 'desc', 'a'));

You can try this approach

Balaji
  • 795
  • 1
  • 2
  • 10