Getting undefined instead of string - javascript

The output of this program is undefined instead of string name.
I am taking a date as input to the program and comparing the date with the existing dates of president array. In case if the date matches then i want to return the president name for that particular date
process.stdin.resume();
process.stdin.setEncoding('utf8');
var stdin = '';
process.stdin.on('data', function (chunk) {
//printing the value returned by presidentOnDate function
console.log(JSON.stringify(presidentOnDate(chunk)));
});
//This is presidents array
var presidents = [
{"number":32,"president":"Franklin D. Roosevelt","took_office":"1933-03-04","left_office":"1945-04-12"},
{"number":33,"president":"Harry S. Truman","took_office":"1945-04-12","left_office":"1953-01-20"},
{"number":34,"president":"Dwight D. Eisenhower","took_office":"1953-01-20","left_office":"1961-01-20"},
{"number":35,"president":"John F. Kennedy","took_office":"1961-01-20","left_office":"1963-11-22"},
{"number":36,"president":"Lyndon B. Johnson","took_office":"1963-11-22","left_office":"1969-01-20"},
{"number":37,"president":"Richard Nixon","took_office":"1969-01-20","left_office":"1974-08-09"},
{"number":38,"president":"Gerald Ford","took_office":"1974-08-09","left_office":"1977-01-20"},
{"number":39,"president":"Jimmy Carter","took_office":"1977-01-20","left_office":"1981-01-20"},
{"number":40,"president":"Ronald Reagan","took_office":"1981-01-20","left_office":"1989-01-20"},
{"number":41,"president":"George H. W. Bush","took_office":"1989-01-20","left_office":"1993-01-20"},
{"number":42,"president":"Bill Clinton","took_office":"1993-01-20","left_office":"2001-01-20"},
{"number":43,"president":"George W. Bush","took_office":"2001-01-20","left_office":"2009-01-20"},
{"number":44,"president":"Barack Obama","took_office":"2009-01-20","left_office":"2017-01-20"}
];
//PresidentOnDate function which should return a president name based on input date
function presidentOnDate(date) {
var output="";
for(var i=0;i<presidents.length;i++){
//console.log(presidents[i].took_office);
if((presidents[i].took_office)==date){
output+=presidents[i].president;
}
}
return output;
}

I think the problem is you are passing in a buffer instead of a string.
Try changing the chunk buffer to a string before passing it to presidentOnDate.
So instead of presidentOnDate(chunk) try presidentOnDate(chunk.toString())

Try this function it's working fine.
problem you facing when you take input it take \r\n also so when you compare both you get false that y output showing null.
EX:input string: "2009-01-20\r\n" compare with : took_office: "2009-01-20" => result false
EX: input string with trim: "2009-01-20" compare with : took_office: "2009-01-20" => result True
change only : (presidents[i].took_office) ==date.trim()
function presidentOnDate(date) {
var output="";
for(var i=0;i<presidents.length;i++){
if((presidents[i].took_office) ==date.trim()){
output+= presidents[i].president;
}
}
return output;
}

Related

Javascript If statements in Zapier Code, "must return a single object or array of objects."

I am trying to do a simple If function in zapier that returns a number between 1-10 based on another number input. for example if the number input is equal to 7200000 it should output 2. so far i have this:
if (inputData.num === '7200000') {
output = '2';
} else {
output = inputData.num;
}
This is giving me the error "You must return a single object or array of objects."
Can anyone help with this?
Thanks in advance :)
I found the solution,
Input Data: ms = TimeEstimate
var d = new Date(1000*Math.round(inputData.ms/1000));
function pad(i) { return ('0'+i).slice(-2); }
var str = d.getUTCHours() + ',' + pad(d.getUTCMinutes());
console.log(str);
output = [{str}];

String.padStart() not applying in Angular function

I have an angular function which receives a number from a GET request and then will encode that number as base 64. I am trying to use the padStart function outlined here, but when I log the string after calling the function, the string is not padded. Any ideas why?
Angular:
$scope.generateCode = function(){
var number = autogenNumber(); //Pull the number
number.then(function (result) { //Then increment up and convert
var working_str = result.toString();
console.log("The pre padded string is", working_str);
working_str.padStart(8, '1234');
console.log("The padded string is now", working_str, typeof working_str);
})
};
A string is immutable. You have to reassign
working_str = working_str.padStart(8, '1234');

Assign text to variable inside the String

I am saving string into mongoDB with preset variable as
'Current time is ${time}'
After that I am retrieving somewhere else this string and would like to assign value to time
It would look something like this
const time = '15:50'
const response = result //saves string retreived from mongo
res.json({
response: response
})
But that returns 'Current time is ${time}' instead of 'Current time is 15:50'
I am aware that the string should be in `` instead of single quotes for variable to work, not sure though how to implement that as output from mongo
Anyone could point me to correct direction?
An alternative is to pass the string and parameters to a function and reduce over the parameters object:
var str = 'Current time is ${time}';
var params = { time: '13:30' };
function merge(str, params) {
return Object.keys(params).reduce((out, key) => {
return str.replace(`\${${key}}`, params[key]);
}, '');
}
console.log(merge(str, params));
And this is an example of interpolation magic, as mentioned in other answer ;) Note, than even without the evil() ;)
var time = '15:50'
var response = 'Current time is ${time}'
var converted = (_=>(new Function(`return\`${response}\`;`))())()
console.log(converted)
Interpolation is not performed on a string variable that happens to contain a template literal placeholder. In order for interpolation to happen, you must have a literal string in the code, enclosed in back ticks with a placeholder:
let time = '15:50';
let message = `Current time is ${time}`
console.log(message); // "Current time is 15:50"
If you must store strings in your database, you'll have to come up with your own mechanism for interpolating your placeholders.

