Devide numbers on countup function - javascript

I'm starting to learn javascript and I basically needed a countup that adds an x value to a number(which is 0) every 1 second. I adapted a few codes I found on the web and came up with this:
var d=0;
var delay=1000;
var y=750;
function countup() {
document.getElementById('burgers').firstChild.nodeValue=y+d;
d+=y;
setTimeout(function(){countup()},delay);
}
if(window.addEventListener){
window.addEventListener('load',countup,false);
}
else {
if(window.attachEvent){
window.attachEvent('onload',countup);
}
}
There's probably residual code there but it works as intended.
Now my next step was to divide the resultant string every 3 digits using a "," - basically 1050503 would become 1,050,503.
This is what I found and adapted from my research:
"number".match(/.{1,3}(?=(.{3})+(?!.))|.{1,3}$/g).join(",");
I just can't find a way to incorporate this code into the other. What should I use to replace the "number" part of this code?
The answer might be obvious but I've tried everything I knew without sucess.
Thanks in advance!

To use your match statement, you need to convert your number to a String.
Let's say you have 1234567.
var a = 1234567;
a = a + ""; //converts to string
alert(a.match(/.{1,3}(?=(.{3})+(?!.))|.{1,3}$/g).join(","));
If you wish, you can wrap this into a function:
function baz(a) {
a = a + "";
return a.match(/.{1,3}(?=(.{3})+(?!.))|.{1,3}$/g).join(",");
}
Usage is baz(1234); and will return a string for y our.
While I do commend you for using a pattern matching algorithm, this would probably be easier to, practically speaking, implement using a basic string parsing function, as it doesn't look anywhere as intimidating from just looking at the match statement.
function foo(bar) {
charbar = (""+bar).split(""); //convert to a String
output = "";
for(x = 0; x < charbar.length; x++) { //work backwards from end of string
i = charbar.length - 1 - x; //our index
output = charbar[i] + output; //pre-pend the character to the output
if(x%3 == 2 && i > 0) { //every 3rd, we stick in a comma, except if it is not the leftmost digit
output = ',' + output;
}
}
return output;
}
Usage is basically foo(1234); which yields 1,234.

Related

Breakpoint Debugging forEach - JS

I'm trying to return the length of the last word in a string, I am struggling with debugging at the moment. The problem is with the forEach loop I hit a breakpoint that wont update the empty array.
function lengthOfLastWord(s) {
let spaces = [];
let space = ' ';
let spaceInd = s.indexOf(space);
while (spaceInd != -1) {
spaces.push(spaceInd);
spaceInd = s.indexOf(space, spaceInd + 1);
}
let nonSpaces = [];
let wordArray = [];
for(let i = 0; i<spaces.length; i++) {
nonSpaces.push((spaces[i + 1] - spaces[i]) - 1);
}
nonSpaces.forEach(function(number) {
if (number >= 1) {
wordArray.push(number);
}
})
let words = wordArray[wordArray.length - 1];
if ((wordArray.length === 0)) {
console.log(0);
} else {
console.log(words);
}
};
lengthOfLastWord("this is my test string");
If I ignore the breakpoint I get the correct outcome, but I can't seem to figure out why the empty wordArray wont update.
(I'm sure there is an easier way to get the result using filters and mapping but i'm wondering if there is a simple fix to my current buggy code)
Right now, your code seems to return the length of the second to last word, rather than the last. The problem does not lie in the forEach, rather it is in the way you're doing it. When you take the index of spaces in the string and calculate distance between each of them, this excludes the first and the last words, as there isn't a space at the very beginning and at the very end. As a result, the second to last word's length is logged rather than the very last.
The simple fix would be to add this line right after your while loop:
spaces.push(s.length);
This will make sure that the final word length will also be calculated in the following for loop.
As you are aware, there is a much simpler way to do this.
Here is one using split:
function lengthOfLastWord(string) {
let split = string.trim().split(" ");
return split[split.length - 1].length
}

Write a JavaScript function to find longest substring in a given a string without repeating characters

