i want the user to enter a few marks and at the end i want to display the highest lowest average how many got a make of "A","B","C","D","F"
var highestMark=0;
var gradeAwarded;
var StudentArr= [Student];
var markArr = [mark];
var Student = prompt("Enter Student Name: ", "Name");
var mark = prompt("Enter Student Mark: ", 50);
var max = Math.max.apply(markArr); /* This about equal to Math.max(numbers[0], ...) or Math.max(5, 6, ..) */
var min = Math.min.apply(markArr);
if (mark < 0 || mark > 100) {
alert("Grate out of bounds");
} else if (mark >= 83) {
gradeAwarded = "A";
} else if (mark >= 70) {
gradeAwarded = "B";
} else if (mark >= 50) {
gradeAwarded = "C";
} else if (mark >= 0) {
gradeAwarded = "F";
}
document.write(min);
You can just sort the array and take the first and last value. For example:
arr = [3, 5, 2, 14];
arr.sort(function(x, y){return x-y});
min = arr[0]; // 2
max = arr[arr.length - 1]; // 14
Note that a custom comparison function is necessary since you want numerical sorting instead of lexical sorting of the string representation of the numbers. (Otherwise, "14" would be 'smaller' than "2", which is obviously not the way you want it.)
For the record, I agree with Mike Samuel on the other issues with your code.
Array.prototype.reduce allows you to fold over an array.
var min = markArr.reduce(
function (a,b) { return Math.min(a, b); },
Infinity);
var max = markArr.reduce(
function (a,b) { return Math.max(a, b); },
-Infinity);
var mean = markArr.reduce(function (a, b) { return a + b; }, 0)
/ markArr.length;
You've got a number of issues with your code though.
var markArr = [mark];
var Student = prompt("Enter Student Name: ", "Name");
var mark = prompt("Enter Student Mark: ", 50);
You're using mark to initialize markArr before reading mark.
Also, mark is read as a string.
You should reorder your statements so that you initialize variables before using them, and you
should make sure mark ends up as a numeric value.
var mark = +prompt("Enter Student Mark: ", 50);
The + before prompt coerces the string returned by prompt to a number.
Related
Goal
I am at the final stage of scripting a Luhn algorithm.
Problem
Let's say I have a final calculation of 73
How can I round it up to the next 0? So the final value is 80.
And lastly, how can I get the value that made the addition? e.g. 7 is the final answer.
Current code
function validateCred(array) {
// Array to return the result of the algorithm
const algorithmValue = [];
// Create a [2, 1, 2] Pattern
const pattern = array.map((x, y) => {
return 2 - (y % 2);
});
// From given array, multiply each element by it's pattern
const multiplyByPattern = array.map((n, i) => {
return n * pattern[i];
});
// From the new array, split the numbers with length of 2 e.g. 12 and add them together e.g. 1 + 2 = 3
multiplyByPattern.forEach(el => {
// Check for lenght of 2
if(el.toString().length == 2) {
// Split the number
const splitNum = el.toString().split('');
// Add the 2 numbers together
const addSplitNum = splitNum.map(Number).reduce(add, 0);
// Function to add number together
function add(accumalator, a) {
return accumalator + a;
}
algorithmValue.push(addSplitNum);
}
// Check for lenght of 1
else if(el.toString().length == 1){
algorithmValue.push(el);
}
});
// Sum up the algorithmValue together
const additionOfAlgorithmValue = algorithmValue.reduce((a, b) => {
return a + b;
});
// Mod the final value by 10
if((additionOfAlgorithmValue % 10) == 0) {
return true;
}
else{
return false;
}
}
// Output is False
console.log(validateCred([2,7,6,9,1,4,8,3,0,4,0,5,9,9,8]));
Summary of the code above
The output should be True. This is because, I have given the total length of 15 digits in the array. Whereas it should be 16. I know the 16th value is 7, because the total value of the array given is 73, and rounding it up to the next 0 is 80, meaning the check digit is 7.
Question
How can I get the check number if given array length is less than 15?
You could do something like this:
let x = [73,81,92,101,423];
let y = x.map((v) => {
let remainder = v % 10;
let nextRounded = v + (10-remainder);
/* or you could use
let nextRounded = (parseInt(v/10)+1)*10;
*/
let amountToNextRounded = 10 - remainder;
return [nextRounded,amountToNextRounded];
});
console.log(y);
EDIT
As noticed by #pilchard you could find nextRounded using this more simplified way:
let nextRounded = v + (10-remainder);
https://stackoverflow.com/users/13762301/pilchard
I think what you need is this:
var oldNum = 73
var newNum = Math.ceil((oldNum+1) / 10) * 10;;
Then check the difference using this:
Math.abs(newNum - oldNum);
As the topic states what is the best way to make it so that when you pass an array of emotions/values, to show the closest value based on a numeric mapping in javascript?.
Assume that 'Glad' is the same thing as 'Happy', and 'Down' is the same thing as 'Sad'. Ithe code I've tried seems incredibly lengthy and gets bloated if I add more emotions/states (i.e. Angry). Aside from the emotions array, any new functions and data structures and variables can be changed/introduced.
for example, I can get a list of emotions:
let emotions = ['Happy','Happy','Sad','Glad','Angry'];
Now I want to return a string that reflects what the 'closest' emotion based on these 5 emotions.
For a better example, let's assume the values correspondent to each emotion is:
Angry = 1, Happy = 2, Sad = 3
I was trying something like:
var numb = 0;
for (var i = 0; i < emotions.length; i++) {
if (numb == 'Angry')
numb += 1;
if (numb == 'Happy' || numb == 'Glad')
numb += 2;
if (numb == 'Sad' || numb == 'Down')
numb += 3;
}
var average = numb / emotions.length;
// check which number is closer to
if (average < 1.5)
return 'Angry';
if (average >= 1.5 && < 2.5)
return 'Happy';
if (average > 2.5)
return 'Sad';
if (average == 1.5)
return 'Angry or Happy';
if (average == 2.5)
return 'Happy or Sad';
My expected result based on this list of emotions is:
2(*Happy*) + 2(*Happy*) + 3(*Sad*) + 2(*Happy|Glad*) + 1(*Angry*) = 10
Then divide by 5 (the emotions array length), resulting in 2.
So the result that should be returned, as string, is "Happy".
Let's say I added a fourth type of emotion/feeling... I would be adding more and more of these conditions, and it gets more complicated in the logic checking for the ranges of the numbers.
I am looking at the list of emotions as a whole, and trying to come up with an overall emotion that represents the whole list.
What is the best way to do this so that the code looks clean and I can support more states without having the lines of code become too long?
What about something like this:
Having two object constants:
emotionsValues: Here you assing a value to each emotion you want, like a score to each.
emotionsRank: Here is the final result of each value, based on average you'll get the result from here.
Now:
Receive the emotions array by parameter.
reduce it based on the value of each mapped emotion (using emotionsValues).
Get the average
See if the floor value + ceil value divided by 2 is equal to the number itself (it means its exactly the half), so use the "emotion or emotion".
OR, if not the half, then round to the nearest and get the correct emotion. Don't forget to check if average is below 1 or bigger the the last rank (3 in this case)
const emotionsValues = {
"Angry": 1,
"Happy": 2,
"Glad": 2,
"Sad": 3,
"Down": 3,
}
const emotionsRank = {
1: "Angry",
2: "Happy",
3: "Sad",
}
function getEmotion(arrayEmot) {
let numb = arrayEmot.reduce((acc, v) => Number(emotionsValues[v]) + acc, 0);
let avg = numb / arrayEmot.length;
let min = Math.floor(avg)
let max = Math.ceil(avg)
if ((min + max) / 2 == avg && min != max) {
return emotionsRank[min] + " or " + emotionsRank[max]
} else {
let rounded = avg < 1 ? 1 : avg > 3 ? 3 : Math.round(avg);
return emotionsRank[rounded];
}
}
let emotionsTest = ['Happy', 'Happy', 'Sad', 'Glad', 'Angry'];
console.log(getEmotion(emotionsTest))
let emotionsTest2 = ['Happy', 'Happy', 'Sad', 'Sad'];
console.log(getEmotion(emotionsTest2))
You may create the function emo to value and its reciprocal one: value to emotionS:
Then you map every emotions found in array to its value
do your standard mathematical stuff
and get back to emotions via the reciprocal function
const emoToValue = {
Glad: 1,
Happy: 1,
Sad: 2
}
const valueToEmos = Object.entries(emoToValue).reduce((acc, [emo, val]) => {
acc[val] = acc[val] || []
acc[val].push(emo)
return acc
}, {})
//compute the average:
function avgEmotion (emotions) {
if (emotions.length == 0) return ''
const avg = emotions.reduce((s, em) => s + emoToValue[em], 0) / emotions.length
return valueToEmos[Math.round(avg)].join(' or ')
}
console.log('str', avgEmotion(['Happy', 'Happy', 'Sad', 'Happy'])) //Glad or Happy
console.log('str', avgEmotion(['Happy', 'Happy', 'Sad', 'Sad'])) //Sad
This function explicitly checks for the "mid" case and also for out of range values (since it's based on indices):
function getEmotion(emotions, value) {
// Out of range
if ( value > emotions.length ) return emotions[emotions.length - 1];
if ( value < 1 ) return emotions[0];
// Determine if decimal is .5
let mid = value % 1 === .5;
// Round the value to the nearest integer
let rounded = Math.round(value);
return mid ? `${emotions[rounded - 2]} or ${emotions[rounded - 1]}` : emotions[rounded - 1];
}
Output:
let emotions = ['Happy', 'Happy', 'Sad', 'Glad', 'Angry'];
console.log(getEmotion(emotions, -23)); // Happy
console.log(getEmotion(emotions, 0)); // Happy
console.log(getEmotion(emotions, 1)); // Happy
console.log(getEmotion(emotions, 2.43)); // Happy
console.log(getEmotion(emotions, 2.5)); // Happy or Sad
console.log(getEmotion(emotions, 3.1)); // Sad
console.log(getEmotion(emotions, 155.65)); // Angry
You could create a set of indices and get the values by filtering with the index.
function getEmotion(emotions, value) {
var values = new Set([value + 0.5, value - 0.5, Math.round(value)]);
return emotions.filter((e, i) => values.has(i + 1)).join(' and ');
}
console.log(getEmotion(['Happy', 'Sad', 'Glad', "Angry"], 1));
console.log(getEmotion(['Happy', 'Sad', 'Glad', "Angry"], 1.5));
console.log(getEmotion(['Happy', 'Sad', 'Glad', "Angry"], 1.7));
i got stucked in a chalenge in codeFights.my code pass the simple test and fail in just 2 from five of hidden tests her is the chalenge instruction:
Ratiorg got statues of different sizes as a present from CodeMaster for his birthday, each statue having an non-negative integer size. Since he likes to make things perfect, he wants to arrange them from smallest to largest so that each statue will be bigger than the previous one exactly by 1. He may need some additional statues to be able to accomplish that. Help him figure out the minimum number of additional statues needed.
Example
For statues = [6, 2, 3, 8], the output should be
makeArrayConsecutive2(statues) = 3.
Ratiorg needs statues of sizes 4, 5 and 7.
Input/Output
[time limit] 4000ms (js)
[input] array.integer statues
An array of distinct non-negative integers.
Constraints:
1 ≤ statues.length ≤ 10,
0 ≤ statues[i] ≤ 20.
[output] integer
The minimal number of statues that need to be added to existing statues such that it contains every integer size from an interval [L, R] (for some L, R) and no other sizes.
and here is my code :
function makeArrayConsecutive2(statues) {
//range the table from min to max
var rang=statues.sort();
var some=0;
//if the table is one element
if(rang.length-1==0){
return 0;
}else{
//if the table contain more then one element
for(i=0;i<=rang.length-2;i++){
//add the deference of two consecutive position -1
//to find the number of missing numbers
some+=(rang[i+1]-rang[i]-1);
}
return some;
}
}
Everything is correct, except the sorting part.
You have used sort function to sort the array in increasing order
var rang = statues.sort();
But if sort function is not provided a compare function, it converts its elements in strings and then sort it in unicode order.
For eg: [2,1,11] will be sorted as [1,11,2] which will give undesired output.
Correct way is
var rang = statues.sort(function (a, b){
return (a - b)
});
SO THE LOGIC TO SOLVE THIS QUESTION IS:
Find the Smallest and Largest Element in Array.
Get the count of can say, difference of Largest and Smallest value of array in order to calculate, how many elements must be there to make it as a continuous array
. Like from 5 to 9, count of total elements must be 5 ( i.e.5,6,7,8,9) and also add 1 to the result to make count inclusive.
Find the Length of the Array
Subtract the count i.e. "difference of largest and smallest value " with the length of array
PYTHON CODE (For explanation):
def makeArrayConsecutive2(statues):
max_height = max(statues)
min_height = min(statues)
array_length = len(statues)
count_of_element = max_height - min_height + 1
# '1 ' is added to make it inclusive
return count_of_element-array_length
and Python one liner :
def makeArrayConsecutive2(statues):
return max(statues)-min(statues)-len(statues)+1
I agree with Deepak's Solution. The question is ready not about sorting but helping to figure out the minimum number of additional statues needed. You only need to get the max and min values.
int makeArrayConsecutive2(int[] statues)
{
int min=Integer.MAX_VALUE,max=-1;
for(int i=0;i<statues.length;i++)
{
if(statues[i] < min){ min = statues[i]; }
if(statues[i] > max){ max = statues[i]; }
}
return (max-min)+1 - statues.length;
}
Solution in typescript. Create a new array from the min and max from the status array using a for loop. Subtract new array length with status array length.
function makeArrayConsecutive2(statues: number[]): number {
let min = Math.min(...statues);
let max = Math.max(...statues);
let arr = [];
for (let i = min; i <= max; i++) {
arr.push(i);
}
return arr.length - statues.length;
}
function makeArrayConsecutive2(statues) {
const nums = [];
for (let i = Math.min(...statues); i <= Math.max(...statues); i++) {
if (!statues.includes(i)) {
nums.push(i);
}
}
return nums.length;
}
console.log(makeArrayConsecutive2([6, 2, 3, 8]))
Sorting (nlogn)is not required. Below is the solution in Java.
int makeArrayConsecutive2(int[] statues) {
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int i = 0; i < statues.length; i++) {
max = Math.max(max, statues[i]);
min = Math.min(min, statues[i]);
}
return (max - min) + 1 - statues.length;
}
This Code works
var statues = [2, 3, 6, 8];
var newStatues = [];
Function declaration
function makeArrayConsecutive2(statues) {
statues.sort(function(a, b) { return a - b });
for(var i = statues[0]; i <= statues[statues.length-1]; i++) {
newStatues.push(i);
}
return console.log(newStatues.length - statues.length);
}
Function Calling
makeArrayConsecutive2(statues);
Best solution goes here in just O(1) complexity:
let n = statues.length;
let max = Math.max.apply(null, statues);
let min = Math.min.apply(null, statues);
return max - min - n + 1;
function makeArrayConsecutive2(statues) {
var rang = statues.sort(function (a, b){
return (a - b)
});
var some=0;
if(rang.length-1==0){
return 0;
}else{
for(i=0;i<=rang.length-2;i++){
some+=(rang[i+1]-rang[i]-1);
}
return some;
}
}
function makeArrayConsecutive2(statues) {
const n = statues.length;
const min = Math.min(...statues);
const max = Math.max(...statues);
return max - min - n + 1;
}
If we subtract the minimum from the maximum element, then we get the number of elements that should be in the final array. Now subtract the already existing number of elements from this amount and add 1, then we get the result we need - the number of missing elements
Just for fun in C#
static int makeArrayConsecutive2(int[] statues)
{
List<int> ConsecutiveNums = new List<int>();
for(int i = statues.Min(); i != statues.Max() + 1; i++)
ConsecutiveNums.Add(i);
return ConsecutiveNums.Count - statues.Length;
}
function makeArrayConsecutive2(statues) {
return Math.max(...statues) - Math.min(...statues) + 1 -(statues.length)
}
I don't think we need a Looping there, that's my solution
you can try using for loop and ternary operation by the following code
def makeArrayConsecutive2(statues):
count=0
for i in range (min(statues),max(statues)):
count=count+1 if i not in statues else count
return count
function makeArrayConsecutive2(statues) {
s = statues.sort(function(a, b){return a - b});
n = statues.length;
val = 0;
for (let i=0;i<n-1;i++) {
val += (Math.abs(s[i]-s[i+1]))-1;
}
return val;
}
sort(statues.begin(), statues.end());
int count = 0;
for(int i = 1;i<statues.size(); i++){
int diff = statues[i]-statues[i-1];
if(diff>1){
count+=diff-1;
}
}
return count;
Solution in PHP
function solution($statues) {
return max($statues) - min($statues) - count($statues) + 1;
}
PHP solution for question.
function solution($statues) {
sort($statues);
$missing = 0;
$lowest = min($statues);
$highest = max($statues);
$numbers = range($lowest, $highest);
foreach($numbers as $number){
if(!in_array($number, $statues)){
$missing++;
}
}
return $missing;
}
here is code in python
def solution(statues):
statues.sort()
c = 0
for i in range(len(statues)-1):
if statues[i+1]-statues[i] > 1:
c += statues[i+1]-statues[i] -1
return (c)
I want to convert a number to its corresponding alphabet letter. For example:
1 = A
2 = B
3 = C
Can this be done in javascript without manually creating the array?
In php there is a range() function that creates the array automatically. Anything similar in javascript?
Yes, with Number#toString(36) and an adjustment.
var value = 10;
document.write((value + 9).toString(36).toUpperCase());
You can simply do this without arrays using String.fromCharCode(code) function as letters have consecutive codes. For example: String.fromCharCode(1+64) gives you 'A', String.fromCharCode(2+64) gives you 'B', and so on.
Snippet below turns the characters in the alphabet to work like numerical system
1 = A
2 = B
...
26 = Z
27 = AA
28 = AB
...
78 = BZ
79 = CA
80 = CB
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var result = ""
function printToLetter(number){
var charIndex = number % alphabet.length
var quotient = number/alphabet.length
if(charIndex-1 == -1){
charIndex = alphabet.length
quotient--;
}
result = alphabet.charAt(charIndex-1) + result;
if(quotient>=1){
printToLetter(parseInt(quotient));
}else{
console.log(result)
result = ""
}
}
I created this function to save characters when printing but had to scrap it since I don't want to handle improper words that may eventually form
Just increment letterIndex from 0 (A) to 25 (Z)
const letterIndex = 0
const letter = String.fromCharCode(letterIndex + 'A'.charCodeAt(0))
console.log(letter)
UPDATE (5/2/22): After I needed this code in a second project, I decided to enhance the below answer and turn it into a ready to use NPM library called alphanumeric-encoder. If you don't want to build your own solution to this problem, go check out the library!
I built the following solution as an enhancement to #esantos's answer.
The first function defines a valid lookup encoding dictionary. Here, I used all 26 letters of the English alphabet, but the following will work just as well: "ABCDEFG", "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", "GFEDCBA". Using one of these dictionaries will result in converting your base 10 number into a base dictionary.length number with appropriately encoded digits. The only restriction is that each of the characters in the dictionary must be unique.
function getDictionary() {
return validateDictionary("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
function validateDictionary(dictionary) {
for (let i = 0; i < dictionary.length; i++) {
if(dictionary.indexOf(dictionary[i]) !== dictionary.lastIndexOf(dictionary[i])) {
console.log('Error: The dictionary in use has at least one repeating symbol:', dictionary[i])
return undefined
}
}
return dictionary
}
}
We can now use this dictionary to encode our base 10 number.
function numberToEncodedLetter(number) {
//Takes any number and converts it into a base (dictionary length) letter combo. 0 corresponds to an empty string.
//It converts any numerical entry into a positive integer.
if (isNaN(number)) {return undefined}
number = Math.abs(Math.floor(number))
const dictionary = getDictionary()
let index = number % dictionary.length
let quotient = number / dictionary.length
let result
if (number <= dictionary.length) {return numToLetter(number)} //Number is within single digit bounds of our encoding letter alphabet
if (quotient >= 1) {
//This number was bigger than our dictionary, recursively perform this function until we're done
if (index === 0) {quotient--} //Accounts for the edge case of the last letter in the dictionary string
result = numberToEncodedLetter(quotient)
}
if (index === 0) {index = dictionary.length} //Accounts for the edge case of the final letter; avoids getting an empty string
return result + numToLetter(index)
function numToLetter(number) {
//Takes a letter between 0 and max letter length and returns the corresponding letter
if (number > dictionary.length || number < 0) {return undefined}
if (number === 0) {
return ''
} else {
return dictionary.slice(number - 1, number)
}
}
}
An encoded set of letters is great, but it's kind of useless to computers if I can't convert it back to a base 10 number.
function encodedLetterToNumber(encoded) {
//Takes any number encoded with the provided encode dictionary
const dictionary = getDictionary()
let result = 0
let index = 0
for (let i = 1; i <= encoded.length; i++) {
index = dictionary.search(encoded.slice(i - 1, i)) + 1
if (index === 0) {return undefined} //Attempted to find a letter that wasn't encoded in the dictionary
result = result + index * Math.pow(dictionary.length, (encoded.length - i))
}
return result
}
Now to test it out:
console.log(numberToEncodedLetter(4)) //D
console.log(numberToEncodedLetter(52)) //AZ
console.log(encodedLetterToNumber("BZ")) //78
console.log(encodedLetterToNumber("AAC")) //705
UPDATE
You can also use this function to take that short name format you have and return it to an index-based format.
function shortNameToIndex(shortName) {
//Takes the short name (e.g. F6, AA47) and converts to base indecies ({6, 6}, {27, 47})
if (shortName.length < 2) {return undefined} //Must be at least one letter and one number
if (!isNaN(shortName.slice(0, 1))) {return undefined} //If first character isn't a letter, it's incorrectly formatted
let letterPart = ''
let numberPart= ''
let splitComplete = false
let index = 1
do {
const character = shortName.slice(index - 1, index)
if (!isNaN(character)) {splitComplete = true}
if (splitComplete && isNaN(character)) {
//More letters existed after the numbers. Invalid formatting.
return undefined
} else if (splitComplete && !isNaN(character)) {
//Number part
numberPart = numberPart.concat(character)
} else {
//Letter part
letterPart = letterPart.concat(character)
}
index++
} while (index <= shortName.length)
numberPart = parseInt(numberPart)
letterPart = encodedLetterToNumber(letterPart)
return {xIndex: numberPart, yIndex: letterPart}
}
this can help you
static readonly string[] Columns_Lettre = new[] { "A", "B", "C"};
public static string IndexToColumn(int index)
{
if (index <= 0)
throw new IndexOutOfRangeException("index must be a positive number");
if (index < 4)
return Columns_Lettre[index - 1];
else
return index.ToString();
}
I am trying to create a alphanumeric serial number in Javascript, the serial number is governed by the following rules:
3-Digit Alphanumeric Series
Allowed values 1-9 (Zero is excluded) and A-Z (All Capitals with exclusions of I and O)
The code should be able to give the next number after getting the input number.
The last part is tricky, basically the code would fetch the existing value of the serial number and it would then give the output as the next number.
For example: If the input number 11D then the output number should be 11E. Please let me know if this description is good enough to explain my requirement.
The excel sheet for the same is attached here
Also the part of the code where the script would fetch the starting value 11D would be from this code:
cur_frm.add_fetch('item_group','serial_number','serial_number');
This should do it:
var nextSerialNumber = function(serialNumber) {
return (parseInt(serialNumber, 36) + 1).toString(36).replace(
/i/g,'j').replace(/o/g, 'p').replace(/0/g, '1').toUpperCase();
}
nextSerialNumber("99Z") //=> "9A1"
nextSerialNumber("11D") //=> "11E"
I'm not sure what you want to happen after ZZZ. It jumps to 1111, but that could be changed.
If you input an invalid serial number (e.g. 11I), it gives you the next valid number (e.g. 11J).
var alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
var alphabetLen = alphabet.length;
function nextDigit(digit) {
nextDigitPos = (alphabet.indexOf(digit)+1) % alphabetLen;
return alphabet.charAt(nextDigitPos);
}
/**
* Computes the next serial id.
* #param id the id to compute the successor of,
* if null or empty String the first id
* "111" is returned.
*/
function nextSerial(id) {
if(id==null || id.length==0) return "111";
var digits = id.split("");
digits[2] = nextDigit(digits[2]);
if(digits[2] == "1") /* overflow */ {
digits[1] = nextDigit(digits[1]);
if(digits[1] == "1") /* overflow */ {
digits[0] = nextDigit(digits[0])
}
}
return digits.join("");
}
This should do it:
function getNext(num) {
var alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
var digits = num.toUpperCase().split(""),
len = digits.length,
increase = true;
if (len != 3)
throw new Error("Invalid serial number length in getNext: "+num);
for (var i=len-1; increase && i>=0; i--) {
var val = alphabet.indexOf(digits[i]);
if (val == -1)
throw new Error("Invalid serial number digit in getNext: "+num);
val++;
if (val < alphabet.length) {
digits[i] = alphabet[val];
increase = false;
} else { // overflow
digits[i] = alphabet[0];
}
}
if (increase) // is still true
throw new Error("Serial number overflow in getNext");
num = digits.join("");
return num;
}
Since you are working with a nearly alphanumeric alphabet, a parseInt/toString with radix 33 might have done it as well. Only you need to "jump" over the 0, I and O, that means replacing 0,A,B… by A,B,C…, replacing H,I,J… by J,K,L… and replacing M,N,O… by P,Q,R… (and everything back on deserialisation) - which might be OK if JS has a numeric char datatype, but I think it's easier to do it manually as above.
If you're curious:
String.prototype.padLeft = function(n, x) {
return (new Array(n).join(x || "0")+this).slice(-n);
};
function getNext(num) {
var alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
var back = {}, forth = {};
for (var i=0; i<alphabet.length; i++) {
var a = alphabet[i],
b = i.toString(36);
back[a] = b;
forth[b] = a;
}
return (parseInt(num.replace(/./g, function(c) {
return back[c]; // base33 from alphabet
}), alphabet.length) + 1)
.toString(alphabet.length)
.padLeft(3)
.replace(/./g, function(c) {
return forth[c]; // base33 to alphabet
});
}