Convert values - issue - javascript

I'm using this code for simple conversion of values between different bases (baseConversion). But there are occurring some issues that I'd love to fix!
"1234" from base 10 to base 3 will get "1200201" and decoded again to base 10 will get "1234" again. So far so good.
Encoding "0001" to base 3 will get "1" and decoding again will get "1" instead of "0001" again. How to fix this?
function convertBase(value, from_base, to_base) {
var range = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/'.split('');
var from_range = range.slice(0, from_base);
var to_range = range.slice(0, to_base);
var dec_value = value.split('').reverse().reduce(function(carry, digit, index) {
if (from_range.indexOf(digit) === -1) throw new Error('Invalid digit `' + digit + '` for base ' + from_base + '.');
return carry += from_range.indexOf(digit) * (Math.pow(from_base, index));
}, 0);
var new_value = '';
while (dec_value > 0) {
new_value = to_range[dec_value % to_base] + new_value;
dec_value = (dec_value - (dec_value % to_base)) / to_base;
}
return new_value || '0';
}
let raw = "1234"
document.body.innerHTML += "raw: " + raw + "<br>"
let encoded = convertBase(raw, 10, 3)
document.body.innerHTML += "encoded: " + encoded + "<br>"
let decoded = convertBase(encoded, 3, 10)
document.body.innerHTML += "decoded: " + decoded + "<br><br>"
raw = "0001"
document.body.innerHTML += "raw: " + raw + "<br>"
encoded = convertBase(raw, 10, 3)
document.body.innerHTML += "encoded: " + encoded + "<br>"
decoded = convertBase(encoded, 3, 10)
document.body.innerHTML += "decoded: " + decoded + "<br><br>"
* {
font-family: Arial;
}
i {
font-weight: bold;
color: gray;
}
<b>Note</b>: "1234" from base 10 to base 3 will get <i>"1200201"</i> and decoded again to base 10 will get <i>"1234"</i>
<br><br> Encoding "0001" to base 3 will get <i>"1"</i> and decoding again will get <i>"1"</i> instead of <i>"0001"</i> again.<br><br>
----------------
<br><br><br><br>
Any help would be very appreciated. Thanks a million in advance!

Related

Replacing null with 0 when summing values

I have a function that sums my values and everything works fine, but only when all inputs have a value entered. However, I would like default to have 0 assigned to it.so that the function works when at least one value is given . How to do it ?.
var DeductiblepercentageM = thisPointer.entity.getValue('number.DeductiblepercentageM[' + i + ']');
var InsuranceLimitM = thisPointer.entity.getValue('number.InsuranceLimitM[' + i + ']');
var insuranceRaitingM = thisPointer.entity.getValue('number.insuranceRaitingM[' + i + ']');
var InsurerNumberM = thisPointer.entity.getValue('number.InsurerNumberM[' + i + ']');
DeductiblepercentageM = DeductiblepercentageM.replace(",", ".");
DeductiblepercentageM = parseFloat(DeductiblepercentageM)
InsuranceLimitM = InsuranceLimitM.replace(",", ".");
InsuranceLimitM = parseFloat(InsuranceLimitM)
insuranceRaitingM = insuranceRaitingM.replace(",", ".");
insuranceRaitingM = parseFloat(insuranceRaitingM)
InsurerNumberM = InsurerNumberM.replace(",", ".");
InsurerNumberM = parseFloat(InsurerNumberM)
//log the outcome of decimal separator change
var positionSum = +(DeductiblepercentageM + InsuranceLimitM +insuranceRaitingM + InsurerNumberM);
jQ('[id="DeductibleM[' + i + ']"]').val(positionSum);
thisPointer.entity.setValue('DeductibleM[' + i + ']', positionSum);
thisPointer.entity.mergeLocal(true);
if (totalSum != "NaN") {
totalSum = +(totalSum + positionSum).toFixed();
}
}
else {
totalSum = "-";
}
According to #Terry
var InsuranceLimitM = thisPointer.entity.getValue('number.InsuranceLimitM[' + i + ']') || 0;
adding || 0 to the end of the code helps and makes the code count right away

Done / How to make a space printer in javascript

