can you help whi console log? - javascript

i need to count X and Y
but my console log dosent work, maybe problem in
if matches[i].includes(something) == "true"
var input = "10W5N2S6E";
var matches = input.split(/(?<=[A-Z])(?=\d)/);
for (let i = 0; i < matches.length; i++) {
let x = 0;
let y = 0;
if (matches[i].includes("w") == "true") {
x = x - matches[i];
console.log(x);
}
if (matches[i].includes("e") == "true") {
x = x + matches[i];
console.log(x);
}
if (matches[i].includes("n") == "true") {
y = y + matches[i];
console.log(y);
}
if (matches[i].includes("s") == "true") {
y = y - matches[i];
console.log(y);
}
}

You need to to use toLowerCase() since includes() is case sensitive.
Also, no need to compare includes() == "true" since it returns a boolean and it is enough for the if condition (which will execute the next block statement based on that boolean condition)
var input = "10W5N2S6E";
var matches = input.split(/(?<=[A-Z])(?=\d)/);
for (let i = 0; i < matches.length; i++) {
const match = matches[i].toLowerCase();
let x = 0;
let y = 0;
if (match.includes("w")) {
x = x - matches[i];
console.log(x);
}
if (match.includes("e")) {
x = x + matches[i];
console.log(x);
}
if (match.includes("n")) {
y = y + matches[i];
console.log(y);
}
if (match.includes("s")) {
y = y - matches[i];
console.log(y);
}
}

Related

Js Multi-dimensional Array setting value oddly

I've made a multidimensional array with Array constructor and Array.fill method.
I cannot figure out where the problem is, but this code doesn't work as I want.
function loadChunk(){
for(var x = 0; x< 3; x++){
for(var y= 0; y < 3; y++){
console.log(x+","+y);
console.log((world[x][y]).loaded);
if(!(world[x][y]).loaded){
world[x][y].loaded=true;
}
}
}
}
function createWorld(w, d){
var worldz = new Array(d * 2 + 1);
var world = new Array(w * 2 + 1);
world.fill(worldz);
for(var x = 0; x< w * 2+ 1; x++){
for(var z = 0; z < d * 2 + 1; z++){
world[x][z]= { loaded: false };
}
}
return world;
}
var world = createWorld(1, 1);
Start();
function Start(){
loadChunk();
}
You can see what is happening with console.
With my view, no true should be written on console.
The problem is, if I edit world[0][n],then world[1 or more][n] changes too.
Replace your createWorld function with this:
function createWorld(w, d){
var world = new Array(w * 2 + 1);
for(var x = 0; x< w * 2+ 1; x++){
// each item of the array requires a new instance
// you should not use fill method in this situation
world[x]=new Array(d * 2 + 1);
for(var z = 0; z < d * 2 + 1; z++){
world[x][z]= { loaded: false };
}
}
return world;
}
function loadChunk() {
for (var x = 0; x < 3; x++) {
for (var y = 0; y < 3; y++) {
console.log(x + "," + y, (world[x][y]).loaded);
if (!(world[x][y]).loaded) {
world[x][y].loaded = true;
}
}
}
}
function createWorld(w, d) {
var world = [];
for (var x = 0; x < w * 2 + 1; x++) {
world[x] = [];
for (var z = 0; z < d * 2 + 1; z++) {
world[x][z] = {loaded: false};
}
}
return world;
}
var world = createWorld(1, 1);
Start();
function Start() {
loadChunk();
}
The problem that you expirience is that you fill "rows" of world with the same array, so world[0] === world[1] && world[1] === world[2] because array variable worldz is holding a reference
The best way to learn your problem is doing next thing:
function createWorld(w, d){
var worldz = new Array(d * 2 + 1);
var world = new Array(w * 2 + 1);
world.fill(worldz);
for(var x = 0; x< w * 2+ 1; x++){
for(var z = 0; z < d * 2 + 1; z++){
world[x][z]= { loaded: false };
debugger;
}
}
return world;
}
And inspecting in chrome debugger what happens with world variable on a first step
The reason why a change of world[0][0] also changes world[1][0] and world[2][0] (same for other indecees of worldz) is that world.fill(worldz) makes all elements of world the same identical object (Array) worldz.
To avoid this every element of world should be a new Array like eg:
for(n=0,max=world.length;n<max;n++) {world[n] = new Array(d * 2 + 1);}

