I faced with a problem that string comparison in C# works a bit strange:
"0".CompareTo("#") // is 1
And I'm very surprised with that because ASCII codes is next:
ASCII '#' // 64
ASCII '0' // 48
If I'm comparing chats or use String.CompareOrdinal everything fine:
'0'>'#' // false
String.CompareOrdinal("0","#") // -16
And in JS it works also as expected:
"0" > "#" // false - in Javascript
Next thing that C# code I can't change - it uses CompareTo.
But I need same sorting rules in Javascript.
I can't find any solution smarter than replace '#' sign with the '#' because it ASCII code less than zero:
ASCII '#' // 35
Maybe somebody can explain why:
"0".CompareTo("#") // is 1
Or suggest better workaround how making comparison the same in Javascript
It's not strange, it's culture specific. I'm not an expert in js but I guess that localeCompare may help you.
CompareTo() will return 1 if the first value is meant to be sorted after the second value (in ascending order), according to its call to String.Compare(firstValue,(String)secondValue, StringComparison.CurrentCulture), which would consider 0 to come after # in a sorted list for display, so you would have #foo, 0foo, 1foo, afoo, Afoo, foo.
In JavaScript, you can pass a function to Array.sort() that would mimic the behavior for the relevant C# culture.
Related
First post on here!
I've done a couple hours of research, and I can't seem to find any actual answers to this, though it may be my understanding that's wrong.
I want to convert a string, lets say "Hello 123" into any Base N, lets say N = 32 for simplicity.
My Attempt
Using Javascript's built-in methods (Found through other websites, and):
stringToBase(string, base) {
return parseInt(string, 10).toString(base);
}
So, this encodes the string to base 10 (decimal) and then into the base I want, however the caveat with this is that it only works from 2 to 36, which is good, but not really in the range that I'm looking for.
More
I'm aware that I can use the JS BigInt, but I'm looking to convert with bases as high as 65536 that uses an arbitrary character set that does not stop when encountering ASCII or (yes I'm aware it's completely useless, I'm just having some fun and I'm very persistent). Most solutions I've seen use an alphabet string or array (e.g. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+-").
I've seen a couple threads that say that encoding to a radix which is not divisible by 2 won't work, is that true? Since base 85, 91, exist.
I know that the methods atob() and btoa() exist, but this is only for Radix/Base 64.
Some links:
I had a look at this github page: https://github.com/gliese1337/base-to-base/blob/main/src/index.ts , but it's in typescript and I'm not even sure what's going on.
This one is in JS: https://github.com/adanilo/base128codec/blob/master/b128image.js . It makes a bit more sense than the last one, but the fact there is a whole github page just for Base 128 sort of implies that they're all unique and may not be easily converted.
This is the aim of the last and final base: https://github.com/qntm/base65536 . The output of "Hello World!" for instance, is "驈ꍬ啯𒁗ꍲ噤".
(I can code java much better than JS, so if there is a java solution, please let me know as well)
I'm trying to solve a challenge on Codewars which requires you to reverse an array in JavaScript, in 16 characters or less. Using .reverse() is not an option.
The maximum number of characters allowed in your code is 28, which includes the function name weirdReverse, so that leaves you with just 16 characters to solve it in. The constraint -
Your code needs to be as short as possible, in fact not longer than 28 characters
Sample input and output -
Input: an array containing data of any types. Ex: [1,2,3,'a','b','c',[]]
Output: [[],'c','b','a',3,2,1]
The starter code given is -
weirdReverse=a=>
My solution (29 characters) is -
weirdReverse=a=>a.sort(()=>1)
which of course fails -
Code length should less or equal to 28 characters.
your code length = 29 - Expected: 'code length <= 28', instead got: 'code length > 28'
I'm not sure what else to truncate here.
Note - I did think about posting this question on CodeGolf SE, but I felt it wouldn't be a good fit there, due to the limited scope.
I'd like to give you a hint, without giving you the answer:
You're close, but you can save characters by not using something you need to add in your code.
By adding the thing you won't use, you can remove ().
Spoiler (answer):
// Note: this only really works for this specific case.
// Never EVER use this in a real-life scenario.
var a = [1,2,3,'a','b','c',[]]
weirdReverse=a=>a.sort(x=>1)
// ^ That's 1 character shorter than ()
console.log(weirdReverse(a))
I'm writing a javascript program that needs random 10-digit numbers which can sometimes have the 10th digit as 0. I assigned a variable to one of these numbers and then logged it to make sure everything was alright...but it wasn't. Here is my code:
var candidate = 0135740250;
var candidate2 = 0272189318;
console.log(candidate); // Returns 24625320
console.log(candidate2); // Returns 272189318
I tried taking the 0 off the beginning of candidate, and that made it return correctly, but I don't understand why it doesn't work in the first place. I included candidate2 above because whatever I do to it, adding 0s in the middle, changing it in other ways, it stays correct, so I can't figure out why candidate is being screwed up. I vaguely understand the number storage system in Javascript and that its not perfect, but I need a predictable, repeatable way to return the correct number.
The question is: what is happening here and how can I reliably avoid it?
"The question is: what is happening here..."
The first is a valid octal, so it gets converted as such.
The second is not a valid octal because of the 8 and 9, so it gets the base 10 representation with the leading 0 removed since it adds no value.
"...and how can I reliably avoid it?"
Avoiding it will depend on how you're generating your numbers. If you were using .random() it wouldn't be an issue, so I'd assume they're coming from some sort of string representation.
If so, and if you're using parseInt() to get the actual number, then pass it 10 as the second argument to ensure base-10 representation.
JavaScript treats any number beginning with 0 as octal if it is a valid octal.
Another quack is, if you know the length of string to generate
"use strict"
var strlent = 10
console.log(candidate2.toString().length < strlent ? "0" +
candidate2.toString() : candidate2.toString())
>>>0272189318
I've seen examples of code that uses only operators and "" to perform complex string operations. Basically, the idea was that something like ((+"+")+"")[+""] gives you a letter N, etc. I forgot where I found it, and I'm having no luck finding proper google keywords. Does anyone have a link at hand?
Basically there are two main concepts used here:
making a Number out of string, i.e. Number(str), which shortcut is +str;
stringifying numeric values, i.e. String(n), which shortcut is n+"".
Hence, if we look at the expression thoroughly, we'll see:
+"+" === NaN
NaN + "" === "NaN"
+"" === 0
"NaN"[0] === "N"
There are a lot of things you can do in JavaScript in the same way. One funny example is provided in the following question: What are JavaScript's builtin strings?
What's the difference between
"2" * 1 + 5
and
parseInt("2") + 5
It's just a to write a more readable code, or there are compatibility issues with the first form.
parseInt is used to grab integers from a string. Consider the following code:
var myString = "3 blind mice";
var myInteger = parseInt(myString); //3
JavaScript will do automatic type conversion, so something like this:
"2" * 1 + 5 //7
The string "2" gets converted to a number.
As noted above in the comments, parseInt takes an additional argument for the base.
JavaScript has a lot of very weird rules about type conversion, and sometimes it's not exactly clear what JavaScript will do in every situation. Keep in mind that the + operator is also used for concatenation as well as addition.
If you're trying to explicitly convert something to a number, you can use the Number constructor provided by JavaScript. Considering the following:
var myString = "2";
var myNum = Number(myString); //2
console.log(typeof myNum); //number
Without the new keyword, it can be used to convert strings to numbers. While it does work, I am not sure parseInt should be used for conversion. Just use the Number constructor.
I don't think there are compatibility issues with using coercion in the first form, it is a language feature that should be widely supported.
However, since you have to add code to do the conversion either way (* 1 vs. parseInt), I would vote for parseInt from a style perspective because it makes your intention clearer. It is hard enough sometimes to keep types straight in javascript without using implicit conversions.
Someone not familiar with your code or with javascript might wonder what is going on with that first form as well.
Plus, as indicated in the comments, parseInt is faster so it's a win all around.