"Write a JavaScript function to find longest substring in a given a string without repeating characters."
Here's what I tried, but it doesn't print anything
function sort(names) {
let string = "";
let namestring = names.split("");
for(let i = 0; i < namestring.length; i++) {
for(let j = 0; j < string.length; j++) {
if(string[j] != namestring[i]) {
string = string + namestring[i];
}
}
}
return string;
}
console.log(sort("google.com"));
What's wrong?
function sort(names)
{
string="";
ss="";
namestring=names.split("");
for(j=0;j<namestring.length;j++) {
for(i=j;i<namestring.length;i++) {
if(string.includes(namestring[i]))
break;
else
string+=namestring[i];
}
if(ss.length<string.length)
ss=string;
string="";
}
return ss;
}
console.log(sort("google.com"));
It's o(n^2) complexity but try this(may be o(n^3) if contains function take o(n) complexity)
function sort(names)
{
string="";
ss="";
namestring=names.split("");
for(j=0;j<namestring.length;j++) {
for(i=j;i<namestring.length;i++) {
if(string.includes(namestring[i])) // if contains not work then
break; //use includes like in snippet
else
string+=namestring[i];
}
if(ss.length<string.length)
ss=string;
string="";
}
return ss;
}
console.log(sort("google.com"));
What are you expecting the answer to be here? Should it be "ogle.com" or "gle.com"? If the first, the below should get you there, if the latter, update the tested = name.charAt(i) in the else to tested = "".
So a few things to note, though you're more than welcome to do as you wish:
1) the function name. This isn't doing a "sort" as far as I can tell, so if this is for your use (or any reuse. Basically, anything more than a one off homework assignment), you may want to rename it to something you'd actually remember (even the example I give is probably not completely best as "pick longest substring" is non-descriptive criteria).
2) variable naming. string and namestring may mean something to you here, but considering we're trying to find the longest substring (with the no double characters) in a string, I felt it was better to have the one we're checking against (tested) and the one we're storing to return later (longest). It helps make sense as you're reading through the code as you know when you are done with a checked string (tested), you want to compare if it is greater than the current longest substring (longest) and if it is bigger, you want it to be the new longest. This will save you a ton of headache to name variables to things that'll help when designing your function as you can get it as close to requirements written down as possible without trying to do some form of substitution or worse, forgetting which variable holds what.
I don't know what you want the result to be in the event that tested length is the same as longest length. Currently I have it set to retain, if you want the most recent, update the check to >=.
Beyond that, I just iterate over the string, setting to the currently tested string. Once double characters are met, I then see if what I just generated (tested) is larger than the current longest and if it is, it is now the longest. Once I finish looping across the string, I have to do the current vs longest check/set again as otherwise, it'd make the final tested meaningless (it went outside the loop before another double character situation was hit).
function pickLongestSubstring(name) {
let tested = "";
let longest = "";
for (let i = 0; i < name.length; i++) {
if (tested.length == 0 || tested.charAt(tested.length - 1) != name.charAt(i)) {
tested += name.charAt(i);
}
else {
if (tested.length > longest.length) {
longest = tested;
tested = "";
}
}
}
if (tested.length > longest.length) {
longest = tested;
}
return longest;
}
console.log(pickLongestSubstring("google.com"))
console.log(pickLongestSubstring("example.com"))
This is a recursive loop that should get the longest string. Uses sort to determine longest string. Works, even if multiple instances of same repeat char.
function longestWithoutRepeat(testString, returnString){
var returnString = returnString || "";
for(var i = 0; i < testString.length; i++) {
if(i > 0){
if(testString[i] == testString[i-1]) {
var testStringArray = testString.split(testString[i] + testString[i-1]);
testStringArray.sort(function(firstString, nextString){ return nextString.length - firstString.length})
returnString = testStringArray[0];
longestWithoutRepeat(testStringArray[0], returnString);
}
} else {
returnString = testString
}
}
return returnString;
}
console.log(longestWithoutRepeat("oolong"));
console.log(longestWithoutRepeat("google.com"));
console.log(longestWithoutRepeat("diddlyougotoofarout"));

JavaScript: Is there a benefit in using the charCode when comparing characters?

