What do you call this programming pattern? [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm trying to figure out how to do this in JavaScript and can't seem to find the right words to Google for it. It's a fairly common pattern.
someOperation(obj) { resultOfSomeOperation ->
anotherOperation(resultOfSomeOperation)
}
Presumably someOperation is a method that takes as arguments an obj, and a function with signature result -> ??. What do you call this?

I believe the pattern you're pointing to is the "Callback" pattern, or more generally "Higher Order Functions", in which a function takes in a function as a parameter, and then uses the passed in function in some way. Some examples would be Each, Map, Reduce, etc... These often use lambda functions.
Here's some information on these topics: Callbacks on Wikipedia, JavascriptIsSexy Callbacks, Eloquent Javascript Chapter 5.
I'm leaning on Javascript examples, because that's the tag you used. Feel free to ask me clarifying questions and I can explain them further.
Here's an example:
var exampleArray = [1, 2, 3, 4, 5];
exampleArray.map(function(num){
return num * 2
});
// Returns [2, 4, 6, 8, 10];
As you can see, map makes use of the anonymous function that was passed in. Map applies the given function to each element of the array, and returns those outputs to a new array. This could also be done by defining the function ahead of time, and passing it in by name.
var exampleArray = [1, 2, 3, 4, 5];
var doubleValue = function(num) {
return num * 2;
};
exampleArray.map(doubleValue);
// Returns [2, 4, 6, 8, 10];

Related

Javascript is it bad practice to return an object that is passed by reference [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 11 months ago.
Improve this question
Let's say I have this function in JavaScript:
function foo(a) {
a.item = "four"
return a
}
b = {
item: "three"
}
b = foo(b)
console.log(b)
Since JavaScript is a call-by-sharing language there is no need to return a, the object b would have the same final value with the below code:
function foo(a) {
a.item = "four"
return a
}
b = {
item: "three"
}
foo(b)
console.log(b)
Is it bad practice to use return b for better readability even though it is not needed
Are there any downsides to returning the object?
You're correct, in your example the return statement is unnecessary, strictly speaking. Also, just as a point of clarification, while JS passes objects by reference, primitive types are passed by value.
However, it is considered a JS best practice to avoid mutating function parameters. It can very quickly get very confusing when you have many functions performing actions on the same object that is getting passed around and mutated. So, in fact, I would consider it a bad practice to write a mutating function that does not involve returning a value.
Following that idea, your example would look like:
function foo(a) {
// Copy our input (assuming 'a' only contains primitive values)
const output = { ...a };
output.item = 'four';
return output;
}
const b = { item: 'three' };
const c = foo(b);
// b is unchanged
The built-in Array.prototype.sort() method returns the array even though it's sorting it in place.
Whether this provides better readability is a matter of personal preference. But it can make it easier to work with arrays/objects that are created on the fly, e.g.
sorted_words = string.split(" ").sort();
If it didn't return the array, you'd have to do this in two steps:
sorted_words = string.split(" ")
sorted_words.sort();

Understanding this JS syntax [duplicate]

This question already has answers here:
How do JavaScript closures work?
(86 answers)
Higher-order functions in Javascript
(5 answers)
Understanding Higher Order functions in Javascript
(2 answers)
Closed 3 years ago.
I am practising ES6 and I have this code:
const over = (...fns) => (...args) =>
fns.map(fn => fn.apply(null, args));
const minMax = over(Math.min, Math.max);
console.log(minMax(1, 2, 3, 4, 5));
console.log(minMax(1, 2, 5, 4, 3));
console.log(minMax(1, 2, 5, -4, 3));
The goal is to get the minimum and the maximun values between the numbers passed as arguments.
I could understand almost everything, the dynamic is very clear, with one exception, I know that args refers to the parameters coming from minMax(), but I couldn't get how the code recognize it.
My guess is: since we have two functions, over() and minMax(), when called, they are automatically read in this order, that is why the code knows that the first anonymous function refers to over() and the second one to minMax(). But this is just a guess, I don't know if I am right.
What is exactly happening here?

Set an array as parameter in javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to parse an array from one function ton another.
I have seen in other posts that ".apply" can be used as in this example:
var x = [ 'p0', 'p1', 'p2' ];
call_me.apply(this, x);
But in my code I want to parse to other function not just one array, I want to parse the array and two strings more. So mi code looks more like:
var array = [1, 2, 3];
var string = "something":
var string1 = "something":
ShowM(array, string, string2);
function ShowM(array, string1, string2) {
alert(array[1] + string1 + string2);
}
Is there any way to do that without changing the original location of the elements of the arrays for not getting undefined?. Thnks
If the question is purely about how do you set an array as a parameter in Javascript as your topic question states, you just do like any other variable.
var array = [a,b,c];
var str = "hello";
var str2 = "something";
function foo(x,y,z) {
// do stuff...
}
foo(array, str, str2); //executes function with the 3 parameters
If you just want to pass the array into a function, you can pass it as you would any other variable:
function showM(a, b, c) {
// empty function definition
}
var x = [ 'p0', 'p1', 'p2' ];
showM(x, "some string", "another string");
All arrays are passed by reference in javascript, so when you alter a passed array's contents within the function, the contents will change across all scopes. And duck-typing means that you can use any variable type as an argument.
The apply function, on the other hand, calls a function with a given content and an array of arguments (which it expands, like with the ES6 spread operator):
// equivalent to the other call, except "this" is bound to null
showM.apply(null, [x, "some string", "another string"]);

How might the syntax `foo(a)(b)` be useful? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Today I have found a strange way of adding 2 numbers in javascript:
Basically the call of the method looks this way: add(5)(6) and the declaration of the method is:
function add(x) {
return function(y) { return x + y; };
}
Ok, I got it. The add function does not return a number, but returns the anonymous function which adds the first number with the second. But what is the point (how it can be helpful)?
Where exactly can it be useful apart from puzzling other people or writing some sort of obfuscated malware?
Obviously, the call add(5)(6) is not too useful - you'd rather write 5 + 6, or, if it's really a function, add(5, 6).
The great benefit is in functional programming where you are supposed to pass a function around (callback!) - most prominent in the array utils. For example:
[1, 2, 3].map(add(5)) // [6, 7, 8]
You can also use this for the composition of quite complex functions, without having to deal with function expressions. If we didn't have this curried add function, in the above example we would have needed to write
[1, 2, 3].map(function(y) {
return 5 + y;
}) // [6, 7, 8]
…and that every time for each different x.
Lets have a look at a function which is bit more common in the wild, pluck:
function pluck(prop) {
return function(obj) {
return obj[prop];
}
}
This function accepts a property name and returns a new function which, given an object, returns the property of that object.
This is useful for mapping an array of objects to an array of a specific property of those objects:
var names = people.map(pluck('name'));
Now, if you just have to do this a single time, there is no need to create a dedicated pluck function. However, if you do this multiple times, it avoids code repetition.
You wouldn't necessarily use it as you've described, but perhaps if you want to pass around a function that "adds 5 to the result", you could do
var addsFive = add(5);
// some other code, perhaps passing this var to another function
var result = addsFive(6); // returns 11
This technique of "partial" function invocation is called currying - this other SO question goes into some details on how/where it can be useful, as well as provides several links to help explain the concept.

Store objects in arrays and call their methods in Javascript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I would like to have a Javascript object obj that contains an array of other objects and is able to call their methods. I would also want any object to be able to register into the array by calling a special function of the object obj and pass a reference of itself as an argument.
Would anybody be so kind and help me with that, please? I've been having a hard time with it.
Also I thought of a simple solution where the object obj creates all the other objects but that doesn't seem to work as well...
Perhaps you mean something like this
function Invoker(arr) {
arr = arr.slice();
arr.invoke = function (methodName) {
var args = Array.prototype.slice.call(arguments, 1),
i;
for (i = 0; i < this.length; ++i)
if (methodName in this[i])
this[i][methodName].apply(this[i], args);
};
return arr;
}
var arr = [
{foo: function (a, b) {console.log('foo', a);}},
{foo: function (a, b) {console.log('bar', b);}}
];
var invkr = Invoker(arr);
invkr.invoke('foo', 'hello', 'world');
/*
foo hello
bar world
*/

Categories

Resources