How to get list and create auto ID?

Hello guys, I want to create a function auto ID. Example : In table Product have ID ( P0001,P0004,P0006) . It’ll create ID with value P0002. Logic as follow

  1. Check row in table Product , if not row , the value first is P0001
  2. If some rows in table , check some case and create ID
  • P0002,P0004,P0005 CREATE P0001
  • P0001,P0002,P0004,P0005 CREATE P0003
  • P0003,P0004,P0001,P0005.P0007 CREATE P0002
    etc…

$scope.ListProID = [];
$scope.GetProID = function () {
CatList.select(‘Select ProID from product’, []).then(function (res) {
$scope.ListProID = res;
console.log(res);
if (res.length == 0) { ///not row in table product
return ‘P0001’;
}
else { //create ProID
for (var i = 0; i < res.rows.length; i++) {
// check value of ID and create ID
//
}
// return value of ID new;
}
});
};

Thank you.

I am new here, but here is something I would try.

Use this link to sort the item into order

then I would use the code you have and a bit of hard coding. ugly and have not tested.

var str= ‘’;
var i = 0;
var num=0;
$scope.GetProID = function () {
CatList.select(‘Select ProID from product’,[]).then(function (res) {
$scope.ListProID = res;
console.log(res);
if (res.length == 0) { ///not row in table product
return ‘P0001’;
}else{
var crazyLoop = true;
for (crazyLoop) {
if((parseInt(res.rows[i+1].substring(1))-parseInt(res.rows[i].substring(1)))>=1){
num = i;
crazyLoop = false;
}
i++;
}
var counter = (’’ + num).length;
counter = 4 - counter;
while(counter>0){
str = ‘0’ + i;
counter–;
}
i=0;
num=0;
return ‘P’ + str;
}else{
num = 1+i;
var counter = (’’ + num).length;
counter = 4 - counter;
. str=I;
while(counter>0){
str = ‘0’ + str;
counter–;
}
i=0;
num=0;
return ‘P’ + str;
}
});
};

Hopefully someone can come up with better one.

Thank you so much .I’ll try it.