var arg = 5
var string = ' '
for (let i = 0; i < arg; i++) {
console.log('"' + string + '"')
}
I expected the output is:
" " \\ There are 5 spaces between the ""
But the output is:
" "
" "
" "
" "
" "
I am a newbie in javascript. Hope you will help me
you can use method string.padEnd that fill string with blank space until parameter pass to the method
var arg = 5;
var string = ' ';
string = string.padEnd(arg)
console.log('"' + string + '"');
reference : https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd
I don't think there is a way to console.log on the same line. You can do something like this
var arg = 5
var string = ' '
var final_string = ''
for (let i = 0; i < arg; i++)
final_string = final_string + string
}
console.log('"' + final_string + '"')
I think you can use or \xa0 for printing spaces
var arg = 5
var string = '\xa0\xa0\xa0\xa0\xa0';
for (let i = 0; i < arg; i++) {
console.log('"' + string + '"')
}
There are many ways to do this. One would be to do it via a loop. That way you can stay flexible. For loop has already been mentioned. here with a foreach loop.
let string = '';
[...Array(5).keys()].forEach(e => string += ' ');
console.log('"' + string + '"');

Javascript for Phone Number Formatting in Dynamics 365

Javascript we had for Unified interface of Dynamics 365 to format phone numbers was working perfectly until the latest update, now it only works in custom interface and has stopped working in UI, anybody has any idea how this can be fixed?
var XXX = window.XXX || {};
(function() {
// Code to run in the form OnLoad event
this.formOnLoad = function(executionContext) {
var formContext = executionContext.getFormContext();
// display the form level notification as an INFO
formContext.ui.setFormNotification(message, "INFO", myUniqueId);
// Wait for 5 seconds before clearing the notification
window.setTimeout(function() {
formContext.ui.clearFormNotification(myUniqueId);
}, 5000);
}
// Code to run in the attribute OnChange event
this.mobilePhoneFormatting = function(executionContext) {
var formContext = executionContext.getFormContext();
var mobilePhone = formContext.getAttribute("mobilephone").getValue();
var formatPhone = "";
try {
if (mobilePhone != null) {
var phoneNumbers = mobilePhone.replace(/\D/g, '');
if (phoneNumbers.length == 10) { //10 digit case. Output adds +1 and proper format
formatPhone = ("+1 (" + phoneNumbers.substring(0, 3) + ") " + phoneNumbers.substring(3, 6) + "-" + phoneNumbers.substring(6, 10));
} else if (phoneNumbers.length == 11) { //11 digit case. Output proper format
formatPhone = ("+" + phoneNumbers.substring(0, 1) + " (" + phoneNumbers.substring(1, 4) + ") " + phoneNumbers.substring(4, 7) + "-" + phoneNumbers.substring(7, 11));
} else if (phoneNumbers.length == 14) { //14 digit case. Without Country code and with extension
formatPhone = ("+1 (" + phoneNumbers.substring(0, 3) + ") " + phoneNumbers.substring(3, 6) + "-" + phoneNumbers.substring(6, 10) + " x" + phoneNumbers.substring(10, 14));
} else if (phoneNumbers.length == 15) { //15 digit case. With Country code and extension
formatPhone = ("+" + phoneNumbers.substring(0, 1) + " (" + phoneNumbers.substring(1, 4) + ") " + phoneNumbers.substring(4, 7) + "-" + phoneNumbers.substring(7, 11) + " x" + phoneNumbers.substring(11, 15));
} else if (phoneNumbers.length == 4) { //4 digit case. Extension Only
formatPhone = ("x" + phoneNumbers.substring(0, 4));
} else {
formatPhone = mobilePhone;
}
formContext.getAttribute("mobilephone").setValue(formatPhone);
formContext.data.entity.save();
}
} catch (err) {
txt = "There was an error formatting the Phone Number.\n\n";
txt += "Error description: " + err.message + "\n\n";
txt += "Click OK to continue.\n\n";
alert(txt);
}
}

Javascript document.getElementByID with condition

I'm reading from a text file some numbers. Sometimes there's a number 0 and the line below outputs 0, but I don't want to output if the number is "0". Is there a way to change the line below to NOT output/print when the number is "0"? Thanks
document.getElementById('inputText').innerHTML= "(" + parseFloat(output1*2).toFixed(3) + "," + parseFloat(output2*2).toFixed(3) + ")";
You can make a function that checks each value and generates a result based on that, like this:
var getResult = function (num1, num2) {
var result1 = num1 ? (parseFloat(num1) * 2).toFixed(3) : "";
result1 = isNaN(result1) ? "" : result1;
var result2 = num2 ? (parseFloat(num2) * 2).toFixed(3) : "";
result2 = isNaN(result2) ? "" : result2;
var comma = result1 && result2 ? ", " : "";
return `(${result1}${comma}${result2})`;
};
document.getElementById('result').innerHTML += `5, 0 = ${getResult("5")}<br/>`;
document.getElementById('result').innerHTML += `0, 4 = ${getResult("0", "4")}<br/>`;
document.getElementById('result').innerHTML += `3, 2 = ${getResult("3", "2")}<br/>`;
document.getElementById('result').innerHTML += `3, 2 = ${getResult("three", "15.5")}<br/>`;
<div id="result"></div>
Edit: Removed possible NaN-results.
You can replace 0 with nothing using the or operator:
parseFloat(output1*2) || ""
or using a ternary:
output1? parseFloat(output1*2).toFixed(3) : ""
document.getElementById('inputText').innerHTML= "(" + ((parseFloat(output1*2).toFixed(3) + ",") ? parseFloat(1*2).toFixed(3):"") + ((parseFloat(output2*2).toFixed(3)) ? parseFloat(1*2).toFixed(3):"") + ")";
Use if statement to check your number:
Html:
<p id="inputText">
0
</p>
Js:
var output = document.getElementById('inputText').innerHTML;
output = parseFloat(output);
if(output != '0'){
inputText.innerHTML= "(" + (output *2)
.toFixed(3) + "," + (output*2).toFixed(3) + ")";
}
https://jsfiddle.net/b5st3h2m/2/

Interesting behavior in my US Number formatting code

I'm trying to make 10 digits look like a US telephone number (i.e.(###) ###-####). My code does accomplish this first goal, but it also does something I can't quite figure out. When typing in the digits, the characters "()" show up before typing any other digits. I want the open parenthesis to appear first and the closing parathesis to appear after entering the third digit. Please don't give me a new solution; try to pin point the issue I'm describing.
<script type="text/javascript">
$('.drumbi-caller-number').live('keydown', function (event) {
if (event.keyCode == 8 || event.keyCode == 37 || event.keyCode == 39) {
} else {
inputval = $(this).val();
var string = inputval.replace(/[^0-9]/g, "");
var first3 = string.substring(0,3);
var next3 = string.substring(3,6);
var next4 = string.substring(6,9);
var string = ("(" + first3 + ")" + next3 + "-" + next4);
$(this).val(string);
}
});
</script>
Here's a jsFiddle that displays this behavior: http://jsfiddle.net/bigthyme/j6kHn/3/
replace keydown with keyup, on keydown the value of the input element isn't updated
also set your string conditionally, only if long enough:
var string = string.length > 2 ? ("(" + first3 + ")" + next3 + "-" + next4) : first3;
here is the code: http://jsfiddle.net/j6kHn/10
btw: you should also replace .live(...) with .on(...) as .live() is deprecated..
You need to check the length of first3 before appending the paren:
var string = ("(" + first3 + ((first3.length>=3)?")":"") + next3 + "-" + next4);
And although not in your question, you can do the same for the hyphen:
var string = ("(" + first3 +
// only append the ) if the you have 3+ chars
((first3.length>=3)?")":"") +
next3 +
// only append the - if the you have 6+ chars
(((first3+next3).length>=6)?"-":"") +
next4);
You should also use .on() instead of live();
See it all working in this jsFiddle
Go with
$('.foo').on('keyup', function (event) {
$(this).val($(this).val().replace(/\D/g, "").replace(/(\d{0,3})(\d{0,3})(\d{0,4}).*/, "($1) $2-$3"));
});
Test this code here.
Try using this code, it should fix all of your issues:
Demo: http://jsfiddle.net/bN6Rh/3/
jQuery:
$('.foo').on('keyup', function(event) {
if (event.keyCode == (8 || 37 || 39)) { }
else {
inputval = $(this).val();
var string = inputval.replace(/[^0-9]/g, "");
var first3 = string.substring(0, 3);
var next3 = " " + string.substring(3, 6);
var next4 = string.substring(6, 10);
if (string.length < 3) { // Less than 3
var string = "(" + first3;
}
else if (string.length > 2 && string.length < 7) { // More than 2 and less than 7
var string = "(" + first3 + ")" + next3;
}
else { // Anything else
var string = "(" + first3 + ")" + next3 + "-" + next4;
}
$(this).val(string);
}
});​
The problem was that you weren't checking the number of characters so as soon as anything was entered it put in ()-, the above code also adds the space you mentioned wanting.
The code could of course be more compressed:
$('.foo').on('keyup', function(e) {
if (e.keyCode == (8 || 37 || 39));
else {
var str = this.value.replace(/[^0-9]/g, "");
var f3 = str.substring(0, 3),
n3 = " " + str.substring(3, 6),
n4 = str.substring(6, 10);
if (str.length<3) str = "(" + f3;
else if (str.length>2&&str.length<7) str="("+f3+")"+n3;
else str="("+f3+")"+n3+"-"+n4;
this.value = str;
}
});​

Categories