ES6/8 syntax - arrow functions - ecmascript-6

The two of the following result in different things although they look like the same thing.
1
const addBlogPost = dispatch => {
return () => {
dispatch({type: 'add_blogpost'});
}
};
2
const addBlogPost = dispatch => dispatch({type: 'add_blogpost'});
Could anyone point out how are they different?

You can use this site to compile es6 arrow functions to vanilla JS to easily see the difference.
The first one compiles to this
var addBlogPost = function addBlogPost(dispatch) {
return function () {
dispatch({
type: 'add_blogpost'
});
};
};
While the second compiles to this
var addBlogPost = function addBlogPost(dispatch) {
return dispatch({
type: 'add_blogpost'
});
};
The first returns a function that has a dispatch while the second one returns a dispatch directly.

The result will always be the same as both functions are retuning the same thing.
The only difference is:
In the first function, you're returning a function which returns an object that returns dispatch function.
In the second function, you're returning your dispatch function directly.

Related

React Native run function any outher screen

I have a simple question.
I want to run the function I created in App.js in a different screen.
Each screen is connected to an AppContainer in context.
I'm going to use state on another screen, but I do not know how to do it.
Can you give me a simple example?
_setDefaultLocation = locationKey => {
console.log("call _setDefaultLocation function");
this.setState({ defaultLocation: locationKey });
console.log(this.state.defaultLocation);
this._getCurrent(locationKey);
};
The above function is called this.props._setDefaultLocation (); I tried to do this and it did not work.
import React from "react";
const WeatherContext = React.createContext();
function withWeather(WrappedComponent) {
return function withContext(props) {
return (
<WeatherContext.Consumer>
{value => <WrappedComponent value={value} {...props} />}
</WeatherContext.Consumer>
);
};
}
export { WeatherContext, withWeather };
Context is used to make it like that.
You can use global keyword to make your function global. Then you can use it in any screen.
For example, assume that you have a function is called 'myFunction'. You can implement your function in App.js as following.
global.myFunction = () => {
console.warn('I am a global function...')
// your function body
};
Then you can call this function in any screen just like other function calling..
In your case your function can implement in this format.
global._myFunction = locationKey => {
console.warn('I am a global function...')
// your function body
};
And when you are calling the function call it as _myFunction(locationKey).
NOTE: 'locationKey' is the parameter that you should pass for your function.
Think this solution will help you.

Conditional gulp task inside gulp.paralell() or gulp.series()

