return a return in javascript - javascript

I want to write a assert() function in Js. Something like this:
assert = function(condition, message) {
if(condition) {
console.log(message);
} else {
return return;
}
}
But it's not true.
We can write it like this:
assert = function(condition, message) {
if(condition) {
console.log(message);
return true
} else {
return false;
}
}
And use that like this:
function () {
if(!assert(condition)) { return; }
//Other Lines
}
But it could be better if we were be able to use that like this:
assert(condition, 'OK');
Is it possible to return a return?
In fact have we any way to use something like to previous line to end a function by a assert?
Update:
My goal is end a function by a simple assert(condition) use, and not
with use second conditions like if(!assert(condition)) { return; }.
p.s: I'm a newbie.

How about throwing an exception from assert if not true and otherwise nothing. That way, you can use them as you might be familiar already from other languages.
Code example:
assert = function(condition, message) {
if(condition) {
console.log(message);
} else {
throw "Assertion failed!";
}
}

It seems to me you just want to write less code. If you want to write lots of asserts then consider having a function that processes your list for you, then you only need to maintain an array of parameters:
var list = [
[condition, 'OK'],
[condition2, 'OK'],
[condition3, 'OK'],
[condition4, 'OK']
];
function runAsserts(asserts){
for(var i = 0; i < asserts.length; i++){
if(!assert(asserts[i][0], asserts[i][1])) {
return;
}
}
}
Then you just call it with:
runAsserts(list);

Related

How to reuse conditional check for each function?

I have many functions example like this
function update() {
if (isAdminUser()) {
return false;
}
...
}
function get() {
if (isAdminUser()) {
return false;
}
...
}
...
is there any possible way to have the conditional statement
if (isAdminUser()) {
return false;
})
written once and run by itself at the beginning of each function. I'm using javascript
You could use a higher order function to encapsulate the logic needed to run before a specific function is run. Higher order functions take functions as parameters, therefore a possible solution to your problem could look like this:
function withIsAdminUser(callback) {
return function() {
if (isAdminUser()) {
return false;
}
return callback();
}
}
function getRaw() {
// Do something here, this whole function could also be inlined
}
const get = withIsAdminUser(getRaw);
If you use TypeScript try decorators.
Docs: https://www.typescriptlang.org/docs/handbook/decorators.html#decorators
maybe you can define a function that can accept another function as an argument and returns false if that function (i.e isAdminUser in your code snippet) returns true
const checkUser = func => func() && false
then the function can be used like:
function update() {
if (checkUser(isAdminUser)) {
// update() logic will only run if user is not admin
}
}
function get() {
if (checkUser(isAdminUser)) {
// get() logic will only run if user is not admin
}
}

JSDoc for a method that doesn't return anything

I'm trying to fix JSDoc for my methods right now. And I'm confused of what I should write for it as the method doesn't return anything but call another method depending on if/else code.
methodOne () {
if (something) {
this.runMethod()
} else {
this.runAnotherMethod()
}
}
Try adding the following:
methodOne(): void {
if (something) {
this.runMethod()
} else {
this.runAnotherMethod()
}
}

How to exit (escape) a function from for loop inside of it?

This is theoretical question to understand how many escapes (return or exit) can apply to nested loops or other controls and functions.
I confused about this because I am stuck in the code
How to escape from for ... each loop and method at the same time?
I can't stop iterating over options in select element.
I tried return and return false already, but am unsuccesful.
Generally how we can do that?
function() {
for (...) {
if (...) {
$(...).each(function() {
// You have to exit outer function from here
});
}
}
}
Use a shared variable between the loops. Flip it to true at the end of the each() loop if you want to exit and at the end of the for-loop check for it being true. If yes, break out of it.
I would do it this way:
Create a boolean variable to check on each loop, and if the variable is true, then exit the loop (do this for each).
var exitLoop = false;
$(sentences).each(function() {
if(exitLoop) {return;}
var s = this;
alert(s);
$(words).each(function(i) {
if(exitLoop) {return;}
if (s.indexOf(this) > -1)
{
alert('found ' + this);
throw "Exit Error";
}
});
});
Note this is not the correct use of a try-catch as a try-catch should strictly be used for error handling, not jumping to different sections of your code - but it will work for what you're doing.
If return is not doing it for you, try using a try-catch
try{
$(sentences).each(function() {
var s = this;
alert(s);
$(words).each(function(i) {
if (s.indexOf(this) > -1)
{
alert('found ' + this);
throw "Exit Error";
}
});
});
}
catch (e)
{
alert(e)
}
Code taken from this answer
The loop can also be exited by changing the iterator value.
var arr = [1,2,3,4,5,6,7,8,9,10];
for(var i = 0;i<arr.length;i++){
console.log(i);
compute(i);
function compute(num){
//break is illegal here
//return ends only compute function
if(num>=3) i=arr.length;
}
}
"label"s are the solution for scope processes like breaking loops. Here is the built-in answer I realized after years: https://css-tricks.com/you-can-label-a-javascript-if-statement/
Not ideal but you can do
let result = false;
function() {
for (...) {
if (...) {
$(...).each(function() {
result = true;
});
}
}
if (result == true){
return;
}
}
As in most languages. The keyword to exit a loop is break;
More info here:
http://www.w3schools.com/js/js_break.asp

