syntax on nodejs function - node.js

I'm starting right now with coding on JS. There are a few things that I don't understand pretty well, and I'm a little bit confused because I have tried almost all, and I don't get to solve the error. Would someone provide me some help or guidance with this.
my code
function ImparPar(NumIp) {
if(NumIp % 2 === 0) {
return 'Par';
} else {
return 'Impar';
}
}

Your function definition (on Line 1) has the following:
The function keyword
A function name (ImparPar)
A formal parameter (NumIP)
All these make this a function definition.
When you are calling the function later on in the code (line 13) you just need to call it by name. e.g.:
ImparPar(2);
When you are calling a function, you pass it - what is called - an actual parameter (in your case 2).
When you prefix it with the function keyword, it is interpreted as a function definition and therefore does not expect an actual parameter, and instead expects a formal parameter.
If you remove the function keyword from line 13 it should work as expected for you, and just execute the function.

Related

Using unwrap_or_else for error handling in Rust

I have a rust program that has a function
‘is_input_sanitized’ that takes an input
String m, and checks if the input is free of special characters.The method is being used on a separate function in the following way.
let a = match is_input_sanitized(m) {
Ok(m) => m,
Err(_) => { return Err("error"); },
};
I am trying to convert this snippet into using ‘unwrap_or_else’ which will return an error when the input is not sanitized.I have read the documentation and have not been able to decipher a proper way to achieve this. Is this conversion possible?
unwrap_or_else is for extracting Result values. It sounds to me like you don't want to extract the result, so much as make a new one and propagate errors. You have two different things you want to do here. The first is that you want to change the error from whatever it started as (indicating by your _ in the pattern match) to something you control, and the second is that you want to return errors.
Replacing the error can be done with map_err, which takes a function (such as a closure) and applies that function to the error if the Result is an Err. If the result is Ok, then it returns the current Result unmodified.
The second problem, returning on Err, is exactly what the question mark operator was invented for.
Chaining results using match can get pretty untidy; luckily, the ? operator can be used to make things pretty again. ? is used at the end of an expression returning a Result, and is equivalent to a match expression, where the Err(err) branch expands to an early return Err(From::from(err)), and the Ok(ok) branch expands to an ok expression.
So what you're looking for is
let a = is_input_sanitized(m).map_err(|_| "error")?;

What is the equivalent of 'pass' from Python?

I want to check if the result from a request is having any issue. I categorize it into two: i) server error, ii) something else that is not a success. The third category is, result actually being a success. However, in the third category, I don't want to do anything.
So, my desirable code is:
if res.status().is_server_error() {
panic!("server error!");
} else if !(res.status.is_success()){
panic!("Something else happened. Status: {:?}", res.status());
} else{
pass;
}
I am aware of other ways to achieve this result: using match, ifs instead of if else if. But I wanted to learn what is the corresponding keyword of pass, like we have in Python. My aim is: if result is successful, just move along, if not, there are two ways to handle that panic.
Behold!
if predicate {
do_things();
} else {
// pass
}
Or even better
if predicate {
do_things();
} // pass
Or as I’ve recently taken to calling it the implicit + pass system
if predicate {
do_things();
}
In all seriousness there is no pass and no need for a pass in rust. As for why it exists in python, check out this answer
Python needs pass because it uses indentation-based blocks, so it requires some syntax to "do nothing". For example, this would be a syntax error in a Python program:
# syntax error - function definition cannot be empty
def ignore(_doc):
# do nothing
count = process_docs(docs, ignore) # just count the docs
The ignore function has to contain a block, which in turn must contain at least one statement. We could insert a dummy statement like None, but Python provides pass which compiles to nothing and signals the intention (to do nothing) to the human reader.
This is not needed in Rust because Rust uses braces for blocks, so one can always create an empty block simply using {}:
// no error - empty blocks are fine
fn ignore(_doc: &Document) {
// do nothing
}
let count = process_docs(docs, ignore); // just count the docs
Of course, in both idiomatic Python and Rust, one would use a closure for something as simple as the above ignore function, but there are still situations where pass and empty blocks are genuinely useful.

Groovy Syntax Confusion

