I need to decode base36 string to double. The actual double value is 0.3128540377812142. Now when I am converting it to base 36:
(0.3128540377812142).toString(36);
Results are :
Chrome: 0.b9ginb6s73gd1bfel7npv0wwmi
Firefox: 0.b9ginb6s73e
Now my question is:
1) Is there any way to get same base 36 result for all browsers ?
2) How to decode them back to double value ?
For converting from string (up to base 36) to a number you can use this.
String.prototype.toNumber = function(base) {
var resultNumber = 0;
var inMantissa = false;
var mantissaDivisor;
var currentCharCode;
var digitValue;
if (typeof base === "undefined" || base === "" || base === null) {
base = 10;
}
base = parseInt(base);
if (isNaN(base) || base > 36 || base < 2) {
return NaN;
}
for(var i=0; i<this.length; i++) {
currentCharCode = this.charCodeAt(i);
if (currentCharCode === 46 && !inMantissa) {
// we're at the decimal point
inMantissa = true;
mantissaDivisor = 1;
} else {
if (currentCharCode >= 48 && currentCharCode <= 57) {
// 0-9
digitValue = currentCharCode - 48;
} else if (currentCharCode >= 65 && currentCharCode <= 90) {
// A-Z
digitValue = currentCharCode - 55;
} else if (currentCharCode >= 97 && currentCharCode <= 122) {
// a-z
digitValue = currentCharCode - 87;
} else {
return NaN;
}
if (digitValue > base - 1) {
return NaN;
}
if (inMantissa) {
mantissaDivisor *= base;
resultNumber += digitValue/mantissaDivisor;
} else {
resultNumber = (resultNumber * base) + digitValue;
}
}
}
return resultNumber;
}
Here's a fiddle: http://jsfiddle.net/ugshkp4d/25/
Related
Hi This is my first time using this website, I did do some research about how to convert lowercase letter to uppercase letter but still filles. The requirement is to check if "even", covert the even digit letter to different type(lower to upper or upper to lower). below is my code:
function question4(str,pos)
{ var newLetter;
var kkk=str;
if (pos='even')
{
for (var i=0;i<str.length;i=i+2)
{
if (str[i].toString()==str[i].toString().toUpperCase())
{
newLetter=str[i].toString().toLowerCase();
kkk[i]=newLetter;
}else
{
newLetter=str[i].toUpperCase();
kkk[i]=newLetter;
}
}
}else if (pos='odd')
for ( i=0;i<str.length;i=i+2)
{
if (str[i]===str[i].toLowerCase())
{
alert('3');
}else if (str[i]===str[i].toUpperCase())
{
alert('4');
}
}
return kkk;
}
the requirement is: Write a function to change the case of all the characters in string based on their position which matches the value of the pos parameter function. function (str, pos [even|odd]). Example ( (‘abCd’, ‘odd’) return Abcd)
Update: now I have make "odd" condition working, but "even "still is not working, can any one take a look why?
function question4(strr,pos) {
var result ;
var sum="";
var aaa;
for (var i = 0; i <= strr.length - 1; i = i + 1)
{
if (pos == "odd"&&i%2==0)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result = String.fromCharCode(aaa + 32);
} else
result = String.fromCharCode(aaa - 32);
}
else if (pos == "even"&&i%2==1)
{
if (aaa >= 65 && aaa <= 90 )
{
result= String.fromCharCode(aaa + 32);
} else
result = String.fromCharCode(aaa - 32);
}else result=strr[i];
sum+=result;
}
return sum;
}
To achieve this, you can construct a string by concating char by char:
function question4(strInput, pos) {
let str = ""; // The string to construct
if (!pos || (pos !== "even" && pos !== "odd")) { // Validating pos
throw "invalid pos";
}
for (var i=0;i<strInput.length;i++) // Looping on strInput
{
let huPos = i + 1;
if ((pos === "even" && huPos%2 == 1) ||
(pos === "odd" && huPos%2 == 0)) {
/* If we want switch odd and we are on even position or if we want switch even and we are on odd position, then we add the original char
*/
str += strInput[i];
}
else {
// In others case, we switch lower to upper and upper to lower
let char = strInput[i];
str += char == char.toUpperCase() ? char.toLowerCase() : char.toUpperCase();
}
}
return str;
}
console.log(question4('abCdef', "odd")); // Return "AbcdEf"
Associated bin
EDIT:
After seeing edit, i can see you want to do it without using toLower/UpperCase. As stated in comment i think it is a bad idea in js, but to experiment you can achieve this:
const reverser = {
"a": "a".charCodeAt(0),
"z": "z".charCodeAt(0),
"A": "A".charCodeAt(0),
"Z": "Z".charCodeAt(0),
};
const conversionValueToLower = reverser.a - reverser.A;
const conversionValueToUpper = reverser.A - reverser.a;
function reverseChar(char) {
var code = char.charCodeAt(0);
// If you want to go from upper to lower
if (code >= reverser.A && code <= reverser.Z) {
// Simply add the difference between lower and upper
return String.fromCharCode(code + conversionValueToLower);
} // Same logic here
else if (code >= reverser.a && code <= reverser.z) {
return String.fromCharCode(code + conversionValueToUpper);
}
/**
Or use if you want full digit
if (code <= 90 && code >= 65) {
return String.fromCharCode(code + 32);
}
else if (code >= 97 && code <= 122) {
return String.fromCharCode(code - 32);
}
**/
return char; // Other case return original char
}
function question4(strInput, pos) {
let str = "";
if (!pos || (pos !== "even" && pos !== "odd")) {
throw "invalid pos";
}
for (var i=0;i<strInput.length;i++)
{
let huPos = i + 1;
if ((pos === "even" && huPos%2 == 1) ||
(pos === "odd" && huPos%2 == 0)) {
str += strInput[i];
}
else {
str += reverseChar(strInput[i]);
}
}
return str;
}
console.log(question4('abCdef', "odd")); // return "AbcdEf"
Associated bin
Another way could be to code utils functions imitating toLower/UpperCase
I corrected your code in your answer aswell, without changing original logic
function question4(strr,pos) {
var result ;
var sum="";
var aaa;
for (var i = 0; i <= strr.length - 1; i = i + 1)
{
if (pos == "odd"&&i%2==0)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result = String.fromCharCode(aaa + 32);
} else if(aaa >=97&&aaa <=122)
{ result = String.fromCharCode(aaa - 32);}
else {result=strr[i];}
}
else if (pos == "even"&&i%2==1)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result= String.fromCharCode(aaa + 32);
} else if(aaa >=97&&aaa <=122)
{ result = String.fromCharCode(aaa - 32);}
else {result=strr[i];}
}else {result=strr[i];}
sum+=result;
}
return sum;
}
console.log(question4("abCd", "odd")) // return Abcd;
A simple solution for this question
// Function used to invert the letter case
const changeCase = c => {
if (c === c.toUpperCase()) return c.toLowerCase()
return c.toUpperCase()
}
const swapCaseConditional = (str, pos) => {
// Use split method to convert string into array and map the array
return str.split('').map((c, index) => {
if (pos === 'even') {
// if pos and index are even, change the letter case
if (index % 2) return changeCase(c)
return c
}
else {
// if pos and index are odd, change the letter case
if (!(index%2)) return changeCase(c)
return c
}
// Convert to string
}).join('')
}
console.log(swapCaseConditional('abCd', 'odd'))
I worked two nights and finally got it working. although not fully cover all the situations, but almost there.
function question4(strr,pos) {
var result ;
var sum="";
var aaa;
for (var i = 0; i <= strr.length - 1; i = i + 1)
{
if (pos == "odd"&&i%2==0)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result = String.fromCharCode(aaa + 32);
} else
result = String.fromCharCode(aaa - 32);
}
else if (pos == "even"&&i%2==1)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result= String.fromCharCode(aaa + 32);
} else if(aaa >=97&&aaa <=122)
{ result = String.fromCharCode(aaa - 32);}
else {result=strr[i];}
}else {result=strr[i];}
sum+=result;
}
return sum;
}
I have two number range.
Lets say 1st rage is 6-9 and second is 1-15
I need to check that if it is conflicting. I mean if 1-15 is crossing 6-9,
Valid ranges are
1-5,
10-15
but 1-15, 2-18 like this should return me that it is violating 6-9.
Currently I am checking only signle digit if it falls between range,
if (typeof (Number.prototype.isBetween) === "undefined") {
Number.prototype.isBetween = function (min, max, notBoundaries) {
var between = false;
if (notBoundaries) {
if ((this < max) && (this > min)) between = true;
alert('notBoundaries');
} else {
if ((this <= max) && (this >= min)) between = true;
alert('Boundaries');
}
alert('here');
return between;
}
}
But now I need to check range. Any help is appreciated
Making use of your function, I added a new function to compare ranges
if (typeof (Number.prototype.isBetween) === "undefined") {
Number.prototype.isBetween = function (min, max, notBoundaries) {
var between = false;
if (notBoundaries) {
if ((this < max) && (this > min)) between = true;
} else {
if ((this <= max) && (this >= min)) between = true;
}
return between;
}
}
if (typeof (Array.prototype.isRangeCrossed) === "undefined") {
Array.prototype.isRangeCrossed = function (target,notBoundaries) {
var result = false;
if ((target[0].isBetween(this[0],this[1],notBoundaries) ) || (target[1].isBetween(this[0],this[1],notBoundaries))){
result = true;
}
return result;
}
}
var range1 = [6,9];
var range2 = [1,15];
var range3 = [2,5];
console.log(range2.isRangeCrossed(range1,false));
console.log(range3.isRangeCrossed(range1,false));
If you want a pure function, this should suffice:
var rangesOverlap = function(n1, n2, r1, r2, boundaries) {
if (boundaries) {
return n1 >= n2 || n2 >= r1 || r1 >= r2;
} else {
return n1 > n2 || n2 > r1 || r1 > r2;
}
}
n1 and n2 are the first range, r1 and r2 are the second range, and boundaries indicate allowing overlaps on the boundary.
On the Array prototype, where comp is the 2nd range array:
Array.prototype.rangesOverlap = function(comp, boundaries) {
if (boundaries) {
return this[0] > this[1] || this[1] > comp[0] || comp[0] > comp[1];
} else {
return this[0] >= this[1] || this[1] >= comp[0] || comp[0] >= comp[1];
}
}
See this JSFiddle for a working example.
You can simplify your range checking code.
if (typeof(Number.prototype.isBetween) === 'undefined') {
Number.prototype.isBetween = function(min, max, inclusive) {
return inclusive ? (this <= max && this >= min) : (this < max && this > min);
}
}
var range = { min : 7, max : 12 };
var validMinInclusive = range.min.isBetween(range.min, range.max, true);
var validMaxInclusive = range.max.isBetween(range.min, range.max, true);
var invalidMinExclusive = range.min.isBetween(range.min, range.max, false);
var invalidMaxExclusive = range.max.isBetween(range.min, range.max, false);
console.log(validMinInclusive, validMaxInclusive, invalidMinExclusive, invalidMaxExclusive);
The following code constructs a Range object with a method for checking if another range fits inside of it. There is an inclusive flag like the one used in the above code.
function Range(min, max) {
if (arguments.length === 0) {
throw 'Range must include at least one value.';
}
if (arguments.length === 1) {
max = min;
min = 0;
}
this.min = min;
this.max = max;
}
Range.inBounds = function(outer, inner, inclusive) {
return inclusive
? (inner.min >= outer.min && inner.max <= outer.max)
: (inner.min > outer.min && inner.max < outer.max);
};
Range.prototype.inBounds = function(target, inclusive) {
return Range.inBounds(this, target, inclusive);
};
var rangeInner = new Range(6, 9);
var rangeOuter = new Range(1, 15);
var validRangeBounds = rangeOuter.inBounds(rangeInner, false); // true
var invalidRangeBounds = rangeInner.inBounds(rangeOuter, false); // false
console.log(validRangeBounds, invalidRangeBounds);
Currently it validates to true(passes the test) even if username contains just text, or just number characters alone. I want the validation to only be true(Passed) if and only if the username contains both text and number characters and fail otherwise.
How do I implement that? Thank you.
function isUser(username)
{
var numaric = username;
for(var j=0; j<numaric.length; j++)
{
var alphaa = numaric.charAt(j);
var hh = alphaa.charCodeAt(0);
if ((hh > 96 && hh<123) || (hh > 64 && hh<91) == false) { //A-Z - a-z
} else if ((hh > 47 && hh<58) ==false){ //0-9
} else if (true == (hh > 96 && hh<123) || (hh > 64 && hh<91) || (hh > 47 && hh<58)) { //A~Z - a~z - 1~9
} else {
alert("Your Alpha Numeric Test Falid");
return false;
}
alert("Your Alpha Numeric Test passed");
return true;
}
}
It seems that you want to check for a alphanumeric username without RegExp.
ABC
//fail
123
//fail
abc123
//pass
abc123$_
//fail
function isUser(username)
{
var numaric = username;
var num, alp;
for(var j=0; j<numaric.length; j++)
{
var alphaa = numaric.charAt(j);
var hh = alphaa.charCodeAt(0);
if(!((hh>=48&&hh<=57)||(hh>=97&&hh<=122)||(hh>=65&&hh<=90))) //if hh is anything other than letter or number return false
{
alert('Test failed. Non-alphanumeric characters are present.');
return false;
}
else
{
if(hh>=47&&hh<=57) //if number
num=true;
if((hh>=97&&hh<=122)||(hh>=65&&hh<=90)) //if letter
alp=true;
}
}
if(num&&alp) //if both letter and number is present than passed
{
alert('Test passed');
return true;
}
else
{
alert('Test failed. Not alphanumeric (contains only letters or numbers).');
return false;
}
}
1.The code first checks if hh is not a letter or number, if so than returns false.
2.Otherwise,
2.1.Checks for number, if present than set num to true.
2.2.Check for letter, if present than set alp to true.
3.If both num and alp is true, ie. both letters and numbers are present than return true.
4.Otherwise, returns false.
Your question is unclear if you would accept a mix of digits and letters /^(([A-Za-z]+\d)|(\d+[A-Za-z]))[A-Za-z0-9]*$/ or if it is strictly letters trailed by digits /^+\d+$/.
// Matches /^[A-Za-z]+\d+$/
function isUser(username) {
var numaric = username;
var mode = 0;
for (var j = 0; j < numaric.length; j++) {
var alphaa = numaric.charAt(j);
var hh = alphaa.charCodeAt(0);
var letter = ((hh > 96 && hh < 123) || (hh > 64 && hh < 91));
var digit = (hh > 47 && hh < 58);
switch( mode )
{
case 0:
if( letter )
break;
else if( j == 0 )
return false;
++mode;
case 1:
if( !digit )
return false;
}
}
return mode == 1;
}
// Matches /^(([A-Za-z]+\d)|(\d+[A-Za-z]))[A-Za-z0-9]*$/
function isUser2(username) {
var numaric = username;
var found_letter = false;
var found_digit = false;
for (var j = 0; j < numaric.length; j++) {
var alphaa = numaric.charAt(j);
var hh = alphaa.charCodeAt(0);
var letter = ((hh > 96 && hh < 123) || (hh > 64 && hh < 91));
var digit = (hh > 47 && hh < 58);
if((hh > 96 && hh < 123) || (hh > 64 && hh < 91))
found_letter = true;
else if(hh > 47 && hh < 58)
found_digit = true;
else
return false;
}
return found_letter && found_digit;
}
var tests = ['test', '0030342', 'foobar4342', '31313ffefe', 'dfdf424dfdg']
tests.forEach( function(d) { console.log( 'isUser( ' + d + ' ) --> ' + isUser( d ) + ' compared to ' + /^[A-Za-z]+\d+$/.test( d ) ); } );
tests.forEach( function(d) { console.log( 'isUser2( ' + d + ' ) --> ' + isUser2( d ) + ' compared to ' + /^(([A-Za-z]+\d)|(\d+[A-Za-z]))[A-Za-z0-9]*$/.test( d )); } );
Tests:
isUser( test ) --> false compared to false
isUser( 0030342 ) --> false compared to false
isUser( foobar4342 ) --> true compared to true
isUser( 31313ffefe ) --> false compared to false
isUser( dfdf424dfdg ) --> false compared to false
isUser2( test ) --> false compared to false
isUser2( 0030342 ) --> false compared to false
isUser2( foobar4342 ) --> true compared to true
isUser2( 31313ffefe ) --> true compared to true
isUser2( dfdf424dfdg ) --> true compared to true
I'm checking for integer values in node.js using IsNaN function.
Unexpectedly, this function validates the strings like 1E267146, 1E656716 , 914E6583 to be numbers, as these strings are exponential values. Any way to work around this? In actual scenario i wont get any exponential values.
ECMA6 defines Number.isInteger as follows:
Javascript
function isInteger(nVal) {
return typeof nVal === "number" && isFinite(nVal) && nVal > -9007199254740992 && nVal < 9007199254740992 && Math.floor(nVal) === nVal;
}
but this will also accept scientific notation
console.log(isInteger(1e6));
console.log(isInteger(+"1e6"));
jsfiddle
You need to be clear as to what your definitions/expectations are.
My guess is that you may want something like this, if you are testing strings and have no limits on the max or min integer.
Javascript
function isStringNumericalInteger(testValue) {
return typeof testValue === "string" && /^[\-+]?[1-9]{1}\d+$|^[\-+]?0$/.test(testValue);
}
console.log(isStringNumericalInteger("9007199254740991"));
console.log(isStringNumericalInteger("-123216848516878975616587987846516879844651654847"));
console.log(isStringNumericalInteger("1.1"));
console.log(isStringNumericalInteger("-1.1"));
console.log(isStringNumericalInteger("1e10"));
console.log(isStringNumericalInteger("010"));
console.log(isStringNumericalInteger("0x9"));
console.log(isStringNumericalInteger(""));
console.log(isStringNumericalInteger(" "));
console.log(isStringNumericalInteger());
console.log(isStringNumericalInteger(null));
console.log(isStringNumericalInteger([]));
console.log(isStringNumericalInteger({}));
Output
true
true
false
false
false
false
false
false
false
false
false
false
false
jsfiddle
If you want to bound the range to what javascript can represent numerically as an integer then you will need to add a test for && +testValue > -9007199254740992 && +testValue < 9007199254740992
If you don't like using RegExs, you can also accomplish this with a parser. Something like this:
Javascript
function isCharacterDigit(testCharacter) {
var charCode = testCharacter.charCodeAt(0);
return charCode >= 48 && testCharacter <= 57;
}
function isStringNumericalInteger(testValue) {
var start = 0,
character,
index,
length;
if (typeof testValue !== "string") {
return false;
}
character = testValue.charAt(start);
if (character === "+" || character === "-") {
start += 1;
character = testValue.charAt(start);
}
start += 1;
length = testValue.length;
if ((length > start && character === "0") || !isCharacterDigit(character)) {
return false;
}
for (index = start; index < length; index += 1) {
if (!isCharacterDigit(testValue.charAt(index))) {
return false;
}
}
return true;
}
jsfiddle
I would use something like below code to validate number input. First I parse the given value to float and then check isNaN().
var isNumber = function (obj) {
return !isNaN(parseFloat(obj)) && isFinite(obj);
};
I think this is what you need in your case (i hate regex because this is not very good for the performance but..)
http://jsbin.com/EQiBada/1/
var NMAX = Math.pow(2, 53);
function isNumeric(n) {
n = n < 0 ? n * -1 : n;
var r = /^\d+$/.test(n);
if (r === true)
{
return parseInt(n, 10) >= (NMAX * -1) + 1 && parseInt(n, 10) <= NMAX;
}
return false;
}
Minified
var NMAX = Math.pow(2, 53);
function isNumericMin(n) {
n = n < 0 ? n * -1 : n;
return /^\d+$/.test(n) === true ? parseInt(n, 10) >= (NMAX * -1) + 1 && parseInt(n, 10) <= NMAX : false;
}
var i = '1E267146'
if(isNaN(i) || !isFinite(i) !! i=="")
{
// do stuff
}
else
{
// do stuff
}
i have to convert alphabets to corresponding numbers like i have a data like "DRSG004556722000TU77" and the index for A is 10, B is 11, C is 12 and so on up to Z is 35.
any helping tips??
here is the javascript which return me ascii code but i want to get the above indecies for respective alphabet
var string = DRSG004556722000TU77;
function getColumnName(string) {
return ((string.length - 1) * 26) + (string.charCodeAt(string.length - 1) - 64);
}
document.write( getColumnName(string) );
This may help
var output = [], code, str = 'DRSG004556722000TU77',i;
for(i in str){
code = str.charCodeAt(i);
if(code <= 90 && code >= 65){
// Add conditions " && code <= 122 && code >= 97" to catch lower case letters
output.push([i,code]);
}
}
Now ouput contains all letters codes and their corresponding indexes
var string = 'DRSG004556722000TU77';
function getColumnName(string) {
var recode = new Array(), i, n = string.length;
for(i = 0; i < n; i++) {
recode.push(filter(string.charCodeAt(i)));
}
return recode;
}
function filter(symbol) {
if ((symbol >= 65) && (symbol <= 90)) {
return symbol - 55;
} else if ((symbol >= 48) && (symbol <= 57)) {
return symbol - 48;
}
}
document.write(getColumnName(string));