Using function results in "function source code" and not evaluated function value?

The following code sample (also at http://jsfiddle.net/MZwBS/)
var items = [];
items.push({
example: function() {
if(0 > 1) {
return 'true';
} else {
return 'false';
}
}
});
document.write(items[0].example);
produces
'function () { if (0 > 1) { return "true"; } else { return "false"; } }'
instead of
'false'
It seems like I've been able something like this with ExtJS. Can anyone tell me where I went wrong? I'd like to evaluate anonymous functions like this on-the-fly.
Do you mean to execute it?
document.write(items[0].example());​
You want:
document.write(items[0].example());
When you skip the parentheses, you are saying, "Print this function." When you have them, you are saying, "Evaluate this function and print the result."
I've solved my issue by adding '()' after the anonymous function as shown below. http://jsfiddle.net/MZwBS/7/
var items = [];
items.push({
example: function() {
if(0 > 1) {
return 'true';
} else {
return 'false';
}
}()
});
document.write(items[0].example);
This code block now produces the expected result of
'false'

Try/catch oneliner available?

Just as you can convert the following:
var t;
if(foo == "bar") {
t = "a";
} else {
t = "b";
}
into:
t = foo == "bar" ? "a" : "b";
, I was wondering if there is a shorthand / oneline way to convert this:
var t;
try {
t = someFunc();
} catch(e) {
t = somethingElse;
}
Is there a method of doing this in a shorthand way, preferably an oneliner? I could, of course, just remove the newlines, but I rather mean something like the ? : thing for if.
Thanks.
You could use the following function and then use that to oneline your try/catch. It's use would be limited and makes the code harder to maintain so i'll never use it.
var v = tc(MyTryFunc, MyCatchFunc);
tc(function() { alert('try'); }, function(e) { alert('catch'); });
/// try/catch
function tc(tryFunc, catchFunc) {
var val;
try {
val = tryFunc();
}
catch (e) {
val = catchFunc(e);
}
return val;
}
No, there isn't a "one-liner" version of try-catch besides simply removing all the newlines.
Why would you want to? Vertical space doesn't cost you anything.
And even if you'll settle for removing all the newlines, this, in my opinion, is harder to read:
try{t = someFunc();}catch(e){t = somethingElse;}
than this:
try {
t = someFunc();
} catch(e) {
t = somethingElse;
}
What you have is perfectly fine. Readable code should be a priority. Even if it means more typing.
There is one liner available as npm package try-catch. You can use it this way:
const tryCatch = require('try-catch');
const {parse} = JSON;
const [error, result] = tryCatch(parse, 'hello');
There is similar approach for async-await try-to-catch:
const {readFile} = require('fs').promises;
read('./package.json').then(console.log);
async function read(path) {
const [error, data] = await tryToCatch(readFile, path, 'utf8');
return data || error.message;
}
All this wrappers do is wrap one function with try-catch block and uses destructuring to get result.
Also there is an idea to use something similar to Go style error handling:
// this is not real syntax
const [error, result] = try parse('hello');
You can get it down to two lines.
try { doSomething(); }
catch (e) { handleError(); }
Or, in your specific example, 3 lines.
var t;
try { t = doSomething(); }
catch (e) { t = doSomethingElse(); }
Either way, if your code allows for it, a two liner is much more concise, IMO, than the typical try/catch block.
While this doesn't help with your question about shorthand, it could help if you are seeking to get a try-catch working in an inline context which expects an expression (as distinct from statements, as try-catch uses).
You can achieve this by wrapping the try-catch into an IIFE, which, though an expression, lets you add statements within it that are immediately executed:
var t, somethingElse;
var failingCondition = false;
var result = failingCondition || (function () {
try {
t = someFunc();
} catch(e) {
t = somethingElse;
}
})();
The above is probably of little use but you could conditionally return values also:
var t, somethingElse;
var failingCondition = false;
var result = failingCondition || (function () {
try {
t = someFunc();
return 'someFunc';
} catch(e) {
t = somethingElse;
return 'somethingElse';
}
})();
Since someFunc() fails here (in our case, since it is not defined), result will equal "somethingElse".
Here it is using only js:
const result = (()=>{ try{ return fn(); } catch(e) { return "other"; } })();
const badFn = ()=>{ return JSON.parse("broken json"); }
const result = (()=>{ try{ return badFn(); } catch(e) { return "other"; } })();
console.log(result);

Categories