I'm new to Groovy/Gradle and I'm currently learning the syntax, but I'm a bit confused by its syntax because it seems that same thing can be achieved by a lot of different ways. Does anyone know what's the meaning of the following groovy code:
something(x, y) {
// some code here
}
It is definitely not a method declaration because it doesn't have the def keyword. It also doesn't look like an invocation of the something method, because that wouldn't explain the curly braces. What exactly does this code do?
It is definitely not a method declaration because it doesn't have the
def keyword.
Method definitions do not require the def keyword.
It also doesn't look like an invocation of the something method,
because that wouldn't explain the curly braces. What exactly does this
code do?
something(x, y) {
// some code here
}
It is an invocation of a method. That code is invoking a method named something and passing 3 parameters. x and y are the first 2 parameters and a groovy.lang.Closure is the 3rd. That code is the same as the following:
def closure = {
// some code here
}
something(x, y, closure)

Is there is option to evaluate values in nodejs without using eval or safe-eval?

I am trying to create a function in javascript having the same behavior as eval as it is not that much secure as safe-eval npm package. When I am trying to use safe-eval library rather than eval it doesn't support many of the functions as if, switch etc so it is giving me error as
SyntaxError: Unexpected token if
So I tried to write a code for same but facing some issues in that as well.
Is Anyone know how to use the safe-eval for condition execution or is anyone knows how to write a similar customized function/method for achieving the same goal.
thanks !!
The safe-eval npm page says of the input:
the JavaScript code must be an expression (something which evaluates to a value).
if(...) { ... } is a statement, not an expression.
The simple solution here is one that is already suggested by the documentation on that same NPM page: wrap your statements inside of a function expression that you immediately call.
var code = '(function square(b) { return b * b; })(5)'
var evaluated = safeEval(code)
You could put anything inside of that function, including statements:
var code = '(function square(b) { if(b === 5) { return "yes"; } else { return 0; } })(5)'
var evaluated = safeEval(code)
See the documentation: (emphasis added)
Currently, it works only with Node.js, and the JavaScript code must be an expression (something which evaluates to a value).
if is a statement, not an expression.
You can make it evaluate statements by wrapping them in an IIFE, which is an expression.

Xquery ( XDMP-ARGTYPE error ) the expected type of a function input is different from the actual type

I'm trying to remove stop words from a text in MarkLogic 8 using this function :
declare function rec:remove-stop-words($string, $stop_words) {
(: This is a recursive function. :)
if(not(empty($stop_words))) then
rec:remove-stop-words(
replace($string, $stop_words[1], '', 'i'),
(: This passes along the stop words after
the one just evaluated. :)
$stop_words[position() > 1]
)
else normalize-space($string)
};
Here where I call it
for $r in /rec:Record
return
rec:remove-stop-words(data($r/rec:Abstract), $stop_words}
It gives me the following error
XDMP-ARGTYPE: (err:XPTY0004) fn:replace((xs:untypedAtomic("
chapter
utilized asymmetry of n..."), xs:untypedAtomic("
book
interrelationship between ...")), "a", "", "i") -- arg1 is not of type xs:string?
The function expects a string type but the actual type is untypedAtomic. I don't know what to do!
NOTE: (( The problem is not in the function because I've tried to use it for a different text and it worked well )).
I tried to the code by converting untypedAtomic to string by:
return
<info>{rec:remove-stop-words(data(xs:string($r/rec:Abstract)), $stop_words)}</info>
but I got this error:
XDMP-ARGTYPE: (err:XPTY0004) fn:replace(("
chapter
utilized asymmetry of n...", "
book
interrelationship between ..."), "a", "", "i") -- arg1 is not of type xs:string
The problem is that when you iterate over /rec:Record and pass $r/rec:Abstract as input, at least one of your records is returning more than one rec:Abstract. The function signature for rec:remove-stop-words allows a sequence of values as input for $string, but the function body where you call fn:replace only handles input for a single value, so it throws an argument exception (given xs:string+ and expecting xs:string?).
You can handle the sequence by iterating over rec:Abstract before you call the function:
for $r in /rec:Record
for $a in $r/rec:Abstract
return
rec:remove-stop-words($a, $stop_words)
If you use stricter function signatures, it can help avoid problems like this, or at least make them easier to debug. For example, if you define your function to only allow a single input for the first parameter:
rec:remove-stop-words($string as xs:string, $stop_words as xs:string*)
...
This will throw a similar exception when $string is passed a sequence, but higher up the call stack, which can help make these types of errors a little more obvious.
Try using this code -
for $r in /rec:Record
return
rec:remove-stop-words(fn:string($r/rec:Abstract), $stop_words}
It looks like you are sending it a node and not a string. Try $r/rec:Abstract/text() or $r/rec:Abstract/string()

Resources