First of all: I'm a bit into JavaScript but not much.
Today I saw these code:
if (stringToSearch[i].charCodeAt(0) === codeToSearch) {
The charCodeAt() method of String is used for to compare the current char with the searched char.
The full code of the function here:
function getOccurences (stringToSearch, charToSearch) {
var ret = 0;
var codeToSearch = 0;
var i;
stringToSearch = stringToSearch.toUpperCase();
codeToSearch = charToSearch.toUpperCase().charCodeAt(0);
for (i = 0; i < stringToSearch.length; i++) {
if (stringToSearch[i].charCodeAt(0) === codeToSearch) {
ret++;
}
}
return ret;
}
I would have compared the char directly. Without using charCodeAt().
Just ...
stringToSearch[i] === charToSeach
As far as I know the computer compares just numbers anyway. Translates the characters to their UTF-codes. Subtracts these numbers against each other and then checks if the result has become zero.
So therefore my question:
Does the usage of charCodeAt() makes any sense?
Are there a benefit to favor the direct charCode-comparison over the character-comparison.
My intuition is to say there's a performance hit when you go through type-conversion and function-calling hoops like that.
That said, you'll likely eke out more performance out of the code by delegating to the native string methods, with something like:
function countCaseInsensitiveOccurrences(haystack, char) {
haystack = haystack.toUpperCase();
char = char.toUpperCase()[0];
var count = 0, pos = -1;
while ((pos = haystack.indexOf(char, pos + 1)) !== -1) {
count++;
}
return count;
}
charCode benefits when we have to increment/decrement the characters.
eg. if we have charCode('a') in variable x, then we can increment it using x++.
But if we had saved 'a' then we cannot perform arithmetic operations.
So charCodeAt(number) is used when you need to increment/decrement the characters.

Recursion and Loops - Maximum Call Stack Exceeded

I'm trying to build a function that adds up all the numbers within a string... for example, 'dlsjf3diw62' would end up being 65.
I tried to be clever and put together a recursive function:
function NumberAddition(str) {
var numbers='1234567890';
var check=[];
str=str.split[''];
function recursive(str,check) {
if (str.length==0)
return check;
else if (numbers.indexOf(str[0])>=0)
{
for (i=0;i<str.length;i++){
if (numbers.indexOf(str[i])<0)
check.push(str.slice(0,i));
str=str.slice(i);
return recursive(str,check);
}
}
else
str.shift();
return recursive(str,check);
}
You'll see that I'm trying to get my numbers returned as an array in the array named check. Unfortunately, I have a maximum call stack size exceeded, and I'm not sure why! The recursion does have a base case!! It ends once str no longer has any contents. Why wouldn't this work? Is there something I'm missing?
-Will
You can achieve the same thing with a far easier solution, using regular expressions, as follows:
var str = 'dlsjf3diw62';
var check = str.match(/\d+/g); // this pattern matches all instances of 1 or more digits
Then, to sum the numbers, you can do this:
var checkSum = 0;
for (var i = 0; i < check.length; i++) {
checkSum += parseInt(check[i]);
}
Or, slightly more compact:
var checkSum = check.reduce(function(sum, num){ return sum + parseInt(num) }, 0);
The reason your recursion doesn't work is the case where you do enter the for loop, because you've found a digit, but the digits continue to the end of the string. If that happens, the return inside the for loop never happens, and the loop ends. After that, the .shift() does not happen, because it's in that else branch, so you return re-process the same string.
You shouldn't solve this particular problem that way, but the code makes a good example of the anti-pattern of having return statements inside if bodies followed by else. Your code would be clearer (and would work) if it looked like this:
function recursive(str, check) {
if (str.length == 0)
return check;
if (numbers.indexOf(str[0]) >= 0) {
// Find the end of the string of digits, or
// the end of the whole thing
for (var i = 0; i < str.length && numbers.indexOf(str[i]) >= 0; i++);
check.push(str.slice(0, i));
str = str.slice(i);
return recursive(str, check);
}
// A non-digit character
str.shift();
return recursive(str, check);
}
In that version, there are no else clauses, because the two if clauses always involve a return. The for loop is changed to simply find the right value of "i" for the subsequent slicing.
edit — one thing this doesn't fix is the fact that you're pushing arrays into your "check" list. That is, the substring "62" would be pushed as the array ["6", "2"]. That's not a huge problem; it's solved with the addition of a .join() in the right place.

Trouble adding leading zeroes to submitted form data in javascript

I looked through here last night for some examples on adding leading zeroes with JavaScript and I couldn't get any of them to work for my purposes. I want to do this with the data once you hit the submit button. It is running a set of checkers when it does this and this is what I have included, but I grab the POST data in a test php page and the field I am trying to fix shows "undefined"
I need the number of digits to always be 7, regardless of whether they entered a four or five digit number. Leading zeroes need to be added. Not sure if I am kind of close or way off target with this:
function pad(number, length){
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
}
offidlength = custform.optionaldata10.value.length;
if (offidlength <7) {
custform.optionaldata10.value = pad(custform.optionaldata10.value, 7);
}
You forgot the return statement.
return str;
Should be at the end of the function.
edit function should look like:
function pad(number, length){
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
You can make your expression simpler, if you always want 7 digits-
var offid= custform.optionaldata10.value, L= 7-offid.length;
if(L>0) custform.optionaldata10.value= '0000000'.substring(0, L)+offid;

Categories