I have a task that I am trying to solve. I have created a function named printRange which will print the number range between rangeStart and rangeStop and all values separated by a comma.
var rangeStart, rangeStop;
function printRange(rangeStart, rangeStop) {
var numberRow = "";
for(var i=rangeStart; i <= rangeStop; i++) {
numberRow += "," + i;
}
return numberRow;
}
I have also created another function named "printRangeReversed" which will print the range but in the opposite order. Again, the values will be separated by a comma.
function printRangeReversed(rangeStart, rangeStop) {
var numberRow = "";
for(var i=rangeStop; i >= rangeStart; i--) {
numberRow += "," + i;
}
return numberRow;
}
Now I should create a new function called printAnyRange. If 'rangeStart' is smaller than 'rangeStop' then I should call the function 'printRange()'. If 'rangeStart' is greater than 'rangeStop' then I should call the function 'printRangeReversed()'.
How do I do this? I have tried myself with the code below but does not get any satisfying results... Thanks in advance!
function printAnyRange(rangeStart, rangeStop) {
var numberRow = "";
if(rangeStart < rangeStop) {
printRange();
}
else {
printRangeReversed();
}
}
printAnyRange(24, 41);
You forgot to supply the arguments to printRange() and printRangeReversed().
Just change
if(rangeStart < rangeStop) {
printRange();
}
else {
printRangeReversed();
}
with
if(rangeStart < rangeStop) {
printRange(rangeStart, rangeStop);
}
else {
printRangeReversed(rangeStart, rangeStop);
}
and it should work.
Related
I actually want to update my previous question Javascript understanding return because the code below is quite similar to the previous one but since that question was answered already I decided to post this. The code of my previous questions works fine already but I want to satisfy some of my curiosities so I experimented the code and moved the return namePosition,
function positionIdentifier(name, nameArray) {
var namePosition;
for (i = 0; i < nameArray.length; i++) {
if (nameArray[i] == name) {
namePosition = function() {
alert("Your name is in position number " + (i + 1));
}
}
}
return namePosition;
}
name1Array = ["look", "sky", "walk", "kier"];
positionIdentifier("walk", name1Array)();
Why does it alert the wrong position (i+1)? Instead it alerts the final position which is the length of the array.
You forgot to use break statement here is correct code:
<script>
function positionIdentifier(name, nameArray) {
var namePosition;
for (i = 0; i < nameArray.length; i++) {
if (nameArray[i] == name) {
namePosition = function () {
alert("Your name is in position number " + (i + 1));
};
break;
}
}
return namePosition;
}
name1Array = ["look", "sky", "walk", "kier"];
positionIdentifier("walk", name1Array)();
</script>
That my friend is what is called a closure in javascript.
function() {
alert("Your name is in position number " + (i + 1));
}
When positionIdentifier function is invoked, i has the last value from the for loop.
To fix this you need to do this
function positionIdentifier(name, nameArray) {
var namePosition;
for (i = 0; i < nameArray.length; i++) {
if (nameArray[i] == name) {
/* now this will keep the correct value of i */
namePosition = (function(i) {
return function(){
alert("Your name is in position number " + (i + 1));
}
})(i)
/* now this will keep the correct value of i */
}
}
return namePosition;
}
Here is a working fiddle https://jsfiddle.net/uxyot51b/
So, I just want to shorten the code below:
var start=function(){
var bevetel = document.getElementsByClassName("bevetel");
var yearlyincome2010=0;
var yearlyincome2011=0;
var yearlyincome2012=0;
var yearlyincome2013=0;
var yearlyincome2014=0;
var yearlyincome2015=0;
var yearlyincome2016=0;
for(var i=0; i < bevetel.length; i++) {
if (i<3) {
if (bevetel[i].value) {
yearlyincome2010 += parseInt(bevetel[i].value);
document.getElementById("yearlyincome2010").innerHTML=yearlyincome2010;
}
else {}
}
else if (i<7){
if (bevetel[i].value) {
yearlyincome2011 += parseInt(bevetel[i].value);
document.getElementById("yearlyincome2011").innerHTML=yearlyincome2011;
}
else {}
}
else if (i<11) {
if (bevetel[i].value) {
yearlyincome2012 += parseInt(bevetel[i].value);
document.getElementById("yearlyincome2012").innerHTML=yearlyincome2012;
}
else {}
}
else if (i<15) {
if (bevetel[i].value) {
yearlyincome2013 += parseInt(bevetel[i].value);
document.getElementById("yearlyincome2013").innerHTML=yearlyincome2013;
}
else {}
}
else if (i<19) {
if (bevetel[i].value) {
yearlyincome2014 += parseInt(bevetel[i].value);
document.getElementById("yearlyincome2014").innerHTML=yearlyincome2014;
}
else {}
}
else if (i<23) {
if (bevetel[i].value) {
yearlyincome2015 += parseInt(bevetel[i].value);
document.getElementById("yearlyincome2015").innerHTML=yearlyincome2015;
}
else {}
}
}
};
Theese #yearlyincome201$'s are IDs of headings...
.bevetel is a class for inputs.
This function calculates each FOUR inputs and gives me the answer of them separately.
var YearsAndIncomes = {
yearIncomes = [],
quarters = [],
}
let year = 2010;
let income = 0;
for (let i = 0; i < bevetel.length; i++) {
income += bevetel[i];
if ((i%4) == 3) {
YearsAndIncomes.yearIncomes.push("YearlyIncome" + year);
YearsAndIncomes.income = income;
income = 0;
year += 1;
}
}
for (let i = 0; i < YearsAndIncomes.yearIncomes.length; i++) {
document.getElementById(YearsAndIncomes.yearIncomes[i]).innerHTML = YearsAndIncomes.income[i];
}
This makes it easier and abstracts your work. Basic rules of looping. Don't hard code anything that you are going to have to add more of later (like years). Try and do everything that is repeated once, (i.e. document.getElementById). This is performed multiple times, but only exists in one place, so you always know where to go if it needs to be fixed or changed.
Also, use 'for (let i' instead of 'for (var i'. Var makes a global variable every time, which you don't want on iterators like 'i'. Let makes a variable that disappears once you are out of the closure, i.e. the 'let i' only exists inside that for loop.
I've created a JavaScript object to get the number of times a character repeats in a string:
function getFrequency(string) {
// var newValsArray =[];
var freq = {};
for (var i=0; i<string.length;i++) {
var character = string.charAt(i);
if (freq[character]) {
freq[character]++;
} else {
freq[character] = 1;
}
}
return freq;
}
Now, I'm trying to construct a new string composed of the keys & their properties (the letters) & numbers of times the letters repeat if the number (property) is more than one but I keep getting undefined and I don't know why:
function newString(freq){
var newValsArray = [];
for (var prop in freq) {
if (freq[prop]>1){
newValsArray.push(prop + freq[prop]);
}
else if (freq[prop] < 2){
newValsArray.push(prop);
}
}
return newValsArray;
}
I feel like my syntax is off or something... if anyone has any suggestions, I'd really appreciate it...
You aren't explicitly returning anything from newString(), so it will return undefined. It sounds like you want something like this:
return newValsArray.join('');
at the end of newString() to construct an actual string (instead of returning an array). With that change, newString(getFrequency("Hello there") will return 'He3l2o thr'.
function getFrequency(string) {
// var newValsArray =[];
var freq = {};
for (var i = 0; i < string.length; i++) {
var character = string.charAt(i);
if (freq[character]) {
freq[character] ++;
} else {
freq[character] = 1;
}
}
return freq;
}
function newString(freq) {
var newValsArray = [];
for (var prop in freq) {
if (freq[prop] > 1) {
newValsArray.push(prop + freq[prop]);
} else if (freq[prop] < 2) {
newValsArray.push(prop);
}
}
return newValsArray.join("");
}
var mystring = "Here are some letters to see if we have any freq matches and so on.";
var results = newString(getFrequency(mystring));
var elem = document.getElementById("results");
elem.innerHTML = results;
<div id="results"></div>
You are not returning anything from the newString function. Add return newString; as the last line of the newString function. Adding that line does result in something being returned, though I can't tell if it is what you expected.
var text = "asdfjhwqe fj asdj qwe hlsad f jasdfj asdf alhwe sajfdhsadfjhwejr";
var myFreq = getFrequency(text);
show(myFreq);
var myNewValsArray = newString(myFreq);
show(myNewValsArray);
function getFrequency(string) {
// var newValsArray =[];
var freq = {};
for (var i=0; i<string.length;i++) {
var character = string.charAt(i);
if (freq[character]) {
freq[character]++;
} else {
freq[character] = 1;
}
}
return freq;
}
function newString(freq){
var newValsArray = [];
for (var prop in freq) {
if (freq[prop]>1){
newValsArray.push(prop + freq[prop]);
}
else if (freq[prop] < 2){
newValsArray.push(prop);
}
}
return newValsArray; // ******** ADD THIS LINE
}
function show(msg) {
document.write("<pre>" + JSON.stringify(msg, null, 2) + "</pre>");
}
Im writing a simple function in Google Spreadsheets.
I want to input two ranges in the argument something like this:
=EctsPartial(C3:C4, E3:E4)
For the following function I wrote:
function EctsPartial(rangeA, rangeB) {
Logger.log(rangeA+" "+rangeB);
var noten = SpreadsheetApp.getActiveSheet().getRange(rangeA).getValues();
var ects = SpreadsheetApp.getActiveSheet().getRange(rangeB).getValues();
for(var i=0; i < SpreadsheetApp.getActiveSheet().getRange(rangeB).getHeight(); i++){
if(noten[i] != "" && noten[i] != 5) {
summe = summe - 0;
ects[i] = ects[i] - 0;
summe = summe + ects[i];
}
Logger.log(i+":");
Logger.log(summe);
}
return summe;
};
But the program keeps telling me that the argument of getRange() is not correct. If I manually type "C3:C4" (including the ") it works but otherwise it doesn't.
What am I doing wrong?
I think this is what you are trying to do. This is for custom spreadsheet functions.
In spreadsheet, the following code allows you to type =EctsPartial(C1) instead of =EctsPartial("C1"). If you put return noten on the script, it will get the value of C1
function EctsPartial(rangeA, rangeB) {
if (rangeA.map) {
return rangeA.map(EctsPartial);
} else {
var noten = rangeA;
}
}
https://developers.google.com/apps-script/guides/sheets/functions#optimization
A couple of options include:
1.
=EctsPartial("C3:C4"; "E3:E4")
.gs:
function EctsPartial(rangeA, rangeB) {
var noten = SpreadsheetApp.getActiveSheet().getRange(rangeA).getValues();
var ects = SpreadsheetApp.getActiveSheet().getRange(rangeB).getValues();
var sum = 0;
noten.forEach(function(value) {
sum += value[0];
});
ects.forEach(function(value) {
sum += value[0];
});
return sum;
}
2.
=EctsPartial(C3:C4; E3:E4)
.gs:
function EctsPartial(rangeA, rangeB) {
var sum = 0;
rangeA.forEach(function(value) {
sum += value[0];
});
rangeB.forEach(function(value) {
sum += value[0];
});
return sum;
}
I have a function that performs a Luhn check on a card entry when a form is posted.
<script language="javascript">
function Calculate(Luhn)
{
var sum = 0;
for (i=0; i<Luhn.length; i++ )
{
sum += parseInt(Luhn.substring(i,i+1));
}
var delta = new Array (0,1,2,3,4,-4,-3,-2,-1,0);
for (i=Luhn.length-1; i>=0; i-=2 )
{
var deltaIndex = parseInt(Luhn.substring(i,i+1));
var deltaValue = delta[deltaIndex];
sum += deltaValue;
}
var mod10 = sum % 10;
mod10 = 10 - mod10;
if (mod10==10)
{
mod10=0;
}
return mod10;
}
function Validate(Luhn)
{
var LuhnDigit = parseInt(Luhn.substring(Luhn.length-1,Luhn.length));
var LuhnLess = Luhn.substring(0,Luhn.length-1);
if (Calculate(LuhnLess)==parseInt(LuhnDigit))
{
return true;
}
alert("\n\nYou have mis-typed your card number! \nPlease check and correct.\n\n")
return false;
}
I also have a function that removes any spaces that may have been entered in the card number onblur.
function stripChar(sValue, sChar) {
var i, tempChar, buildString;
buildString = ""
for (var i=0; i<sValue.length; i++) {
tempChar = sValue.charAt(i);
if (tempChar != sChar) {
buildString = buildString + tempChar;
}
}
return buildString;
How do I combine the functions so that the spaces are removed and the card number checked onblur.
In your onblur function you could use:
Validate(stripChar(sValue, sChar));