Matching string - javascript

I have done a bare minimum of javascript coding via code academy. I also help build spreadsheets in a family business, and we are working on new spreadsheets for 2017 (late!!) with additional capabilities which make function calls within the sheet very unwieldy. Right now experimenting with very simple custom function intending to work up to a few I need to use. Ran into problems so cut out everything from first script except the problem area.
commission(platform, amount) takes a name and numerical amount respectively. Based on these values I will be setting up commission formulas. Discovered a problem matching the name. After deleting all but the problem area, all I have is:
function commission(platform, amount) {
return platform=="AB";
};
It is run from spreadsheet as:
(called from cell e4) =commission(c4,d4)
The value returned is FALSE.
c4 contains the text AB
d4 (irrelevant right now) contains 1000
The problem arose with if(platform == "AB") {.......
The function was not evaluating the condition as true. When I rewrote it to return the value of platform it did indeed return "AB" in cell e4 from which the function was called.
So the variable clearly does read (and return, when told to) the correct contents of c4, but does not recognize this value in the conditional statement.
I have seen condition statements in javascript use both == and ===. Not sure if there is any difference, tried both. Tried single and double quotation marks.
Posting on the good sheets forum, which requested I cross post.

May be intended/irrelevant but I noticed you have an extra ` in your code.
function commission(platform, amount) {
if(platform == "AB"){
return amount;
}
else
{
return 0; /// insert your own return
}
};
Google spreadsheet screenshot of solution

Related

How to accept an input in the console from the user (JS)?

I tried to create a JavaScript program that outputs the binary format of an English letter on input. I had to put the value in the code. How can the value be entered in the console when the program runs?
function returnBinaryLetter(char) {
return ((/^[a-z]$/).test(char)) ? char.charCodeAt(0).toString(2).padStart(8, '0') : 'Sorry, that is not a letter.'
}
// Something like:
// const input = consoleInputFunction('Enter a number.');
// console.log(returnBinaryLetter(input.toLowerCase()));
EDIT 1: This is not for a webpage. This is a JS program which I will run using Node.js. I require a solution with just JS, not with some framework (if that is even possible, mentioning just to be specific).
EDIT 2: I have made the code better after suggestions in Endothermic Dragon's answer.
To directly answer your question, you would use prompt to get a user input in this case.
However, you don't need all of that code. Try this:
function returnBinaryLetter(char) {
if ((/^[a-z]$/).test(char)) {
return char.charCodeAt(0).toString(2).padStart(8, '0')
} else {
return 'Sorry, that is not a letter.'
}
}
var input = prompt('Enter letter to be converted to binary:').toLowerCase();
console.log(returnBinaryLetter(input))
While it may seem a bit intimidating, here's the whole thing broken down:
Ask for an input using prompt, and convert it to lowercase.
Pass the character to the function returnBinaryLetter, and log the output.
Now for the function returnBinaryLetter:
Check if it is a single lowercase letter, using some RegEx.
If it is, return binary. Otherwise, return an error with a description.
Hmm, but how does the binary conversion work?
First, take the character and get its character code.
Next, convert that code to binary.
Finally, pad the start so it is an 8-bit number. If it is not 8 digits, add on 0s at the beginning until it is.
Here, you can see that a more dynamic conversion looks much shorter, and cleaner as well, compared to manually entering about 28 lines of code.
Bonus:
Surprise, surprise! You can further shorten it. Using a ternary operator, you can skip the if-else statement.
function returnBinaryLetter(char) {
return ((/^[a-z]$/).test(char)) ? char.charCodeAt(0).toString(2).padStart(8, '0') : 'Sorry, that is not a letter.'
}
var input = prompt('Enter letter to be converted to binary:').toLowerCase();
console.log(returnBinaryLetter(input))
Now, it's a one-liner!
A ternary operator is usually used within variables when you want to assign its value based on a condition. The ternary operator first checks if the condition inside the brackets is true, and if it is, it returns the first statement (between ? and :), and if not, it returns the second statement (after the :). Pairing this with the return statement of a function, you get a one-liner function!
Feedback:
Since it seems that you are following CamelCase, I thought I would mention that function names should always start with a capital letter, along with each word after that also starting with a capital letter. Variables are different however - for variables, you do make the first letter lowercase, but make all the other words uppercase. In addition, the function name returnBinaryLetter might seem intuitive to you, but not for anyone looking at the code. A more intuitive name that exactly describes its function would be LowercaseLetterToBinary.
For NodeJS, You can use inquirer, which provides different kinds of prompts for the command line (such as text, list, checkbox etc).
Prerequistes:
Install it with npm install inquirer
Example
const { prompt } = require("inquirer");
async main() {
const binaryLetter = await prompt({
type: 'input',
name: 'letter',
message: `What's your name >>`
})
.then(answer => returnBinaryLetter(answer['letter']));
}
main();

