function MyFunction () {
if (SomeCondition) {
MyInnerFunction(SomeParam);
return;
}
if (SomeOtherCondition) {
MyInnerFunction(SomeOtherParam);
return;
}
if (SomeThirdCondition) {
MyInnerFunction(AnotherParam);
return;
}
function MyInnerFunction(Param) {
// Do some work here
// HERE: I want return from MyFunction
}
}
As you can see, when MyInnerFunction returns, the next statement to execute is the return statement of MyFunction. Is there a way to eliminate all these return statements so that the return from MyFunction executes inside MyInnerFunction?
Thanks.
you could reformat the code so that your if conditions are only modifying the parameters.
Then you just call your method with the correct parameters at the end
function MyFunction () {
var params;
if (SomeCondition)
params = SomeParam;
else if (SomeOtherCondition)
params = SomeOtherParam;
else if (SomeThirdCondition)
params = AnotherParam;
MyInnerFunction(params);
}
Related
I have been working to create a function that given another function will make that second function only callable once. not unlike the _.once() function.
the desired outcome is the following:
const oneTimeFunction = _.once(function(string) { string.split(''); })
oneTimeFunction('hello')
//returns: 'olleh', and if called again it would have no effect returning the same thing a the original call.
Currently this is what I have:
_.once = function (func) {
var called = 0;
let args = null;
if (arguments.length > 1) {
args = Array.prototype.slice.call(arguments,1);
}
return function () {
if (called === 0) {
console.log('being called');
called ++;
if (!args) {
console.log('without apply');
return func.call(arguments);
} else {
console.log('with apply');
return func.apply(this,args);
}
} else {
console.log('this has been called');
return null;
}
};
};
I am running into a wall as it is returning error type undefined even with everything I have tried. Any help, even to get to where it can call the function regardless of the one time only stipulation? Thanks!
create a variable that count how much this function is called
let count = 0;
function once(str) {
if(count < 1){
count++;
return str.split("").reverse().join("");
}
else return str;
}
console.log(once("hello")); // olleh
console.log(once("hello")); // hello
console.log(once("hello")); // hello
In reading your question, I'm seeing that you would like to always return the first value on subsequent calls:
"if called again it would have no effect returning the same thing a[s] the original call."
So I believe you want to do something like this:
function computeOnce(myFn) {
let origVal = undefined;
return function (...args) {
// if this is not set, this is the first call
if (!origVal) {
// execute the function and store it's return value
origVal = myFn(...args);
}
return origVal;
}
}
I presume it is possible to create a JavaScript function that disables it self after it is done running.
Is possible? How can this effect be achieved?
Wrap arbitrary runnable in following manner:
function once(subject) {
var first = true;
return function() {
if (first) {
first = false;
return subject();
} else {
return null;
}
};
}
var wrapper = once(function() {alert("No more!");});
wrapper(); // alerts
wrapper(); // noop
Runnable will only be executed on first invocation of wrapper.
You can convert a function of arbitrary arguments to an argumentless runnable.
If you want the functionality to be happen only once you can use the following function
function once(fn, context) {
var result;
return function() {
if(fn) {
result = fn.apply(context || this, arguments);
fn = null;
}
return result;
};
}
// Usage
var canOnlyFireOnce = once(function() {
console.log('Fired!');
});
canOnlyFireOnce(); // "Fired!"
canOnlyFireOnce(); // nada
Courtesy: https://davidwalsh.name/essential-javascript-functions
something like this?
function a(){ alert(1); a = null;}
invoke a() once, second time it will say
Uncaught TypeError: a is not a function
if the function is anonymous, then make it IIFE
(function(){ alert(1);})();
var _flag = true; // Have a flag variable.
function oneTimer(){
// Check flag is set to true or not
if(!_flag) return;
_flag = false;
// Your function definition here.
}
As commented, if you want to execute a function only once, you should try IIFE. These functions are invoked immediately and cannot be called afterwards.
Following is a sample code.
(function test() {
console.log("test");
(function innerFunc() {
console.log("Inner Function");
})();
try {
innerFunc();
} catch (ex) {
console.log(ex)
}
})();
try {
test();
} catch (ex) {
console.log(ex)
}
Pretty easy, just assign an empty function to the function:
function once() {
alert('once');
once = function () { };
}
once();
once();
I trying to create a function, that takes another function as the argument, and creates a new version of the callback function that can only be called once. Subsequent calls will return the output if the initial call.
This is along the lines of recreating the Underscore .once method.
Here is what I have thus far. I have created a chargeCreditCard function. I want to create a new version of this function that can only be called once (chargeOnce). Explanation is appreciated. Thanks.
Edit. I want the once function to not rely on any code outside of the function to work (ie. an external counter variable).
var chargeCreditCard = function(num, price){
return num*price;
};
function once (func) {
var hasActionBeenCalled = false;
var call = function () {
if(!hasActionBeenCalled) {
hasActionBeenCalled = true;
func;
}
}
}
var chargeOnce = once(chargeCreditCard);
console.log(chargeOnce(2,3));
console.log(chargeOnce(4,5));
Your function once does not return anything, and your function call does not call anything. Make it
function once(func) {
var hasActionBeenCalled = false;
return function() {
if (!hasActionBeenCalled) {
hasActionBeenCalled = true;
return func.apply(this, arguments);
}
}
}
For garbage collection, I'd recommend to do
function once(func) {
var res;
return function() {
if (typeof func == "function") {
res = func.apply(this, arguments);
func = null; // unset func
}
return res;
}
}
In my case I have one repository like this from temphire (breeze)
define(['durandal/system'], function (system) {
var Repository = (function () {
var repository = function (entityManagerProvider, entityTypeName, resourceName, fetchStrategy) {
.........
this.find = function (predicate) {
var query = breeze.EntityQuery
.from(resourceName)
.where(predicate);
return executeQuery(query);
};
function executeQuery(query) {
return entityManagerProvider.manager()
.executeQuery(query.using(fetchStrategy || breeze.FetchStrategy.FromServer))
.then(function (data) { return data.results; });
}
................
};
return repository;
})();
return {
create: create,
getCtor: Repository
};
function create(entityManagerProvider, entityTypeName, resourceName, fetchStrategy) {
return new Repository(entityManagerProvider, entityTypeName, resourceName, fetchStrategy);
}
});
NOW
HOW CAN DO LIKE SOME THIS
repository.query(predicate).execute();
function query(predicate) {
return query = breeze.EntityQuery
.from(resourceName)
.where(predicate);
};
function executeQuery(query) {
return entityManagerProvider.manager().executeQuery(query.using(fetchStrategy || breeze.FetchStrategy.FromServer)).then(function(data) {
return data.results;
});
}
function execute() -- >
return executeQuery
the first action return query and after to execute
many thanks
I think the problem with what you are trying is that return terminates execution. If you want to do something as well as return in that function, then you need to do it before you return.
If, on the other hand, you really need to return the value and then execute something, then you should have the method that calls the function expecting the return, call the function to get the return value, and then have that calling function execute the thing you want executed. If that execution needs some data from the function that returns the value, then return that information with the value returned, and pass it into the function that does the execution.
Use
executeQueryLocally // This is syn
instead of
executeQuery // This is async
executeQuery sync
How can I call the function only for once?
var myFunction = function () {
alert("calling function only for once");
}
myFunction();//alert "calling function only for once"
myFunction();//should not alert // if I call multiple times this should not be called
Try this:
var myFunction = function () {
alert("calling function only for once");
myFunction = function(){
return false;
}
}
myFunction();//alert "calling function only for once"
myFunction();//should not alert
Store some goobal variable a flag when run the function and check that variable at the start of the function.
set a flag, and call according to that flag:
var IsAlreadyCalled=false;
var myFunction = function () {
if(!IsAlreadyCalled){
alert("calling function only for once");
IsAlreadyCalled = true;
}
}
myFunction();//alert "calling function only for once"
myFunction();//should not alert
In your very odd scenario , the easiest way is to set a boolean:
var run = true,
myFunction = function(){
if(run){
alert('calling function only for once');
run = false;
} else {
return false;
}
};
myFunction(); // will run
myFunction(); // won't run
That way later on if you need to "reactivate" it you can just set the boolean back to true and call it again.
run = true;
myFunction(); // will run again
Other suggestions of using a flag are fine, but I would build it as a function decorator, that you can apply to any function. You avoid global variables this way, and your code becomes more readable and reusable:
// Takes a function and returns a function
// that executes only once
function once(f) {
var flag;
return function() {
if (!flag) {
flag = true;
return f.apply(this, arguments);
}
};
}
var fn = once(function() {
console.log('logged!');
});
fn(); // logged!
fn();
fn();
Demo: http://jsbin.com/povu/1/edit