What you are looking for is something called "chainable functions".
Example 1
Consider the example below:
var array = [1, 2, 3];
var index = array.filter(cut).indexOf(3);
console.log(index);
function cut(n){
return n > 1;
}
The variable index
returns the result of the function array.filter(...).indexOf(...)
.
But how does it work? Let's break it down.
1. Initializing an array
var array = [1, 2, 3];
// A variable `array`is created with the value of an array `[1, 2, 3]`.
2. Using Array
method filter
array.filter(cut)
// This function returns an array of value [2, 3];
3. Chaining Array
method indexOf
to filter
array.filter(cut).indexOf(3);
// equals to [2, 3].indexOf(3)
// returns the value 1.
So why can we chain the function indexOf
to filter
?
Because array.filter()
returns an array, and indexOf
and filter
are methods that are under the same prototype from Array
constructor.
Example 2
Similarly, this example using String
constructor will work:
var string = 'This is a string';
var newString = string.substring(0, 4).toUpperCase();
console.log(newString);
Because string.substring(...)
returns a string and toUpperCase()
is a method from String
constructor.
Example 3
This is a little bit trickier.
var string = 'This is a string';
var newString = string.split(' ').indexOf('is');
console.log(newString);
Now, split()
is a String
method but indexOf()
is an Array
method. Then why does this work?
Because split()
method returns an array value. So, you need a method from Array
constructor to chain it.
How to create a chainable function?
You can create your own constructor function with its own prototype.
var a = undefined;
// The constructor
var Example = function(string){
this.value = string;
}
// The prototypes
Example.prototype.addString = function(string){
this.value += ' ' + string;
return this;
};
Example.prototype.becomeArray = function(){
return this.value.split(' ');
};
// Creating an instance of the constructor
a = new Example('This is a');
console.log(a.constructor === Example);
// Chaining methods from its prototype
a = new Example('This is a').addString('string').becomeArray();
console.log(a);
Of course this is an oversimplified example. And there is many other ways to achieve the result.
But then that is out of scope of this question.