How can I Create a Function for Infinite Calls in JavaScript - javascript

I am trying to write a function in JavaScript where there will be an infinite call to greet(). The expected outcome is to have the greetings concatenated with each call.
console.log(greet('hello').greet('world').greet())
the output of the above should give Hello world
and there might be infinite greet('string')
My initial implementation looked like this:
let greet = function (a) {
return function (a) {
return function (c){
return c ? (b + " " + c ) : (a + " " + b);
}
}
};
However, the output is not as expected. I am facing some issues in the implementation and would like some help in resolving them. Can someone help me fix this issue? Thank you in advance."

Basically, have a function that returns an object with a function inside which in turn invokes the global function that returns an object... etc
let greet = a => ({
greet: b => b ? greet(a + ' ' + b) : a
})
console.log(greet('hello').greet('world').greet())

You are probably looking for fluent chaining in JavaScript. You can achieve this approach by creating your own custom class and keep returning this:
class Greeter {
content = '';
greet(string) {
this.content += (this.content.length ? ' ' : '') + string;
return this;
}
toString() {
return this.content;
}
}
const greeter = new Greeter();
const output = greeter
.greet('I')
.greet('can')
.greet('do')
.greet('this')
.greet('forever')
.toString();
console.log(output);
You can check other possibilities by searching it. For example on Stackoverflow are similliar questions.

The issue in your code is that you are using the variable b inside the innermost function, but it's not defined in the scope of that function. Also, you are declaring a function with the same name a in the inner function, which shadows the outer a parameter.
Here's a corrected version of the code:
let greet = function (a) {
let b = a;
return function (c) {
if (c) {
b = b + " " + c;
}
return {
greet: function (d) {
return greet(b + (d ? " " + d : ""));
}
};
};
};
With this code, you can call greet multiple times and concatenate the greetings with each call. For example:
console.log(greet('hello').greet('world').greet());
// Output: "Hello world"

Thank you all for responding to my issue.
i also came up through some implementation with traditional function expressions
here is my solution
let greet = function (a) {
return {
greet: function (b) {
return b ? greet(a + " " + b) : a;
}
}
};

Related

where do the arguments go in this function?

I'm working through and trying to understand the source code of https://trianglify.io/ which can be found at https://github.com/qrohlf/trianglify. In the lib/trianglify.js file, I come across the following lines of code:
var x_color = chroma.scale(opts.x_colors).mode(opts.color_space);
var y_color = chroma.scale(opts.y_colors).mode(opts.color_space);
gradient = function(x, y) {
return chroma.interpolate(x_color(x), y_color(y), 0.5, opts.color_space);
};
My question is when the x_color(x) gets called, where does the "x" argument go? How does this argument get passed into the function if it doesn't appear in the definition? My main purpose for doing this is to add some extra custom parameters to x_color() but I can't do that if I have no idea how the parameters even get processed in the function.
EDIT
The .mode(opts.color_space) function can be found at https://github.com/gka/chroma.js/blob/master/src/scale.coffee line 158. It reads as follows:
f.mode = (_m) ->
if not arguments.length
return _mode
_mode = _m
resetCache()
f
not sure what to make of this since my coffeescript knowledge is limited.
chroma is part of chroma.js.
Looking at the code, chroma.scale(...) constructs a function with prototypes with fluent methods.
f = function(v) {
var c;
c = chroma(getColor(v));
if (_out && c[_out]) {
return c[_out]();
} else {
return c;
}
};
f.mode = function(_m) {
if (!arguments.length) {
return _mode;
}
_mode = _m;
resetCache();
return f;
};
So when you call chroma.scale(...) it returns f, and then when you call .mode(...) on the returned object, it again returns the same instance f.
The instance of f is created by the following method:
chroma = function() {
if (arguments[0] instanceof Color) {
return arguments[0];
}
return (function(func, args, ctor) {
ctor.prototype = func.prototype;
var child = new ctor, result = func.apply(child, args);
return Object(result) === result ? result : child;
})(Color, arguments, function(){});
};
As you can see, this makes use of the arguments object. Mozilla defines the arguments object as:
The arguments object is an Array-like object corresponding to the arguments passed to a function.
In short, even if you do not specify parameter names in the function signature, the arguments object will still exist, and any parameters you pass will exist in the arguments array.
I've created an example of using the arguments array here
function a() {
alert(arguments[0] + ' is ' + arguments[1] + ' years old.');
}
function b(name) {
return function test() {
alert(name + ' will vw ' + arguments[0] + ' years old on his next birthday.');
}
}
a('John', 29);
var example2 = b('John');
example2(30);
In the first example, there is a straight function call, but in the second example I am returning an actual function from the b() method, and then I'm calling that returned function.

Will it be any difference whether I declare f as global variable or local variable in Javascript?

function functionFunction(str) {
var f;
return f=function(obj){
return str+', '+obj;
}
}
functionFunction('Hello')('world')
Here is my code. The function functionFunction will return function f. When I declared variable f in the function functionFunction, the output is" Hello, World". When I declared the variable outside the function functionFunction, the output is the same.(Code as below). But I know in Javascript the global and local variable works on different scope. However, in this case, whether the variable f is global or is local, has no effect on the result. I wonder why
var f;
function functionFunction(str) {
return f=function(obj){
return str+', '+obj;
}
}
functionFunction('Hello')('world')
TL;DR: No, there is no functional difference.
When doing return f= function() you get a reference to the function and also set the variable f even though f is never actually used anywhere. Your code would work equally well without the variable as is not being used.
function functionFunction(str) {
return function(obj) {
return str + ', ' + obj;
}
}
let s = functionFunction('Hello')('world');
console.log(s);
You could also use ES6 syntax to do this too
const functionFunction = str => {
return obj => str + ', ' + obj
}
let s = functionFunction('Hello')('world');
console.log(s);

passing a returned value to another function, javascript

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

Why should I assign a function to a variable in javascript? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}
What is the difference between a function expression vs declaration in Javascript?
I am attempting to understand the "best practices" of javascript.
This code is from jqfundementals.com
// create a function that will greet a person,
// and assign the function to the `greet` variable
var greet = function( person, message ) {
var greeting = 'Hello, ' + person + '!';
log( greeting + ' ' + message );
};
greet( 'Jory', 'Welcome to JavaScript' );
greet( 'Rebecca', 'Thanks for joining us' );
Why should I assign the function to the greet variable?
My first impulse would be to write it like this:
function greet ( person, message ) {
var greeting = 'Hello, ' + person + '!';
log( greeting + ' ' + message );
};
What are the differences between these two implementations?
There aren't any differences between those snippets, except hoisting which allows you to call the former function in the lines before the definition. But this is just a simplistic example to get you warmed up. In reality, people don't assign these functions to variables but pass them directly to other functions. Or they otherwise use them in expression contexts. Or they dynamically decide which function to to store. Or anything else really.
There is no real difference but the var form enables you to declare-before-use incase you have recursive functions.
Simple example:
var func1, func2;
func1 = function (count) {
count = count - 2;
if (count > 0) {
func2(count);
}
}
func2 = function (count) {
func1(count + 1);
}
func1(10);
Although
function func1 (count) {
count = count - 2;
if (count > 0) {
func2(count);
}
}
function func2 (count) {
func1(count + 1);
}
func1(10);
is perfectly acceptable too. The interpreter will replace it with the former because of variable hoisting.

how to get a value which points to a function

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?

Categories