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
}
}
Related
I have a js file with many functions
function one(){
//do stuff
}
function two(){
//do stuff
}
function execute_top_one(){
//do stuff
}
function execute_top_two(){
//do stuff
}
and I need to create a function that executes, for example, all functions that start with (or contain) "execute_top" in the function name, instead of having to call all the functions manually like this
execute_top_one();
execute_top_two();
Any suggestion?
I would suggest that you do it in a little other way:
const functionStore = {
one: function() {
console.log('one')
},
two: function() {
console.log('two')
},
execute_top_one: function() {
console.log('execute_top_one')
},
execute_top_two: function() {
console.log('execute_top_two')
},
}
const execute_these = "execute_top"
const executeFunctions = (functionStore, filterString) => {
Object.entries(functionStore).forEach(([fnName, fn]) => {
if (fnName.indexOf(filterString) !== -1) {
fn()
}
})
}
executeFunctions(functionStore, execute_these)
The difference is that you gather your functions into one object (I called it functionStore, and then create the filtering string & function. As you see from the snippet, filtering an object's keys and values (called fnName & fn in my snippet) is quite easy - and inside the filtering you can call the functions stored.
I'm relatively new to coding in JavaScript, and I've came across a problem. I like to nest functions to keep things orderly, but how would I exit from a parent function from inside a child function?
example:
function foo1() {
function foo2() {
//return foo1() and foo2()?
}
foo2();
}
See update under the fold
You can't. You can only return from the child function, and then return from the parent function.
I should note that in your example, nothing ever calls foo2 (As of your edit, something does). Let's look at a more real example (and one that comes up a lot): Let's say we want know if an array contains an entry matching some criterion. A first stab might be:
function doesArrayContainEntry(someArray) {
someArray.forEach(function(entry) {
if (entryMatchesCondition(entry)) {
return true; // Yes it does <-- This is wrong
}
});
return false; // No it doesn't
}
You can't directly do that. Instead, you have to return from your anonymous iterator function in a way to stop the forEach loop. Since forEach doesn't offer a way to do that, you use some, which does:
function doesArrayContainEntry(someArray) {
return someArray.some(function(entry) {
if (entryMatchesCondition(entry)) {
return true; // Yes it does
}
});
}
some returns true (and stops looping) if any call to the iterator function returns true; it returns false if no call to the iterator returned true.
Again, that's just one common example.
You've referred to setInterval below, which tells me that you're almost certainly doing this in a browser environment.
If so, your play function almost certainly has already returned by the time you want to do what you're talking about, assuming the game has any interaction with the user other than alert and confirm. This is because of the asynchronous nature of the environment.
For example:
function play() {
var health = 100;
function handleEvent() {
// Handle the event, impacting health
if (health < 0 {
// Here's where you probably wanted to call die()
}
}
hookUpSomeEvent(handleEvent);
}
The thing is, that play will run and return almost immediately. Then the browser waits for the event you hooked up to occur, and if it does, it triggers the code in handleEvent. But play has long-since returned.
Make a note whether the parent function should also return.
function foo1() {
bool shouldReturn = false;
function foo2() {
shouldReturn = true; // put some logic here to tell if foo1() should also return
return;
}
if (shouldReturn) {
return;
} else {
// continue
}
}
It only says that you can't return the parent function in the child function, but we can do a callback and make it happen.
function foo1(cb = () => null) {
function foo2() {
cb();
}
foo2();
}
foo1(() => {
// do something
});
We can use Promises for this:
const fun1 = async () => {
const shouldReturn = await new Promise((resolve, reject) => {
// in-game logic...
resolve(true)
})
if(shouldReturn) return;
}
if you wanna return from the parent function, then just resolve with true
Based on your comment, something like this might work as a main game loop.
function play() {
var stillPlaying = true;
while(stillPlaying) {
... play game ...
stillPlaying = false; // set this when some condition has determined you are done
}
}
Little confusing. From within function evenCard I'd like to call function autoFlip and pass it function evenBack as an argument. Then to complicate things further, autoFlip needs to pass the argument to another function nested within it and then call function evenBack. Is this possible? Thanks!
function evenCard() {
autoFlip_toggle = true;
autoFlip(evenBack);
}
function autoFlip(back) {
// do other stuff
$(window).scroll(function() {
if (autoFlip_toggle == true) {
// Call evenBack somehow?
}
});
}
function evenBack() {
// Does stuff
}
Call back(); within autoFlip.
function autoFlip(back) {
// do other stuff
$(window).scroll(function() {
if (autoFlip_toggle == true) {
back();
}
});
}
To call evenBack from the scroll function just write evenBack();
I would like to have a function that checks if a condition is true run before a specific function is called. My goal is to have one line of code (the function being called) in another function. This function should run before any other code is executed. Here is some pseudocode to demonstrate what I mean:
function checkFunction(){
//checks if a condition is true if so end function, else continue function
}
function aFunction(){
checkFunction();
//some code
}
I know I can make a conditional statement that contains a return, but I would like to keep it this short if possible.
Thank you guys for your time.
There's nothing designed specifically for what you want, and its verging on bad practice anyway. But you could get it pretty succinct by just writing something like:
function aFunction()
{
if (!checkFunction()) return;
//some code
}
You might want an assert-like function, but then the other way round:
function stopIfTrue(x) {
if(x === true) throw "stop function"; // can be any string
}
and then:
function aFunction(){
stopIfTrue(something); // if 'something' is true an error will be thrown; function will exit
//some code
}
I would simply do this:
function checkFunction(){
return (condition);
}
function aFunction(){
if(!checkFunction()) return;
//some code
}
If what you're trying to do is this:
function aFunction()
{
if(checkFunction())
{
return;
}
//somecode
}
without using a return in aFunction(), you could do this:
function aFunction()
{
if(!checkFunction())
{
//somecode
}
}
A trick you can do is dynamically change the other function. So
function make_wrapped(before, after){
return function(){
if(before()) return;
after.apply(this, arguments);
}
}
//set aFunction to be the new function
aFunction = make_wrapped(checkFunction, aFunction);
edit: I misread the question. This is probably way more complicated than you need.
I have a requirement where I get the anchor tags id and based on the id I determine which function to execute.. so is there anything that suites below code
function treeItemClickHandler(id)
{
a=findDisplay(id);
a();
}
You can assign a function to a variable like so:
You can also return a function pointer from a function - see the return statement of findDisplay(id).
function treeItemClickHandler(id)
{
var a= findDisplay;
var other = a(id);
other();
}
function findDisplay(id)
{
return someOtherThing;
}
function someOtherThing()
{
}
Sure, functions are first class objects in JavaScript. For example, you can create a map (an object) which holds references to the functions you want to call:
var funcs = {
'id1': function(){...},
'id2': function(){...},
...
};
function treeItemClickHandler(id) {
if(id in funcs) {
funcs[id]();
}
}
As functions are treated as any other value, you can also return them from another function:
function findDisplay(id) {
// whatever logic here
var func = function() {};
return func;
}
functions are normal javascript values, so you can pass them around, (re)assign them to variables and use them as parameter values or return values for functions. Just use them ;) Your code is correct so far.
You can map between ids and functions to call in a number of ways.
One of the simpler ones is to create an object mapping ids to functions, and find the function to call from that object (this is in essence a nicer-looking switch statement).
Example:
function treeItemClickHandler(id)
{
var idMap = {
"some-id": findDisplay,
"another-id": doSomethingElse
};
if (!idMap.hasOwnProperty(id)) {
alert("Unknown id -- how to handle it?");
return;
}
// Call the corresponding function, passing the id
// This is necessary if multiple ids get handled by the same func
(idMap[id])(id);
}
function findDisplay(id)
{
// ...
}
function doSomethingElse(id)
{
// ...
}