i have a value like that
var myvalue = myfunction(1,2);
what I need is that
GETTING myfunction(a,b) as a string..
I mean not "myfunction's value"
hmmm, let me explain,
myfunction(1,2) returns 1+2=3
if I type
alert(myvalue)
it returns 3
but I need myfunction(a,b) AS IT'S TYPED when I use alert. NOT IT'S VALUE
think it like
var myvalue='myfunction(a,b)'
now, if i use Alert, it gives me myfunction(a,b)
how can I do that?
var myvalue = function()
{
myfunction(1,2);
};
myvalue is a anonymous function that calls myfunction with the specified parameters. You can call it, and if you print it for debugging, it will look something like:
function () {
myfunction(1, 2);
}
If you want to get the string value of a function, you can use the builtin toString method
var f1 = function(a, b) {
return a + b;
};
function f2(a, b) {
return a + b;
};
console.log(f1.toString());
console.log(f2.toString());
yields
function (a, b) {
return a + b;
}
function f2(a, b) {
return a + b;
}
But why do you want to do this?
Related
I have one simple object calculation function .I was pass the object resultant data in to another object function like the chain reaction
example like:
str.replace().replace().replace() They will pass the resultant data of first replace to 2nd replace like the chain reaction.
So i want to created the below code .But not working in my case .
See the below snippet
var m=function(data){
return {
str :data,
plus:function(b){
this.str = this.str+b;
return this.str;
},
min:function(a){
this.str = this.str-a
return this.str;
}
}
}
console.log(m(5).plus(1).min(3))
If 5 add with 1 is 6 .Then pass the 6 into min() function for reduce 3 .finally console.log result 3 .But It have some here .Please help to solve my problem.
Thanks
I suggest to use an object and return that object after a method call. For better use, you could implement toString and valueOf methods to use the return value directly.
What you need is to return the whole object, for all methods which a chainable.
var m = function(value){
var obj = {
value: value,
plus: function (b) {
obj.value += b;
return obj;
},
min: function(a) {
obj.value -= a;
return obj;
},
toString: function () { return obj.value; },
valueOf: function () { return obj.value; }
}
return obj;
}
console.log(m(5).plus(1).min(3).value);
alert(m(5).plus(1).min(3));
console.log(m(3).plus(7) - m(5).min(1));
var m=function(data){
return {
str :data,
plus:function(b){
this.str = this.str+b;
return this;
},
min:function(a){
this.str = this.str-a
return this;
}
}
}
console.log(m(5).plus(1).min(3).str)
For creating chain like method calls you need to return 'this' from the function after which you want to the chain to continue
Another closer way, we can return this separately, at initialisation, and every other method calls.
Doing it this way is a real chain, as this called in the plus and min function is the incoming object, it's not a recomposition.
We often see both styles.
function m(n) {
this.value = n.value
this.plus = (n) => {this.value = this.value + n.value; return this}
this.min = (n) => {this.value = this.value - n.value; return this}
return this // Only at initialisation
}
console.log(m({value: 5}).plus({value: 1}).min({value: 3}).value)
I understand wrapper would be something like
var str = 'Hello World'; // assigning string to a variable
console.log(str); // 'Hello World'
var str2 = new String('Hello World') // Creating a wrapper function
str2.valueOf() // 'Hello World'
By that logic, can the below example also be considered a wrapper function
function SuperOuterAdd(a, b){
console.log('Wrapper 2');
return OuterAdd(a, b);
}
function OuterAdd(a, b){
console.log('Wrapper 1');
return add(a, b);
}
function add(a, b){
return parseInt(a) + parseInt(b);
}
There's no language definition of wrapper function in JavaScript, and from your code, new String('Hello World'), is an instantiation of a string object - I don't see how that would be considered a wrapper function by any logic at all.
A wrapper function is a design concept where a very minimal function is using another function to do it's "work" for it, sometimes using a slightly different set of arguments.
for example:
function power(x, y) {
var res = 1;
while(y--) {
res *= x;
}
return res;
}
function square(x) {
return power(x, 2);
}
In the code above square is a wrapper function.
Wrappers are a loose term for a function that simply returns a value, with no computation. They are useful when we need a value, but not right away. Maybe the result is not ready yet when you define it, or you need some binding for the function to work (use of this).
Neither of the examples you provided is a wrapper function. The first one is simply an object instantiation (you're not even creating a function). It just so happens that the String constructor can take a string literal as an argument, which means it can work like the identity function. In the second, it's just some more elaborate contraption, but it's still function calling and computing things.
In general, wrapper functions are pretty useless out of context, and they're mostly a Javascript-specific thing, but consider the following:
let foo = null;
fetch('/my/api/call').then(function(res) {
foo = res;
getFoo(); // => [your object]
});
getFoo(); // => null
function getFoo() {
return foo;
}
Here is the example:
function SimpleWrapper() {
var self = this;
initialize();
function initialize() {
self.SuperOuterAdd = SuperOuterAdd;
self.OuterAdd = OuterAdd;
}
function SuperOuterAdd(a, b){
console.log('Wrapper 2');
return OuterAdd(a, b);
}
function OuterAdd(a, b){
console.log('Wrapper 1');
return _add(a, b);
}
function _add(a, b){
return parseInt(a) + parseInt(b);
}
}
Given the following piece of code:
function Foo() {};
Foo.prototype.one = fluent(function(a , b) {
return a + b;
});
Foo.prototype.two = fluent(function(c) {
var d = c + 0.15; //0.15 cause I just couldnt thougth anything else at this moment...
return d;
});
ok that's all good for the moment, now let's say fluent is a decorator function that allows me to implement it like this:
var test = new Foo();
test.one(10, 5).two(); //here is the problem...
Thinking as it was a promise, how can I modify this code in order to make the returned valued of one available on two??? meaning, c should be the returned valued of one(), while keeping the sample implementation.
Here is the fiddle;
I would propose the following definition of fluent. Note that if needed, the final return value is in this.$lastReturn:
function fluent(impl) {
return function() {
// Convert arguments to a real array
var args = Array.prototype.slice.call(arguments);
// Prepend the last return value for this object
if(typeof this.$lastReturn != 'undefined')
args.unshift(this.$lastReturn);
// Invoke the function and save the return value
this.$lastReturn = impl.apply(this, args);
// Return this to allow chaining of the next fluent call
return this;
}
}
This solution utilised the answer of Dark Falcon and makes a little extent to the feature of returning a value or the chain.
Javascript offers the possibillity to request a primitive value of the object, Object.prototype.valueOf()
. In this case it may be used to get a value in case we need a value and on other cases, there is the object returned.
For more information have a look to this article Object-to-Primitive Conversions in JavaScript.
Another addition is argument control at fluent and the call of the methods. If arguments are given, then the arguments are taken, if not given, then the this.$lastreturn is used.
function fluent(impl) {
return function () {
var args = Array.prototype.slice.call(arguments);
// Prepend the last return value for this object only if arg length is 0
if (!args.length && typeof this.$lastReturn !== 'undefined') {
args.unshift(this.$lastReturn);
}
this.$lastReturn = impl.apply(this, args);
return this;
}
}
function Foo() { };
Foo.prototype.one = fluent(function (a, b) {
return a + b;
});
Foo.prototype.two = fluent( function (c) {
return c + 0.77;
});
// this returns the primitive value
Foo.prototype.valueOf = function (c) {
return this.$lastReturn;
};
var test = new Foo();
var x = test.one(10, 5);
document.write(x + '<br>'); // 15
document.write(typeof x + '<br>'); // object
var y = x.two();
document.write(y + '<br>'); // 15.77
document.write(typeof y + '<br>'); // object
var z = y.two(35);
document.write(z + '<br>'); // 35.77
document.write(typeof z + '<br>'); // object
Hi I'm trying to run the following function:
function add (a, b) {
return a + b;
}
var make_lazy = function (add, a, b) {
return function () {
add(a,b);
}
}
Basically what I'm trying to do is to pass another function as an argument and its parameters to the make_lazy function - and then run the function that was passed in as the argument along with the other two parameters. I get undefined is not function as an error when I try to run the code.
You forgot the return statement in the anonymous function that you're returning from make_lazy:
var make_lazy = function (add, a, b) {
return function () {
return add(a,b) // <----- here
}
}
I think you are trying for something like this.
function add (a, b) {
return a + b;
}
var make_lazy = function (a, b) {
return function () {
return add(a,b);
}
}
Then you can call var lazy = make_lazy(3,5); and later call lazy() to get 8
Wrap you lazy function body inside a self calling function and return.
function add (a, b) {
return a + b;
}
var make_lazy = function (add, a, b) {
return (function () {
add(a,b);
})();
}
Here's my point of view.
When you assign a function to make_lazy variable, after that you should make an invocation make_lazy() with the same params as they were in the definition of that function:
make_lazy(function expression, a, b);
This portion:
function (add, a, b)
just makes add a local variable, this is not the same as add(a,b) which is defined above.
To make the code work, try to invoke make_lazy as
make_lazy(add, 3, 4)
Is there a technique where I can execute code after a return?
I want to return a value then reset the value without introducing a temporary variable.
My current code is:
var foo = (function(){
var b;
return {
bar: function(a) {
if(b){
var temp = b;
b = false;
return temp;
}else{
b = a;
return false;
};
}
};
})();
foo.bar(1);
I want to avoid the temp var. Is that possible?
var b holds a value between function calls because it is a memoization styled function.
Use a finally block to ensure certain code runs after another block. That block can include errors, returns, or whatever else. The finally block will run after.
try {
return 'something';
} finally {
// your after return code
}
In Javascript, is there a technique where I can execute code after a return?
Absolutely. It's called setTimeout(), but somehow I doubt that it would be a good solution for you.
Here it is anyway:
var foo = (function(){
var b;
return {
bar: function(a) {
if(b){
setTimeout(function() {b = false;},20);
return b;
}else{
b = a;
return false;
};
}
};
})();
foo.bar(1);
The function you passed as the first argument to setTimeout will "close around" the b variable, and set it after 20 milliseconds.
If you want to retain the synchronous flow of code execution, then absolutely not, unless you do it manually via a function that is returned along with the desired value.
Ultimately, your best bet will be the temp variable. You can close around it like the b variable if you wish:
var foo = (function(){
var b,temp;
return {
bar: function(a) {
if(b){
temp = b;
b = false;
return temp;
}else{
b = a;
return false;
};
}
};
})();
foo.bar(1);
it doesn't really matter what you set b to because you're declaring it with the var inside the function. It does not exist outside the function.
You really need to show your complete code here. In your example, b is always undefined, therefore the conditional would always enter the else case and secondly, since we got a lexical function scope in Javascript, b would always lose its value when the function ends.
So I guess you're taking advantage of closures to hold a reference to that variable. But its impossible to answer without seeing your actual code.
I don't understand anything about this code... but here you can do this :
function(a) {
var b;
// I suppose b is defined here ?
if(b)
{
b = false;
return !b;
} else {
b = a;
return false;
};
};
I think that this is not possible (or I don't know how to do it). I'll try to create a function that do whatever you want (i.e. reset variables) and then use return reset_variables();
The function 'reset_variables' also return the value what you want.
I don't think I would ever use something like this, but you could write a function for it:
var foobar = function(value, callback) {
callback();
return value;
};
Then it would be used like this in your code:
function(a) {
var b;
if (b) {
// The first argument is what you want returned.
// The second argument is a function that you want executed "after" you've calculated the return value
return foobar(b, function() {
b = false;
});
} else {
b = a;
return false;
};
};
I called it foobar because I simply can't think of a name for this concept :)
Obviously the code does not actually execute after the actual return (that would be impossible) but it does capture the value of your return value before the final function is executed, which results in something that looks like what you're after.
But, once again, I'm not really sure if I'd advice to use something like this :)
You can use:
Promise.resolve().then(() => console.log('your action'));
This is similar than using process.nextTick