How to use JavaScript in Node-red to display message based on dropdown options

Given this Node-red flow:
I am unfortunately unsure about how I should implement it in function.
I have 3 options in both dropdowns, one displaying meattype the other doneness. Whenever I choose a combination of the dropdowns, I should have the proper temperature given in the text output.
I have tried using If, but I still have problems with getting it to work.
I only have very basic knowledge of Javascript language, so I hope someone could help and at least lead me in the right direction.
Thank you
EDIT:
In the If code in my function node I had "A conditional expression" present, though I got this fixed by changing If from:
if(msg.payload = "")
to
if(msg.payload == "")
This fixed my code and gave me the expected results.
var payload = msg.payload
if(msg.payload == "KalvRoed"){
msg.temperature = "53-57 grader"}
I had "A conditional expression" which means I had to change my code, so that "if" was written with "==" rather than "=". If "if" had been written with "=" the function node would think that I was creating a variable, while I was trying to have it do something if was true.
var payload = msg.payload
if(msg.payload == "KalvRoed"){
msg.temperature = "53-57 grader"}
Hope that makes sense

Get URL from image via script on Google Sheets - does this code still work?

I am using Google Sheets.
Cell A1:
=image("address.jpg")
This puts the image in a cell. To get the url from Stack Overflow produced this answer.
I created the script, and Google recognised it in autocomplete. The error I am getting is:
TypeError: Cannot call method "match" of null. (line 10).
I ran the regex through a checker, and it does get what I am looking for i.e the address, but the error seems to indicate that it's coming back with nothing.
Does this still work? Has Google changed something?
My work-around is to create two sheets and have §=image in one sheet, while in the second sheet, I remove § and use a standard Google function.
The linked solution is far better, and I'd like to implement that if I could. I cannot post a comment on the original solution's page as I don't have reputation points.
In your situation, "null" is given as an argument. Because the formula cannot be directly retrieved by =getImageUrl(A1). By this, the error of Cannot call method "match" of null. occurs. The formula can be retrieved by getFormula(). This is also mentioned at Eric Koleda's answer. So for example, the script can be modified as follows.
Modified script:
function getImageUrl(range) {
var formula = SpreadsheetApp.getActiveSheet().getRange(range).getFormula(); // Added
var regex = /=image\("(.*)"/i;
var matches = formula.match(regex);
return matches ? matches[1] : null;
}
Note:
If =image("URL") is put in "A1", when you use this like =getImageUrl("A1"). Please enclose A1 by the double quotes. By this, the string of "A1" is given to the function and is used as the range.
Reference:
getFormula()

Passing Dynamic Range:Google Script

I'm trying to write a custom function that will count and return the number of cells that contain information on a singular column. I'm using a range of A(x):Z(x) and I can't seem to dynamically pass these so I can get a user defined range everytime.
Edit: Current Error I'm receiving right now says: Missing ) after argument list. (line 10, file "Number Of Updates")
So far I have this....
function updateNum(row1,col1,row2,col2)
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName("report status");
var r = s.getActiveRange(row1+col1:row2+col2); <---Line with error
return (range.length-2)/2
}
any suggestions on how I could make this pass the range?
thanks,
Alexander
change the line for:
var r= s.getRange(row1, col1, row2-row1+1, col2-col1+1);
but that won't solve your problems has the line just behind is a non sense. "range" is not declared. I don't see where you want to go exactly. please write some pseudocode.
If what you want is to count the number of cells that got informations in it, just use the spreadsheet native function
counta()
Its not possible with custom functions because they are deterministic. That is, they will return the same result given the same input.
In your case even if you fix the bugs you are still not passing the actual input just its range limits. Thus if the data inside the range changes you still pass the same input limits thus will return the previous cached result.
There are ways arround that like passing an extra parameter that always changes like 'now()'but that has performance problems as it will recalculate constantly.