Javascript Math.log() help wanted

World!
I'm trying to create a program in Javascript that takes the log of a number typed into an HTML input. Unfortunately i've encountered a problem where it wont accept the string with the .replace().
Its Function:
I.E: When log(10) is calculated, the function should first remove the first 4 char's "log(" next remove the last parenthesis ")" and then take the log of the no. between.
HTML includes style elements, button and input form and an output < DIV >.
//Function
function calculate()
{
var inputString = document.getElementById("inpstr");
var output = document.getElementById("output");
//TESTING CODE
/*
if (inputString.value.startsWith("log(").endsWith(")"))
{
console.log(output.innerHTML = inputString.value.substring(4, 20).replace(")", ""));
}
else
{
output.innerHTML = "false";
}
*/
//Math.log() calc *****DOESNT WORK*****
if (inputString.value.startsWith("log(").endsWith(")"))
{
output.innerHTML = Math.log(inputString.value.replace(")", "").substring(4, 20));
}
else
{
output.innerHTML = inputString.value;
}
event.preventDefault();
}
If someone can give me an effective solution that would be much appreciated.
Thanks,
Syntax
Since Math.log() accepts only number values and you're trying to pass a string to it, you should first parse this value into a float number and then pass it to the log function:
let val = parseFloat(inputString.value.replace(")", "").substring(4, 20));
output.innerHTML = Math.log(val);
I'm guessing I got downvoted for being lazy, so here is the quick info. Gonras got it right relating to what you want to extract, but he forgot to check that what's being input is actually a log.
That's where the regex below comes in handy! I'm matching the field to:
^ start of word, since we want to match the entire field.
log(
([-.\d])) any consecutive sequence () of numbers (\d), -, and '.', represented by the []. The \(...\) makes sure to save this inner part for later.
$ is end of word, see 1.
res will be null if there is no match. Otherwise, res[0] is the entire match (so the entire input field) and res[1] is the first 'capture group', at point 3 - which is presumably the number.
This of course fails for multiple "-" inside, or "." etc... so think it over.
//Function
function calculate()
{
var inputString = document.getElementById("inpstr");
var output = document.getElementById("output");
var res = /^log\(([-.\d]*)\)$/.exec(inputString.value);
if (res)
output.innerHTML = Math.log(res[1]);
else
output.innerHTML = res;
}
document.getElementById("output").innerHTML='start';
calculate()
<div id='output'></div>
<input id='inpstr' value='log(2.71828)'></input>
If I wanted to fix your if to supplement Gonras's solution:
if (inputString.value.startsWith("log(") && inputString.value.endsWith(")"))
Yours fails since startsWith() returns a boolean, which obviously doesn't have a endsWith function.

How to replace string values with numeric inside a json object used in google visualization api column chart

I have this Json string that i use for google chart visualization that needs to be in this exact format and i need to replace every value of "v" that is a number to its numeric value( the value without the ""). I should do some javascript replace function, but i couldn't find a way to move around the json object. Here is and example json string that i should modify :
{"cols":[
{"id":"r","label":"Reason","type":"string"},
{"id":"m","label":"Minutes","type":"number"}
],
"rows":[
{"c":[
{"v":"Flour - Blower","f":"Flour - Blower"},
{"v":"7","f":"7"}]},
{"c":[
{"v":"Whole Line - d","f":"Whole Line - d"},
{"v":"4","f":"4"}]},
{"c":[
{"v":"Flour - Pipework","f":"Flour - Pipework"},
{"v":"3","f":"3"}]},
{"c":[
{"v":"Horseshoe - Belt","f":"Horseshoe - Belt"},
{"v":"1","f":"1"}]}
],
"p":null
}
probably i should do something like :
var jsonStr = ...;
for (i in jsonStr.rows) {
for(j in jsonStr[i].c)
{
if (parseInt(jsonStr[i].c[j].v) != 'NaN') {
jsonStr.rows[i].c[j].v = parseInt(jsonStr.rows[i].c[j].v);
}
}
Since JSON is effectively a string, why not put the entire string through a global string.replace:
jsonStr = JSON.stringify(jsonStr);
jsonStr = jsonStr.replace(/"v":"(\d+)"/g, '"v":$1');
Jsfiddle demo
Well, the parsing seems okay to me. It's probably not working because you can't really check if a string contains a number or not by comparing something with NaN
This is because even NaN === NaN, famously, returns false.
I'd suggest that you use the isNaN method (which does use parseInt internally). So, something like this ought to work
for (i in jsonStr.rows) {
for(j in jsonStr[i].c)
{
if (!isNaN(jsonStr[i].c[j].v)) {
jsonStr.rows[i].c[j].v = parseInt(jsonStr.rows[i].c[j].v);
}
}
A function that returns string if isNaN else a number:
function convertNumberToInteger(val) {
if (isNaN(val)) {
return val;
} else {
return parseInt(val);
}
}
Usage:
convertNumberToInteger("sasdfasdf");
Output: "sasdfasdf"
convertNumberToInteger("3");
Output: 3
And if you really want to parse it you can do a forEach on the JSON object

Categories