Can't make the code recognize 0 as a value

I'm making an editable RPG sheet. For this specific section, I need it to compare the 1_7, 2_7 and 3_7 to the result of the equation, and have it select the smaller value. However, while it works on most situations, it doesn't recognize 0 as a value. 1_7, 2_7 and 3_7 are inputted manually.
What should I do in order to get the code to recognize 0 as a value?
var x =
this.getField("1_7").value;
var y =
this.getField("2_7").value;
var z =
this.getField("3_7").value;
var f = Math.floor((this.getField("Des Temp").value - 10) / 2);
var temp;
if(!x)
{
x = f;
}
if(!y)
{
y = f;
}
if(!z)
{
z = f;
}
if(x <= y && x <= z)
temp = x;
else if(y <= z)
temp = y;
else
temp = z;
if(f > temp)
f = temp;
if(f > 0){
event.value = "+" + f;
}
else{
event.value = f;
}
O is a "falsy" value so
if(!x)
Is doing what it is supposed to do. The empty value is probably an empty string so you could do
if ( ! x.length )
instead.
$('#x').on( 'input', function() {
console.log( ! $(this).val().length );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='x' >
It's because 0 is considered as false inside a javascript comparaison. If you want to verify if the field have data, you can use the length property.
var x = 0;
var y = 5;
var z = 3;
var f = 10;
if(0)
{
console.log("0 is false");
}
if(1)
{
console.log("1 or any number != 0 is true");
}
if(x.length)
{
x = f;
console.log("x is not set");
}
if(y.length)
{
y = f;
console.log("y is not set");
}
if(y.length)
{
z = f;
console.log("z is not set");
}

Adjusting the scope of the callback function of onclick

I'm trying to solve a programming exercise in which there are several bugs to be fixed. Ultimately, it is supposed to represent an animation with a grid of cells where at each time step, if a cell has exactly three neighbors which are alive (each cell has 8 neighbors), it 'comes to life', and if it has less than 2 or more than 3 neighbors, it 'dies' (where the neighbors 'wrap around' the grid). The initial script is as follows:
<html>
<head>
<script type="text/javascript">
var Board;
var xsize = 10;
var ysize = 10;
var dead = 0;
var alive = 1;
function Neighbors(Board, x, y)
{
var n = 0
for(dx=-1;dx < 1; ++dx)
for(dy=-1;dy < 1; ++dy)
{
var ax = x+dx;
var ay = y+dy;
if(Board[ax][ay]==alive) ++n;
}
return n;
}
function Kill(Board,x,y)
{
if(Board[x][y] == alive)
Board[x][y] = dead;
}
function MakeLive(Board,x,y)
{
if(Board[x][y] == dead)
Board[x][y] = alive;
}
function NextStep(Board)
{
for(var x = 0; x <= xsize; ++x)
{
for(var y = 0; y <= ysize; ++x)
{
n = Neighbors(Board,x,y);
if(n=3) MakeLive(Board,x,y);
if((n<2)||(n>3)) Kill(Board,x,y);
}
}
}
function DrawBoard(Board)
{
var Text = "";
for(var y = 0; y < ysize; ++y)
{
for(var x = 0; x < xsize; ++x)
Text += Board[x][y]==alive ? "o":"_";
Text += "<br/>";
}
document.getElementById("board").innerHTML = Text;
}
function Main()
{
// *** Change this variable to choose a different baord setup from below
var BoardSetup = "blinker";
Board = new Array(xsize);
for(var x = 0; x < xsize; ++x)
{
Board[x] = new Array(ysize);
for(var y = 0; y < ysize; ++y)
Board[x][y] = 0;
}
if(BoardSetup == "blinker")
{
Board[1][0] = 1;
Board[1][1] = 1;
Board[1][2] = 1;
}
else if(BoardSetup == "glider")
{
Board[2][0] = 1;
Board[2][1] = 1;
Board[2][2] = 1;
Board[1][2] = 1;
Board[0][1] = 1;
}
else if(BoardSetup == "flower")
{
Board[4][6] = 1;
Board[5][6] = 1;
Board[6][6] = 1;
Board[7][6] = 1;
Board[8][6] = 1;
Board[9][6] = 1;
Board[10][6] = 1;
Board[4][7] = 1;
Board[6][7] = 1;
Board[8][7] = 1;
Board[10][7] = 1;
Board[4][8] = 1;
Board[5][8] = 1;
Board[6][8] = 1;
Board[7][8] = 1;
Board[8][8] = 1;
Board[9][8] = 1;
Board[10][8] = 1;
}
DrawBoard(Board);
}
</script>
</head>
<body onload="Main()">
<div id="board">
</div>
Next ->
</body>
</html>
The problem is that if I press the 'Next' button, in the console I see the following error:
Uncaught TypeError: Cannot read property '-1' of undefined
at Neighbors (life_broken__281_29.html:19)
at Function.NextStep (life_broken__281_29.html:42)
at HTMLAnchorElement.onclick (life_broken__281_29.html:117)
Neighbors # life_broken__281_29.html:19
NextStep # life_broken__281_29.html:42
onclick # life_broken__281_29.html:117
The problem, I believe, is that the Board is defined in the Main() function, which is not in the scope of the onclick callback function.
My initial approach was to move the initialization of the Board outside of the Main() function, making it a global variable, and removing Board from all function calls. This does not seem like an elegant approach, however. Instead, I tried using Function.prototype.call() as follows:
Next ->
Further, I implemented a wrapAround function to avoid the indices going out of bounds:
function Neighbors(Board, x, y)
{
var n = 0
for(dx=-1;dx < 1; ++dx)
for(dy=-1;dy < 1; ++dy)
{
var ax = x+dx;
var ay = y+dy;
ax = wrapAround(ax, xsize);
ay = wrapAround(ay, ysize);
if(Board[ax][ay]==alive) ++n;
}
return n;
}
function wrapAround(coordinate, size) {
var result = coordinate % size;
if (result < 0) {
result += size;
}
return result;
}
However, now I get a new error:
life_broken__281_29.html:42 Uncaught TypeError: Cannot read property '0' of undefined
at MakeLive (life_broken__281_29.html:42)
at Function.NextStep (life_broken__281_29.html:53)
at HTMLAnchorElement.onclick (life_broken__281_29.html:127)
Apparently, the Neighbors function is now not raising any errors, but the next function in NextStep, MakeLive, is. This I don't understand however because they are both defined at the same 'level' and have similar invocations in NextStep. Can anyone explain what the issue is here?
Update
Indeed Board is declared in the global scope, so there was no need for Function.prototype.call(). (I'm used to Python where declaration and definition are always in the same place). I also changed the Boolean expression to (x === 3).
However, for some reason x is still going up to 10 even if I replace the <= by a <. Here is the updated code, with a console.log statement for debugging:
<html>
<head>
<script type="text/javascript">
var Board;
var xsize = 10;
var ysize = 10;
var dead = 0;
var alive = 1;
function Neighbors(Board, x, y)
{
var n = 0
for(dx=-1;dx < 1; ++dx)
for(dy=-1;dy < 1; ++dy)
{
var ax = x+dx;
var ay = y+dy;
ax = wrapAround(ax, xsize);
ay = wrapAround(ay, ysize);
if(Board[ax][ay]==alive) ++n;
}
return n;
}
function wrapAround(coordinate, size) {
var result = coordinate % size;
if (result < 0) {
result += size;
}
return result;
}
function Kill(Board, x, y)
{
if (Board[x][y] == alive)
Board[x][y] = dead;
}
function MakeLive(Board, x, y)
{
if (Board[x][y] == dead)
Board[x][y] = alive;
}
function NextStep(Board)
{
for(var x = 0; x < xsize; ++x)
{
for(var y = 0; y < ysize; ++x)
{
n = Neighbors(Board,x,y);
console.log("x = " + x + ", y = " + y + ", n = " + n);
if (n===3) MakeLive(Board,x,y);
if ((n<2)||(n>3)) Kill(Board,x,y);
}
}
}
function DrawBoard(Board)
{
var Text = "";
for(var y = 0; y < ysize; ++y)
{
for(var x = 0; x < xsize; ++x)
Text += Board[x][y]==alive ? "o":"_";
Text += "<br/>";
}
document.getElementById("board").innerHTML = Text;
}
function Main()
{
// *** Change this variable to choose a different baord setup from below
var BoardSetup = "blinker";
Board = new Array(xsize);
for(var x = 0; x < xsize; ++x)
{
Board[x] = new Array(ysize);
for(var y = 0; y < ysize; ++y)
Board[x][y] = 0;
}
if(BoardSetup == "blinker")
{
Board[1][0] = 1;
Board[1][1] = 1;
Board[1][2] = 1;
}
else if(BoardSetup == "glider")
{
Board[2][0] = 1;
Board[2][1] = 1;
Board[2][2] = 1;
Board[1][2] = 1;
Board[0][1] = 1;
}
else if(BoardSetup == "flower")
{
Board[4][6] = 1;
Board[5][6] = 1;
Board[6][6] = 1;
Board[7][6] = 1;
Board[8][6] = 1;
Board[9][6] = 1;
Board[10][6] = 1;
Board[4][7] = 1;
Board[6][7] = 1;
Board[8][7] = 1;
Board[10][7] = 1;
Board[4][8] = 1;
Board[5][8] = 1;
Board[6][8] = 1;
Board[7][8] = 1;
Board[8][8] = 1;
Board[9][8] = 1;
Board[10][8] = 1;
}
DrawBoard(Board);
}
</script>
</head>
<body onload="Main()">
<div id="board">
</div>
Next ->
</body>
</html>
and here is the result of the console when I click 'Next':
x = 0, y = 0, n = 0
life_broken__281_29.html:53 x = 1, y = 0, n = 1
life_broken__281_29.html:53 x = 2, y = 0, n = 0
life_broken__281_29.html:53 x = 3, y = 0, n = 0
life_broken__281_29.html:53 x = 4, y = 0, n = 0
life_broken__281_29.html:53 x = 5, y = 0, n = 0
life_broken__281_29.html:53 x = 6, y = 0, n = 0
life_broken__281_29.html:53 x = 7, y = 0, n = 0
life_broken__281_29.html:53 x = 8, y = 0, n = 0
life_broken__281_29.html:53 x = 9, y = 0, n = 0
life_broken__281_29.html:53 x = 10, y = 0, n = 0
life_broken__281_29.html:36 Uncaught TypeError: Cannot read property '0' of undefined
at Kill (life_broken__281_29.html:36)
at NextStep (life_broken__281_29.html:55)
at HTMLAnchorElement.onclick (life_broken__281_29.html:128)
I'm a bit nonplussed why this is happening because a simple for loop in this fashion does work:
for (var i = 0; i < 10; ++i) {
console.log("i = " + i);
}
VM158:2 i = 0
VM158:2 i = 1
VM158:2 i = 2
VM158:2 i = 3
VM158:2 i = 4
VM158:2 i = 5
VM158:2 i = 6
VM158:2 i = 7
VM158:2 i = 8
VM158:2 i = 9
undefined
Is the console somehow using a cached version of the old code? (I'm using the Live Preview in Brackets).
Update 2
This is because I should use a post-increment instead of a pre-increment (cf. http://jsforallof.us/2014/07/10/pre-increment-vs-post-increment/). Changing the ++x to x++ solved the problem.
The error has nothing to do with variable scope. Board is a global variable, so it's accessible to any function.
Your original problem was because you were accessing outside the Board array when x = 0 and dx = -1, and you fixed that with your wrapAround() function.
The next problem is that your loops in NextStep go too far. The row indexes go from 0 to xsize-1 and the columns go from 0 to ysize-1. But the loop there uses x <= xsize and y <= ysize, so it will try to access Board[xsize], which doesn't exist. Change those <= to <, just like the loop in Main().
if(n=3) MakeLive(Board,x,y);, your n = 3 should be n === 3, I'm sure you don't want to assign 3 to n which would cause a truthy value, which will call MakeLive(Board,x,y); every time.
Also, in NextStep you have your x and y go all the way up to xsize and ysize (<=) whereas everywhere else you use <, think that causes your undefined value in Board[x]

A while loop to add the digits of a multi-digit number together? (Javascript)

I need to add the digits of a number together (e.g. 21 is 2+1) so that the number is reduced to only one digit (3). I figured out how to do that part.
However,
1) I may need to call the function more than once on the same variable (e.g. 99 is 9+9 = 18, which is still >= 10) and
2) I need to exclude the numbers 11 and 22 from this function's ambit.
Where am I going wrong below?
var x = 123;
var y = 456;
var z = 789;
var numberMagic = function (num) {
var proc = num.toString().split("");
var total = 0;
for (var i=0; i<proc.length; i++) {
total += +proc[i];
};
};
while(x > 9 && x != 11 && x != 22) {
numberMagic(x);
};
} else {
xResult = x;
};
console.log(xResult);
//repeat while loop for y and z
Here are the problems with your code
var x = 123;
var y = 456;
var z = 789;
var numberMagic = function (num) {
var proc = num.toString().split("");
var total = 0;
for (var i=0; i<proc.length; i++) {
total += +proc[i]; // indentation want awry
}; // don't need this ; - not a show stopper
// you're not returning anything!!!!
};
while(x > 9 && x != 11 && x != 22) {
numberMagic(x);
}; // ; not needed
// because x never changes, the above while loop would go on forever
} else { // this else has no if
xResult = x; // even if code was right, x remains unchanged
};
console.log(xResult);
Hope that helps in some way
Now - here's a solution that works
var x = 123;
var y = 456;
var z = 789;
var numberMagic = function (num) {
while (num > 9) {
if (num == 11 || num == 22) {
return num;
}
var proc = num.toString().split("");
num = proc.reduce(function(previousInt, thisValueString) {
return previousInt + parseInt(thisValueString);
}, 0);
}
return num;
}
console.log(numberMagic(x));
console.log(numberMagic(y));
console.log(numberMagic(z));
I'm not sure to understand what you want..
with this function you reduce any number to one single digit
while(num > 9){
if(num == 11 || num == 22) return;
var proc = num.toString();
var sum = 0;
for(var i=0; i<proc.length; i++) {
sum += parseInt(proc[i]);
}
num = sum;
}
is it what you are looking at?
I wrote an example at Jsfiddle that you can turn any given number into a single digit:
Example input: 551
array of [5, 5, 1] - add last 2 digits
array of [5, 6] - add last 2 digits
array of [1, 1] - add last 2 digits
array of [2] - output
Here is the actual code:
var number = 1768;
var newNumber = convertToOneDigit(number);
console.log("New Number: " + newNumber);
function convertToOneDigit(number) {
var stringNumber = number.toString();
var stringNumberArray = stringNumber.split("");
var stringNumberLength = stringNumberArray.length;
var tmp;
var tmp2;
var tmp3;
console.log("Array: " + stringNumberArray);
console.log("Array Length: " + stringNumberLength);
while (stringNumberLength > 1) {
tmp = parseInt(stringNumberArray[stringNumberLength - 1]) + parseInt(stringNumberArray[stringNumberLength - 2]);
stringNumberArray.pop();
stringNumberArray.pop();
tmp2 = tmp.toString();
if (tmp2.length > 1) {
tmp3 = tmp2.split("");
for (var i = 0; i < tmp3.length; i++) {
stringNumberArray.push(tmp3[i]);
}
} else {
stringNumberArray.push(tmp2);
}
stringNumberLength = stringNumberArray.length;
console.log("Array: " + stringNumberArray);
console.log("Array Length: " + stringNumberLength);
}
return stringNumberArray[0];
}
function addDigits(n) {
let str = n.toString().split('');
let len = str.length;
let add,
acc = 0;
for (i=0; i<=len-1; i++) {
acc += Number(str[i]);
}
return acc;
}
console.log( addDigits(123456789) ); //Output: 45
Just make it a While loop, remember a While loops it's just the same as a For loop, only you add the counter variable at the end of the code, the same way you can do with a Do{code}while(condition) Only need to add a counter variable at the end and its gonna be the same. Only that the variable its global to the loop, I mean comes from the outside.
Ej.
let i = 0; //it's global to the loop, ( wider scope )
while (i<=x) {
//Code line;
//Code line;
//Code line;
//Code line;
i++
}
Now this is working with an outside variable and it's NOT recommended.. unless that var its local to a Function.
Please look at the this solution also
var x = 123;
var y = 456;
var z = 789;
var numberMagic = function (num) {
var total = 0;
while (num != 0) {
total += num % 10;
num = parseInt(num / 10);
}
console.log(total);
if (total > 9)
numberMagic(total);
else
return total;
}
//Call first time function
numberMagic(z);

Create range of letters and numbers

I'm creating a form where users can input a range. They are allowed to input letters and numbers. Some sample input:
From: AA01
To: AZ02
Which should result in:
AA01
AA02
AB01
AB02
And so on, till AZ02
And:
From: BC01
To: DE01
Should result in:
BC01
BD01
BE01
CC01
CD01
CE01
Etc
I managed to get it working for the input A01 to D10 (for example)
jsFiddle
However, i can't get it to work with multiple letters.
JS code:
var $from = $('input[name="from"]');
var $to = $('input[name="to"]');
var $quantity = $('input[name="quantity"]');
var $rangeList = $('.rangeList');
var $leadingzeros = $('input[name="leadingzeros"]');
$from.on('keyup blur', function () {
$(this).val($(this).val().replace(/[^a-zA-Z0-9]/g, ''));
updateQuantity();
});
$to.on('keyup blur', function () {
$(this).val($(this).val().replace(/[^a-zA-Z0-9]/g, ''));
updateQuantity();
});
$leadingzeros.on('click', function () {
updateQuantity();
});
function updateQuantity() {
var x = parseInt($from.val().match(/\d+/));
var y = parseInt($to.val().match(/\d+/));
var xl = $from.val().match(/[a-zA-Z]+/);
var yl = $to.val().match(/[a-zA-Z]+/);
var result = new Array();
if (xl != null && yl != null && xl[0].length > 0 && yl[0].length > 0) {
xl = xl[0].toUpperCase();
yl = yl[0].toUpperCase();
$rangeList.html('');
var a = yl.charCodeAt(0) - xl.charCodeAt(0);
for (var i = 0; i <= a; i++) {
if (!isNaN(x) && !isNaN(y)) {
if (x <= y) {
var z = (y - x) + 1;
$quantity.val(z * (a + 1));
$rangeList.html('');
for (var b = z; b > 0; b--) {
var c = ((y - b) + 1);
if ($leadingzeros.prop('checked')) {
c = leadingZeroes(c, y.toString().length);
}
result.push(String.fromCharCode(65 + i) + c);
}
} else {
$rangeList.html('');
$quantity.val(0);
}
} else {
$rangeList.html('');
$quantity.val(0);
}
}
} else if (!isNaN(x) && !isNaN(y)) {
if (x < y) {
var z = (y - x) + 1;
$quantity.val(z);
$rangeList.html('');
for (var i = z; i > 0; i--) {
var c = (y - i) + 1;
if ($leadingzeros.prop('checked')) {
c = leadingZeroes(c, y.toString().length);
}
result.push(c);
}
} else {
$rangeList.html('');
$quantity.val(0);
}
} else {
$rangeList.html('');
$quantity.val(0);
}
$rangeList.html('');
for (var i = 0; i < result.length; i++) {
$rangeList.append(result[i] + '<br />');
}
}
function leadingZeroes(number, size) {
number = number.toString();
while (number.length < size) number = "0" + number;
return number;
}
This is perfect for a recursive algorithm:
function createRange(from, to) {
if (from.length === 0) {
return [ "" ];
}
var result = [];
var innerRange = createRange(from.substring(1), to.substring(1));
for (var i = from.charCodeAt(0); i <= to.charCodeAt(0); i++) {
for (var j = 0; j < innerRange.length; j++) {
result.push(String.fromCharCode(i) + innerRange[j]);
}
}
return result;
}
Called as follows:
createRange('BC01', 'DE02'); // Generates an array containing all values expected
EDIT: Amended function below to match new test case (much more messy, however, involving lots of type coercion between strings and integers).
function prefixZeroes(value, digits) {
var result = '';
value = value.toString();
for (var i = 0; i < digits - value.length; i++) {
result += '0';
}
return result + value;
}
function createRange(from, to) {
if (from.length === 0) {
return [ "" ];
}
var result = [];
if (from.charCodeAt(0) < 65) {
fromInt = parseInt(from);
toInt = parseInt(to);
length = toInt.toString().length;
var innerRange = createRange(from.substring(length), to.substring(length));
for (var i = fromInt; i <= toInt; i++) {
for (var j = 0; j < innerRange.length; j++) {
result.push(prefixZeroes(i, length) + innerRange[j]);
}
}
} else {
var innerRange = createRange(from.substring(1), to.substring(1));
for (var i = from.charCodeAt(0); i <= to.charCodeAt(0); i++) {
for (var j = 0; j < innerRange.length; j++) {
result.push(String.fromCharCode(i) + innerRange[j]);
}
}
}
return result;
}
Please note that because of your strict logic in how the value increments this method requires exactly 4 characters (2 letters followed by 2 numbers) to work. Also, this might not be as efficient/tidy as it can be but it took some tinkering to meet your logic requirements.
function generate(start, end) {
var results = [];
//break out the start/end letters/numbers so that we can increment them seperately
var startLetters = start[0] + start[1];
var endLetters = end[0] + end[1];
var startNumber = Number(start[2] + start[3]);
var endNumber = Number(end[2] + end[3]);
//store the start letter/number so we no which value to reset the counter to when a maximum boundry in reached
var resetLetter = startLetters[1];
var resetNumber = startNumber;
//add first result as we will always have at least one
results.push(startLetters + (startNumber < 10 ? "0" + startNumber : "" + startNumber));
//maximum while loops for saefty, increase if needed
var whileSafety = 10000;
while (true) {
//safety check to ensure while loop doesn't go infinite
whileSafety--;
if (whileSafety == 0) break;
//check if we have reached the maximum value, if so stop the loop (break)
if (startNumber == endNumber && startLetters == endLetters) break;
//check if we have reached the maximum number. If so, and the letters limit is not reached
//then reset the number and increment the letters by 1
if (startNumber == endNumber && startLetters != endLetters) {
//reset the number counter
startNumber = resetNumber;
//if the second letter is at the limit then reset it and increment the first letter,
//otherwise increment the second letter and continue
if (startLetters[1] == endLetters[1]) {
startLetters = '' + String.fromCharCode(startLetters.charCodeAt(0) + 1) + resetLetter;
} else {
startLetters = startLetters[0] + String.fromCharCode(startLetters.charCodeAt(1) + 1);
}
} else {
//number limit not reached so just increment the number counter
startNumber++;
}
//add the next sequential value to the array
results.push(startLetters + (startNumber < 10 ? "0" + startNumber : "" + startNumber));
}
return results;
}
var results = generate("BC01", "DE01");
console.log(results);
Here is a working example, which uses your second test case
Using #Phylogenesis' code, i managed to achieve my goal.
jsFiddle demo
function updateQuantity() {
var x = parseInt($from.val().match(/\d+/));
var y = parseInt($to.val().match(/\d+/));
var xl = $from.val().match(/[a-zA-Z]+/);
var yl = $to.val().match(/[a-zA-Z]+/);
var result = new Array();
var r = createRange(xl[0], yl[0]);
var z = (y - x) + 1;
if (x <= y) {
for (var j = 0; j < r.length; j++) {
var letters = r[j];
for (var i = z; i > 0; i--) {
var c = (y - i) + 1;
if ($leadingzeros.prop('checked')) {
c = leadingZeroes(c, y.toString().length);
}
if (i == z) {
r[j] = letters + c + '<br />';
} else {
j++;
r.splice(j, 0, letters + c + '<br />');
}
}
}
} else {
for (var i = 0; i < r.length; i++) {
r[i] += '<br />';
}
}
$quantity.val(r.length);
$rangeList.html('');
for (var i = 0; i < r.length; i++) {
$rangeList.append(r[i]);
}
}
This works for unlimited letters and numbers, as long as the letters are first.
Thanks for your help!

Categories

Resources