hopefully this is a silly mistake but I am trying to write text within a rect in p5.js. My method was to convert the text to a character array and count the number of characters I am printing before increasing a y-offset to step down a line. Here is the example code:
let splitQuote = tweetsTable.getRow(row).get("Quote").split('');
let size = splitQuote.length;
let rtnQuoteLines;
let yOff =0;
for (i=0;i<size;i++) {
rtnQuoteLines += splitQuote.shift();
if (i % 44 == 0 && i > 0) {
let rtn = rtnQuoteLines.toString();
text(rtn, 1100,yOff);
console.log("rtn: "+rtn);
yOff += 250;
rtnQuoteLines = "";
} else if (splitQuote.length < 44) {
let rtn = splitQuote.toString();
console.log("rtn2: "+rtn);
text(rtn, 1100,yOff);
break;
}
}
The console output makes me think I'm making some mistake too because the end of the quote remains an array and the start of the quote has 'undefined' before the first character.
Can anyone spot my mistake or suggest a neater way of doing this?
Thanks in advance for your help
First off, to stop the undefined at the begin, set let rtnQuoteLines = ""; When it is initally printed it will have a value to print.
You are getting all of the commas seen in the last part of your console log because when convert an array to a string it will automatically seperate eact element with commas. To make avoid this use let rtn = splitQuote.join(""); instead.
Hope this helps! :D
Related
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
}
I'm totally not a Math whiz kid here, but have put together a function with the great help of StackOverflow (and a lot of trial and error) that generates a random serial number from a Formula, group of Letters/Numbers, and array (so as to not duplicate values).
So, my current formula is as follows:
$.extend({
generateSerial: function(formula, chrs, checks) {
var formula = formula && formula != "" ? formula : 'XXX-XXX-XXX-XXX-XXX', // Default Formula to use, should change to what's most commonly used!
chrs = chrs && chrs != "" ? chrs : "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", // Default characters to randomize, if not defined!
len = (formula.match(/X/g) || []).length,
indices = [],
rand;
// Get all "-" char indexes
for(var i=0; i < formula.length; i++) {
if (formula[i] === "-") indices.push(i);
}
do {
rand = Array(len).join().split(',').map(function() {
return chrs.charAt(Math.floor(Math.random() * chrs.length));
}).join('');
// Rebuild string!
if (indices && indices.length > 0)
{
for(var x=0; x < indices.length; x++)
rand = rand.insert(indices[x], '-');
}
} while (checks && $.inArray(rand, checks) !== -1);
return rand;
}
});
Ok, so, what I need to be able to do is to find total possible values and make sure that it is possible to generate a unique serial number before actually doing so.
For example:
var num = $.generateSerial('XX', 'AB', new Array('AB', 'BA', 'AA', 'BB'));
This will cause the code to do an infinite loop, since there are no more possibilties here, other than the ones being excluded from the extension. So this will cause browser to crash. What I need to be able to do here is to be able to get the number of possible unique values here and if it is greater than 0, continue, otherwise, don't continue, maybe an alert for an error would be fine.
Also, keep in mind, could also do this in a loop so as to not repeat serials already generated:
var currSerials = [];
for (var x = 0; x < 5; x++)
{
var output = $.generateSerial('XXX-XXX-XXX', '0123456789', currSerials);
currSerials.push(output);
}
But the important thing here, is how to get total possible unique values from within the generateSerial function itself? We have the length, characters, and exclusions array also in here (checks). This would seem more like a math question, and I'm not expert in Math. Could use some help here.
Thanks guys :)
Here is a jsFiddle of it working nicely because there are more possible choices than 16: http://jsfiddle.net/qpw66bwb/1/
And here is a jsFiddle of the problem I am facing: Just click the "Generate Serials" button to see the problem (it continuously loops, never finishes), it wants to create 16 serials, but 16 possible choices are not even possible with 2 characters and only using A and B characters: http://jsfiddle.net/qpw66bwb/2/
I need to catch the loop here and exit out of it, if it is not able to generate a random number somehow. But how?
The number of possible serials is len * chrs.length, assuming all the characters in chrs are different. The serial contains len characters to fill in randomly, and chrs.length is the number of possible characters in each position of that.
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.
I am learning JavaScript through Codecademy, but I have an issue. The code below is supposed to search through the text variable for my name in the myName variable and then push all of the individual letters to the hits array. The code that I have written is not correct but Codecademy says that it is correct and is going to let me move on in the lesson.
I have been trying to solve the issue that I am having with no luck. The problem is that when I run the hits.push(text); line it will output the entire variable but I have tried hits.push(text[i]); and get undefined for the result. Can someone please help me understand where I have made the mistake?
/*jshint multistr:true */
var text = "XsddfasASSFABrandonSFsdfdasBrandonsddfadfaBrandon";
var myName = "Brandon";
var hits = [];
for (i=0; i<=text.length;i++){
if (text[i]===myName[i]){
for(var x=i; x<i+myName.length;x++){
hits.push(text);
}
}
}
if (hits.length===0){
console.log("Your name wasn't found!");
} else {
console.log(hits);
}
The best way I can think to explain your mistake is simply by walking through a bit of the logic of what you have written.
for (i=0; i<=text.length;i++){
Your for loop will iterate i for as many characters as there are in your text variable, so: 49 times.
if (text[i]===myName[i]){
The first run through your for loop, where i=0, you are checking to see if text[0] is strictly equal to myName[0]. text[0] = X and myName[0] = B. The strictly equals condition is not met, so the loop proceeds to increment i repeat: text[1] = s and myName[1] = r. This continues 47 more times, and the condition is never met. myName[i] is undefined after the first 7 loops.
Normally you would do this kind of thing using indexOf, match, search, substr or substring, which are all string methods.
However for the purpose of this exercise you can do:
var text = "XsddfasASSFABrandonSFsdfdasBrandonsddfadfaBrandon";
var myName = "Brandon";
var hits = [],
namePosition = 0;
for (var i = 0; i < text.length; i++) {
if (text[i] === myName[namePosition]) {
hits.push(text[i]);
namePosition ++;
if (hits.length === myName.length) {
break;
}
}
else {
namePosition = 0;
hits = [];
}
}
if (hits.length === 0) {
console.log("Your name wasn't found!");
} else {
console.log(hits);
}
(See it working at http://jsfiddle.net/wCWxr/1/). The problems with your original code include:
you try to compare text[i] to myName[i] but the indices of the two strings won't match up.
you try to push the entire string text into hits instead of one character at a time
your logic doesn't deal with the possibility that the beginning but not the end of myName is in text, e.g. if text was aerwerBrasdfsgars
My suggestion fixes this by recording (with namePosition) what position we are currently at within the string myName, and incrementing that when we find a character in text that matches the relevant character in myName. If the characters do not match then it's not a true hit, so we reset hits = [] and namePosition = 0. If the characters all match then hits eventually reaches the length of myName and so we break out of the loop.
If you are trying to find if myName is in text here is what you do:
RegExp:
var pattern = new RegExp(myName);
if (pattern.test(text)){
console.log(myName);
}else {
console.log("Your name wasn't found!");
}
indexOf:
if (text.indexOf(myName) != -1){
console.log(myName);
}else {
console.log("Your name wasn't found!");
}
if (text[i]===myName[i]){
this line should create an error, because myName[i] is not the first letter of myName.
if (text[i]===myName[0]){
Change to this line should work.
I'm a beginner and a student and I'm hoping someone can help me out. I have an assignment where I need the program to be broken up into 3 functions. The first takes a sentence from the user, the second converts the sentence into a new "pig language" depending on the length of each word, and the third displays the results in the console. I have the heart of this program done, but I have a problem with clearing out the return string. Specifically, once the user has gone through all 3 steps, I don't want them to be able to enter into the 3rd part of the program and see the results again. I want them to have to go back to the beginning. Sorry for drawing this out so much, but I'm just not sure of how else to explain it.
Here's my code:
function prog1(){
var userLang = prompt("Type in your sentence");
//If the user enters an empty string
if(userLang == ""){
console.log("You must enter a sentence");
}
//If the user presses cancel
else if(userLang == null){
wantToQuit = true;
}
//If the user enters in a good string
else {
console.log("Thank you, now go to program 2");
been2prog1 = true;
return userLang;
}
}
function prog2(){
//sets newLang = userLang and splits the string
var newLang = prog1Lang.split(" ");
//enters loop to find length of each split word
var x = 0;
for( x = 0; x < newLang.length; x++ ){
//if it's 5 or less words, add -oink
if ((newLang[x].length) <= 5){
newLang[x] += "-oink";
}
//if it's more than 5 words, add -a
else {
newLang[x] += "-a";
}
}
**newLang.join(" ");**
//put the string back together
console.log("String converted");
been2prog2 = true;
return newLang;
}
function prog3(){
var endLang = prog2Lang;
console.log(endLang);
**delete prog2Lang;**
}
I was thinking "delete" might work, as seen above, but I didn't do anything all all. Then I was thinking a Boolean, but I am not sure how to go about doing so. Any help would be much appreciated.
One last thing, I am also stuck on how to join my string back together. Currently it logs it in the console as being a part of the array and separates each word with quotes and a comma. I've looked up the .join(); and I thought it would do the trick, but it doesn't seem to work either. I put it inside of the if else statements in function 2 but, it just freaks out when I do that, so pointers on this issue would also be much appreciated.
Thank you!
Try assigning the newLang.join to itself..
newLang = newLang.join(" ");
I wasn't sure what the other bit was that you were having trouble with was, I was a bit confused.
if all you are trying to do is clear out a string variable then..
prog2Lang = null;
or
prog2Lang = "";
null is a null object and "" is an empty string.
Is that what you were after?