How would you implement auto-capitalization in JavaScript/HTML

I need to implement auto-capitalization inside of a Telerik RadEditor control on an ASPX page as a user types.
This can be an IE specific solution (IE6+).
I currently capture every keystroke (down/up) as the user types to support a separate feature called "macros" that are essentially short keywords that expand into formatted text. i.e. the macro "so" could auto expand upon hitting spacebar to "stackoverflow".
That said, I have access to the keyCode information, as well I am using the TextRange methods to select a word ("so") and expanding it to "stackoverflow". Thus, I have some semblence of context.
However, I need to check this context to know whether I should auto-capitalize. This also needs to work regardless of whether a macro is involved.
Since I'm monitoring keystrokes for the macros, should I just monitor for punctuation (it's more than just periods that signal a capital letter) and auto-cap the next letter typed, or should I use TextRange and analyze context?
Have you tried to apply the text-transform CSS style to your controls?
I'm not sure if this is what you're trying to do, but here is a function (reference) to convert a given string to title case:
function toTitleCase(str) {
return str.replace(/([\w&`'‘’"“.#:\/\{\(\[<>_]+-? *)/g, function(match, p1, index, title){ // ' fix syntax highlighting
if (index > 0 && title.charAt(index - 2) != ":" &&
match.search(/^(a(nd?|s|t)?|b(ut|y)|en|for|i[fn]|o[fnr]|t(he|o)|vs?\.?|via)[ -]/i) > -1)
return match.toLowerCase();
if (title.substring(index - 1, index + 1).search(/['"_{([]/) > -1)
return match.charAt(0) + match.charAt(1).toUpperCase() + match.substr(2);
if (match.substr(1).search(/[A-Z]+|&|[\w]+[._][\w]+/) > -1 ||
title.substring(index - 1, index + 1).search(/[\])}]/) > -1)
return match;
return match.charAt(0).toUpperCase() + match.substr(1);
});
}
Sometimes, not to do it is the right answer to a coding problem.
I really would NOT do this, unless you feel you can write a script to correctly set the case in the following sentence, if you were to first convert it to lowercase and pass it into the script.
Jean-Luc "The King" O'Brien MacHenry van d'Graaf IIV (PhD, OBE), left his Macintosh with in Macdonald's with his friends MacIntosh and MacDonald. Jesus gave His Atari ST at AT&T's "Aids for AIDS" gig in St George's st, with Van Halen in van Henry's van, performing The Tempest.
You have set yourself up for a fall by trying to create a Natural Language Parser. You can never do this as well as the user will. At best, you can do an approximation, and give the user the ability to edit and force a correction when you get it wrong. But often in such cases, the editing is more work than just doing it manually and right in the first place.
That said, if you have the space and power to store and search a large n-gram corpus of suitably capitalized words, you would at least be able to have a wild stab at the most likely desired case.
You pose an interesting question. Acting upon each key press may be more limiting because you will not know what comes immediately after a given keycode (the complexity of undoing a reaction that turns out to be incorrect could mean having to go to a TextRange-based routine anyway). Granted, I haven't wrestled with code on this problem to date, so this is a hypothesis in my head.
At any length, here's a Title Casing function (java implementation inspired by a John Gruber blogging automation) which may spur ideas when it comes to handling the actual casing code:
http://individed.com/code/to-title-case/

Categories