Too much information about conditions tasks inside pipes (e. g. "gulp-if" plugin). However, actually it is not "conditional tasks": it is the "conditional plugin usage", and one task can use multiple plugins. Here is how to conditionally run task NOT inside pipe (for example, inside gulp.paralell())
Suppose that task name can contain spaces for providing easy-to-understand task meaning.
gulp.task('Build', gulp.paralell(
'Preprocess HTML',
'Prepeocess styles',
done => {
if(checkSomeCondition()){
runTask('some Task') // but how?
}
else {
done();
}
}
))
The beauty of gulp4.0 is that your tasks can just be functions, so the following works:
gulp.task('Preprocess HTML', function () {
console.log("in Preprocess HTML");
return gulp.src('./');
});
You can use either the above version (the 'old way') or the newer
way below.
I show two tasks here that use both versions but I personally wouldn't mix them.
// function PreprocessHTML() {
// console.log("in Preprocess HTML");
// return gulp.src('./');
// }
function PreprocessStyles() {
console.log("in Preprocess styles");
return gulp.src('./');
}
function testTaskTrue() {
console.log("in testTaskTrue");
return gulp.src('./');
}
function testTaskFalse() {
console.log("in testTaskFalse");
return gulp.src('./');
}
function checkSomeCondition() {
console.log("in checkSomeCondition");
return false;
}
// Again, I definitely wouldn't mix the two versions of tasks as shown below.
// Just here for demonstration purposes.
gulp.task('test', gulp.parallel( 'Preprocess HTML', PreprocessStyles,
done => {
if (checkSomeCondition()) {
// so testTaskTrue can be any gulp4.0 task, easy to call since it just a function
testTaskTrue();
}
else {
testTaskFalse();
}
done();
}
));
For gulp 4, first create this helper function:
function gulpTaskIf(condition, task) {
task = gulp.series(task) // make sure we have a function that takes callback as first argument
return function (cb) {
if (condition()) {
task(cb)
} else {
cb()
}
}
}
As its first argument, this helper takes a condition in the form of a function. The condition function is run at the time when the task execution is to start, so you can i.e. check output of previous steps in the condition function.
The second arguments specifies the task to be run and can be the same values that gulp.parallel() or gulp.series() accept as arguments, i.e. string, function reference, or a return value from another gulp.parallel() or gulp.series().
Returns a function that can be passedto gulp.task() as second argument or as an argument to gulp.parallel() or gulp.series() call.
Examples (first one matches question):
embedded in e.g. gulp.parallel() or gulp.series(), calling task by name
gulp.task('Build', gulp.parallel(
'Preprocess HTML',
'Prepeocess styles',
runTaskIf(checkSomeCondition, 'some Task')
))
as a task, calling task by name
function myTask() {
return gulp.src(...)
...
.dest(...)
}
gulp.task('my-task', myTask)
gulp.task('default', gulpTaskIf(
function () {
return Math.random() < 0.5; // example condition
},
'my-task')
as a standalone task, calling task by function reference
function myTask() {
return gulp.src(...)
...
.dest(...)
}
gulp.task('default', gulpTaskIf(() => Math.random() < 0.5, myTask)
as a standalone task, calling gulp.parallel() or gulp.series() reference
const manyTasks = gulp.parallel(task1, task2, task3)
gulp.task('default', gulpTaskIf(
function () {
return Math.random() < 0.5;
},
manyTasks)
It is really simple. No need of helper function:
gulp.task('Build', function() {
const tasks = ['Preprocess HTML', 'Preprocess styles'];
if(checkSomeCondition()) tasks.push('some Task');
return gulp.parallel(tasks);
}());
The clue is in calling the function at the last line - it will return an adjusted gulp.parallel task - I am using this to handle command line arguments (yargs)
WARNING: this will be executed before the first task is executed and will be executed also when other task than 'Build' is run. Just have it on your mind when implementing logic ;)
I have an array for plugins where I do a simple If query and then expand the array, see line 280 here.
Based on Gulp 4.
For the build process I changed the Const to Let and also queried it with If.

Named function vs assigned anonymous function in Redux Action Creators

I have tried researching this but was rather swamped, was wondering if someone has a solid answer regarding use of named functions in redux action creators vs named functions - is there any performance difference? Or any other factors that affect this?
eg:
function getUserIdentity() {
return (dispatch) => {
dispatch({
type: types.GET_USER_IDENTITY,
});
}
}
vs
const getUserIdentity = () => (dispatch) => { dispatch({type: types.GET_USER_IDENTITY}) };
Thanks!
Any performance difference doesn't matter, the two functions aren't even doing the same. The arrow function "equivalent" of your function declaration would be
const getUserIdentity = () => (dispatch) => { dispatch({type: types.GET_USER_IDENTITY}) };
not
const getUserIdentity = (dispatch) => dispatch({ type: types.GET_USER_IDENTITY });
as in your question.
Regarding the updated question, no there is no performance difference between calling the different function types. However, there is still a behavioural difference, see Arrow function vs function declaration / expressions: Are they equivalent / exchangeable? and also var functionName = function() {} vs function functionName() {} - a variable initialisation happens at a different time than that of a "hoisted" function declaration, which might make a difference depending on how/where the function is used.

How works this in arrow functions [duplicate]

I've read in several places that the key difference is that this is lexically bound in arrow functions. That's all well and good, but I don't actually know what that means.
I know it means it's unique within the confines of the braces defining the function's body, but I couldn't actually tell you the output of the following code, because I have no idea what this is referring to, unless it's referring to the fat arrow function itself....which doesn't seem useful.
var testFunction = () => {
console.log(this)
};
testFunction();
Arrow functions capture the this value of the enclosing context
function Person(){
this.age = 0;
setInterval(() => {
this.age++; // |this| properly refers to the person object
}, 1000);
}
var p = new Person();
So, to directly answer your question, this inside your arrow function would have the same value as it did right before the arrow function was assigned.
In order to provide the big picture I'm going to explain both, dynamic and lexical binding.
Dynamic Name Binding
this refers to the object the method is called on. This is a regularly to be read sentence on SO. But it is still only a phrase, pretty abstract. Is there a corresponding code pattern to this sentence?
Yes there is:
const o = {
m() { console.log(this) }
}
// the important patterns: applying methods
o.m(); // logs o
o["m"](); // logs o
m is a method because it relies on this. o.m() or o["m"]() means m is applied to o. These patterns are the Javascript translation to our famous phrase.
There is another important code pattern that you should pay attention to:
"use strict";
const o = {
m() { console.log(this) }
}
// m is passed to f as a callback
function f(m) { m() }
// another important pattern: passing methods
f(o.m); // logs undefined
f(o["m"]); // logs undefined
It is very similar to the previous pattern, only the parenthesis are missing. But the consequences are considerable: When you pass m to the function f, you pull outm of its object/context o. It is uprooted now and this refers to nothing (strict mode assumed).
Lexical (or Static) Name Binding
Arrow functions don't have their own this/super/arguments binding. They inherit them from their parent lexical scope:
const toString = Object.prototype.toString;
const o = {
foo: () => console.log("window", toString.call(this)),
bar() {
const baz = () => console.log("o", toString.call(this));
baz();
}
}
o.foo() // logs window [object Window]
o.bar() // logs o [object Object]
Apart from the global scope (Window in browsers) only functions are able to form a scope in Javascript (and {} blocks in ES2015). When the o.foo arrow function is called there is no surrounding function from which baz could inherit its this. Consequently it captures the this binding of the global scope which is bound to the Window object.
When baz is invoked by o.bar, the arrow function is surrounded by o.bar (o.bar forms its parent lexical scope) and can inherit o.bar's this binding. o.bar was called on o and thus its this is bound to o.
Hope this code show could give you clearer idea. Basically, 'this' in arrow function is the current context version of 'this'. See the code:
// 'this' in normal function & arrow function
var this1 = {
number: 123,
logFunction: function () { console.log(this); },
logArrow: () => console.log(this)
};
this1.logFunction(); // Object { number: 123}
this1.logArrow(); // Window
Arrow function this is pointing to the surrounding parent in Es6, means it doesn't scope like anonymous functions in ES5...
It's very useful way to avoid assigning var self to this which is widely used in ES5...
Look at the example below, assigning a function inside an object:
var checkThis = {
normalFunction: function () { console.log(this); },
arrowFunction: () => console.log(this)
};
checkThis.normalFunction(); //Object {}
checkThis.arrowFunction(); //Window {external: Object, chrome: Object, document: document, tmpDebug: "", j: 0…}
You can try to understand it by following the way below
// whatever here it is, function or fat arrow or literally object declare
// in short, a pair of curly braces should be appeared here, eg:
function f() {
// the 'this' here is the 'this' in fat arrow function below, they are
// bind together right here
// if 'this' is meaningful here, eg. this === awesomeObject is true
console.log(this) // [object awesomeObject]
let a = (...param) => {
// 'this is meaningful here too.
console.log(this) // [object awesomeObject]
}
so 'this' in fat arrow function is not bound, means you can not make anything bind to 'this' here, .apply won't, .call won't, .bind won't. 'this' in fat arrow function is bound when you write down the code text in your text editor. 'this' in fat arrow function is literally meaningful here. What your code write here in text editor is what your app run there in repl. What 'this' bound in fat arror will never change unless you change it in text editor.
Sorry for my pool English...
Arrow function never binds with this keyword
var env = "globalOutside";
var checkThis = {env: "insideNewObject", arrowFunc: () => {
console.log("environment: ", this.env);
} }
checkThis.arrowFunc() // expected answer is environment: globalOutside
// Now General function
var env = "globalOutside";
var checkThis = {env: "insideNewObject", generalFunc: function() {
console.log("environment: ", this.env);
} }
checkThis.generalFunc() // expected answer is enviroment: insideNewObject
// Hence proving that arrow function never binds with 'this'
this will always refer to the global object when used inside an arrow function. Use the regular function declaration to refer to the local object. Also, you can use the object name as the context (object.method, not this.method) for it to refer to the local object instead of the global(window).
In another example, if you click the age button below
<script>
var person = {
firstName: 'John',
surname: 'Jones',
dob: new Date('1990-01-01'),
isMarried: false,
age: function() {
return new Date().getFullYear() - this.dob.getFullYear();
}
};
var person2 = {
firstName: 'John',
surname: 'Jones',
dob: new Date('1990-01-01'),
isMarried: false,
age: () => {
return new Date().getFullYear() - this.dob.getFullYear();
}
};
</script>
<input type=button onClick="alert(person2.age());" value="Age">
it will throw an exception like this
×JavaScript error: Uncaught TypeError: Cannot read property
'getFullYear' of undefined on line 18
But if you change person2's this line
return new Date().getFullYear() - this.dob.getFullYear();
to
return new Date().getFullYear() - person2.dob.getFullYear();
it will work because this scope has changed in person2
Differences between arrow functions to regular functions: (taken from w3schools)
With arrow functions there are no binding of this.
In regular functions the this keyword represented the object that called the function, which could be the window, the document, a button or whatever.
With arrow functions the this keyword always represents the object that defined the arrow function.
// Regular Function:
hello = function() {
document.getElementById("demo").innerHTML += this;
}
// The window object calls the function:
window.addEventListener("load", hello);
// A button object calls the function:
document.getElementById("btn").addEventListener("click", hello);
// -------------------------------------------
// Arrow function
hello2 = () => {
document.getElementById("demo2").innerHTML += this;
}
// The window object calls the function:
window.addEventListener("load", hello2);
// A button object calls the function:
document.getElementById("btn2").addEventListener("click", hello2);
<p><i>With a regular function this represents the <b>object that calls the function</b>:</i></p>
<button id='btn'>click me regular function</button>
<p id="demo">Regular function: </p>
<hr>
<p><i>With arrow function this represents the <b>owner of the function(=the window object)</b>:</i></p>
<button id='btn2'>click me arrow function</button>
<p id="demo2">Arrow function: </p>
A related issue:
Came from - Why can't I access `this` within an arrow function?
We know below from here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Does not have its own bindings to this or super, and should not be used as methods.
Arrow functions establish "this" based on the scope the Arrow function is defined within.
Had a issue with this using arrow functions, so created a class (can be function), and class variable is accessed in arrow function, thereby achieved smaller functions using arrow functions without function keyword:
class MyClassOrFunction {
values = [];
size = () => this.values.length;
isEmpty = () => this.size() === 0;
}
let obj = new MyClassOrFunction();
obj.size(); // function call here
You can also have a getter like this, that does not have function keyword, but a bit longer due to return statement, also can access other member functions:
class MyClassOrFunction {
values = [];
size = () => this.values.length;
get length() { return this.size(); }
}
let obj = new MyClassOrFunction();
obj.length; // NOTE: no function call here

How to intercept/peek in an Immutable.js Map- or List chain

Sometimes my Redux selectors are quite complicated. I need some means for debugging each step in the chain.
Here is a simplified selector as an example:
export const selectCompletedFilesForSaveToServer = state => {
return state
.getIn(['file', 'saveToServerQueue'])
.filterNot(item => item.get('isPosting'))
.valueSeq();
};
And this is what I want to do:
export const selectCompletedFilesForSaveToServer = state => {
return state
.getIn(['file', 'saveToServerQueue'])
.intercept(item => console.log(item.toJS())
.filterNot(item => item.get('isPosting'))
.intercept(item => console.log(item.toJS())
.valueSeq();
};
I.e. the intercept function should take whatever collection is thrown at it (Map, List, etc), iterate over the collection and then return the original collection for further chaining.
I tried to use .forEach(), but I didn't understand how it works.
My current solution is to manually break up the chain into separate intermediate variables for inspection, but this is not a nice solution.
Well.. while writing my question I kind of got some perspective and solved it.
The .filter() function essentially is a peek function. Just remember to return true..
export const selectCompletedFilesForSaveToServer = state => {
return state
.getIn(['file', 'saveToServerQueue'])
.filter(item => {
console.log(item.toJS());
return true;
});
.filterNot(item => item.get('isPosting'))
.filter(item => {
console.log(item.toJS());
return true;
});
.valueSeq();
};
edit:
I found an even better function: .update(). It's chainable and takes a custom function as an argument. The custom function gets the collection as argument and should return the collection as well (in my use case).
https://facebook.github.io/immutable-js/docs/#/Collection/update
New example:
export const selectCompletedFilesForSaveToServer = state => {
const peek = function(collection) {
console.log(collection.toJS());
return collection;
};
return state
.getIn(['file', 'saveToServerQueue'])
.update(peek);
.filterNot(item => item.get('isPosting'))
.update(peek);
.valueSeq();
};