The following code is working properly, however I would assume there is a more efficient way to have the logic flow. Currently I am writing out the same function twice with a subtle change in the output string. Does anyone know of way to make this logic work with less code?
if (result <= 1) {
document.getElementById('output').innerText = Math.ceil(result) + " roll of wallpaper";
}
else {
document.getElementById('output').innerText = Math.ceil(result) + " rolls of wallpaper";
}
document.getElementById('output').innerText = [
Math.ceil(result),
' roll',
result > 1 ? 's' : '',
' of wallpaper'].join('')
You can build the difference beforehand and add it in manually:
var s = ( result <= 1 ? 's' : '' );
document.getElementById('output').innerText =
Math.ceil(result) + " roll" +s+ " of wallpaper";
Edit: Cutting-edge JS bonus, using template strings is extra fun (need babel):
var displayResult = Math.ceil(result);
var s = ( result <= 1 ? 's' : '' );
document.getElementByid('output').innerText =
`${displayResult} roll${s} of wallpaper`;
Can be:
var s = (result <= 1) ? 's' : '';
document.getElementById('output').innerText = Math.ceil(result) + ' roll'+s+' of wallpaper';
Related
I am trying to solve a problem from jshero.net. The problem is the following:
Write a function spaces that takes a natural number n and returns a string of n spaces. spaces(1) should return ' '.
I need to use a while loop to solve this challenge. The best solution I could come up with is:
function spaces(num) {
let mySpaces = '';
while(mySpaces === num) {
mySpaces+= num}
}
}
But it returns the following errors:
spaces(0) does not return '', but undefined.
Test-Error! Correct the error and re-run the tests!
Does anyone know how to solve this?
Make sure to return your output, and subtract from num each iteration:
function spaces(num) {
let mySpaces = '';
while (num-- > 0)
mySpaces += ' ';
return mySpaces;
}
console.log(
JSON.stringify(spaces(1)),
'\n',
JSON.stringify(spaces(5))
);
Ultimately, this seems to be the most elegant (and performant) approach:
const spaces = (n) => Array(n + 1).join(' ');
console.log(
JSON.stringify(spaces(1)),
'\n',
JSON.stringify(spaces(5))
);
1.1M ops/s for Array.join vs. 86k for the while loop.
EDIT
Totally blanked on String.repeat, thanks to Daniel for that. Pushing 2M ops/s:
const spaces = (n) => " ".repeat(n);
console.log(
JSON.stringify(spaces(1)),
'\n',
JSON.stringify(spaces(5))
);
I just succeeded to resolve it with the litle help of other peoples answers here.
This is the code that solved :
function spaces(num){
let s = '';
while(s.length < num){
s = ' '.repeat(num);
return s;
}
}
spaces=(n)=>{
let a='';
while(a.length<n){
a= a+ ' ';
}
return a;
}
This snippet worked for me; All tests passed!
function spaces(n){
let a = '';
while ( a.length<n ){
a = a + ' ';}
return a;
}
This is the correct Code you need to put s.length<=num
function spaces(num){
let s = '';
while(s.length <= num){
s = ' '.repeat(num);
return s;
}
}
I am new to Javascript,so forgive my silly mistakes in advance.
I have a requirement where I have to print current and total page number excluding even pages which are blank.
Example : For 5 page long document,it should display like:
1(3)
2(3)
3(3)
Any sort of info is welcome since I am in dire need of this code to work.
I have tried this but it doesn't work:
var current_page=0 ;
var total_pages=0;
if((current_page<total_pages)||(current_page=total_pages))
{
current_page++;
if(current_page % 2!==0)
{
total_pages++;
}
}
Also, this one too doesn't worked :(
var temp = (this.pageNum) + "(" + (this.numPages) + ")" ;
You have a logical error here:
current_page = total_pages // Note single = symbol between.
You are assigning instead of comparing. Please use == to compare:
current_page == total_pages
Or === for strict comparison as the type of both the variables is same.
Does that help?
function (totalPages, currentPage)
{
if (currentPage%2==1) return "";
var tp = parseInt(totalPages/2+1);
var cp = parseInt(currentPage/2+1);
return "" + cp + "(" + tp + ")";
}
I am using this code to convert number to string:
ProductsData[0]['price'].toLocaleString();
I am getting the expexted output:
8,499
But same code is not working for Safari.
Please give me suggestion on same.........
Although toLocaleString (without parameters) works in all mainstream browsers, it's behaviour is inconsistent from one browser to another, unfortunately.
If consistent date/time formatting is important, I'm afraid you will need to resort to building your own version of toLocaleString or working with a library. Here are a couple that may be worth investigating:
https://code.google.com/p/datejs/
https://github.com/jquery/globalize
I've encountered this issue today while working on a (almost complete) site which uses this function a lot and stumbled upon your question (Safari not showing any currency and/or thousands/decimal separators). I wrote a small override function to pop in and fix the toLocaleString to my needs (in Europe and euro's (€)).
Hope this helps anybody else encountering this same issue.
(function() {
Number.prototype._toLocaleString = Number.prototype.toLocaleString;
Number.prototype.toLocaleString = function(locales,options) {
if(options.style == "currency") { // only format currencies.
var prepend = "";
if(options.currency == "EUR") {
prepend = "\u20AC "; // unicode for euro.
}
var val = this;
val = val;
// check if the toLocaleString really does nothing (ie Safari)
var tempValue = val._toLocaleString(locales,options);
if(tempValue == val.toString()) { // "broken"
return prepend+val.formatMoney(2); // <-- our own formatting function.
} else {
return tempValue;
}
} else {
return this._toLocaleString(locales,options);
}
};
Number.prototype.formatMoney = function(c, d, t){
var n = this,
c = isNaN(c = Math.abs(c)) ? 2 : c,
d = d == undefined ? "," : d,
t = t == undefined ? "." : t,
s = n < 0 ? "-" : "",
i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))),
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
// demonstration code
var amount = 1250.75;
var formattedAmount = amount.toLocaleString('nl-NL', {style:'currency',currency: 'EUR'});
console.log(formattedAmount);
})();
credits (and info about the "formatMoney") to https://stackoverflow.com/a/149099/2225737
Everytime the user presses a button I want every 3 characters to add a dot, example:
123
123.456
12.345.678
I want this to happend everytime the key is pressed, this is what I have but no luck...
function format_num(input) {
str = input.value;
str.replace(/(.{3})/,'$1.')
input.value = str;
}
<input type="text" name="num" id="num" onKeyPress="format_num(this)">
First off, you are missing a semicolon after your regex. Second, you have to add the g modifier to find all the matches rather than stopping at the first one. Also, assign the result of the .replace() to a variable, even str itself.
str = str.replace(/(.{3})/g,"$1.");
This is because in Javascript strings are immutable: this means that all the String method do not actually change the contents string, but return a new modified string.
One last caveat: you will notice that, as you add the dots, this regex will not work anymore, as you will be adding dots in between dots.
You have to avoid counting the dots in your string. You might do so by reworking your variable before executing the Regex; something on this line:
str = str.split('.').join('');
Working example
You have to scan from right to left. A more readable (compared to Utkanos) solution is
function format_num(input) {
var inStr = input.value.replace(/\./, '');
var outStr = '';
for (var count=0, i=inStr.length-1; i>=0; i--, count++ ) {
if ( count && count % 3 == 0 ) outStr = '.' + outStr;
outStr = inStr.charAt(i) + outStr;
}
input.value = outStr;
}
This is the most horrible, unreadable answer I've ever posted but it does work, for any number.
var num = 12345678;
var formatted = num.toString().replace(/./g, function(num) { return num+'|'; }).split('|').reverse().join('').replace(/\d{3}/g, function(nums) { return nums+'.'; }).replace(/./g, function(num) { return num+'|'; }).split('|').reverse().join('').replace(/^\./, '');
Generates 12.345.678
I found this script that works perfectly!! I had some issues with the answers so I looked and came up with this piece of work...Thanks anyways!!
function formatNumber( originalValue ){
originalValue = ( originalValue != null ? originalValue.toString() : "0" );
var nStr = originalValue.replace( /\./g, "" );
var jj=0;
var leftNumbers = 0;
var x = nStr.split(',');
var x1 = x[ 0 ];
var x2 = x.length > 1 ? ',' + x[ 1 ] : '';
var rgx = /(\d+)(\d{3})/;
while( rgx.test( x1 ) ){
x1 = x1.replace( rgx, '$1' + '.' + '$2');
}
nStr = x1 + x2;
for( jj=0; leftNumbers>0; jj++ ){
if( /[0-9]/.test( nStr.toString().substring( jj, ( jj + 1 ) ) ) )
leftNumbers--;
}
if( originalValue == nStr )
return originalValue;
return nStr;
}
I have this below code in a javascript file. When i run it i get error message :
"Can't find variable: addZero".
function addZero(n) {
return ( n < 0 || n > 9 ? "" : "0" ) + n;
}
Date.prototype.toISODate =
new Function("with (this)\n return " +
"getFullYear()+'-'+ addZero(getMonth()+1)+ '-'" +
"+ addZero(getDate()) + 'T' + addZero(getHours())+':' " +
"+ addZero(getMinutes()) +':'+ addZero(getSeconds()) +'.000Z'");
function addZero(n) {
return ( n < 0 || n > 9 ? "" : "0" ) + n;
}
Date.prototype.toISODate = function() {
// do what you want here
// with real code! not strings...
}
Theres a good function on the Mozilla Javascript reference page for Date that produces ISO Date strings
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference:Global_Objects:Date
/* use a function for the exact format desired... */
function ISODateString(d){
function pad(n){return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'
}
var d = new Date();
console.log(ISODateString(d)); // prints something like 2009-09-28T19:03:12Z
Looks like your quotes are off. Try
return "with (this)\n return " +
getFullYear() + '-' + addZero(getMonth()+1) + '-' +
addZero(getDate()) + 'T' + addZero(getHours())+':' +
addZero(getMinutes()) +':'+ addZero(getSeconds()) +'.000Z';
Try rewriting your Date extension like this, to keep things clear and to avoid using the with keyword:
Date.prototype.toISODate =
function(){
function padLeft(nr,base,padStr){
base = base || 10;
padStr = padStr || '0';
var len = (String(base).length - String(nr).length)+1;
return len > 0? new Array(len).join(padStr)+nr : nr;
}
return [this.getFullYear(),
'-',
padLeft(this.getMonth()+1),
'-',
padLeft(this.getDate()),
'T',
padLeft(this.getHours()),
':',
padLeft(this.getMinutes()),
':',
padLeft(this.getSeconds()),
'.',
padLeft(this.getMilliseconds(),100),
'Z'].join('');
};
The padLeftZero function now exists within the scope of the Date.toISODate method. The use of an array literal to build the return string is for clarity. It isn't necessary and even can be called bad practice to use new Function ... to assign a function to Date.prototype.toISODate. BTW, milliseconds are added to the result (padded with zero's).