// Array.prototype.reduce()
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15
var sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0);
=> 6
// Arrow function
reduce((accumulator, currentValue) => { ... } )
reduce((accumulator, currentValue, index) => { ... } )
reduce((accumulator, currentValue, index, array) => { ... } )
reduce((accumulator, currentValue, index, array) => { ... }, initialValue)
// Callback function
reduce(callbackFn)
reduce(callbackFn, initialValue)
// Inline callback function
reduce(function callbackFn(accumulator, currentValue) { ... })
reduce(function callbackFn(accumulator, currentValue, index) { ... })
reduce(function callbackFn(accumulator, currentValue, index, array){ ... })
reduce(function callbackFn(accumulator, currentValue, index, array) { ... }, initialValue)
import jwt_decode from "jwt-decode";
const initState = {
loading: false,
signUpErrors: [],
loginErrors: [],
token: "",
user: "",
};
const verifyToken = (token) => {
const decodeToken = jwt_decode(token);
const expireIn = new Date(decodeToken.exp * 1000);
if (new Date() > expireIn) {
localStorage.removeItem("MyToken");
} else {
return decodeToken;
}
};
const token = localStorage.getItem("MyToken");
if (token) {
const decoded = verifyToken(token);
initState.token = token;
const { userData } = decoded;
initState.user = userData;
}
const AuthReducer = (state = initState, action) => {
if (action.type === "SET_LOADER") {
return { ...state, loading: true };
} else if (action.type === "CLOSE_LOADER") {
return { ...state, loading: false };
} else if (action.type === "SIGNUP_ERRORS") {
return { ...state, signUpErrors: action.signupError };
} else if (action.type === "SET_TOKEN") {
const decoded = verifyToken(action.token);
const { userData } = decoded;
return {
...state,
token: action.token,
user: userData,
signUpErrors: "",
loginErrors: "",
};
} else if (action.type === "LOGOUT") {
return { ...state, token: "", user: "" };
} else if (action.type === "LOGIN_ERRORS") {
return { ...state, loginErrors: action.loginErrors };
} else {
return state;
}
};
export default AuthReducer;
const arr = [5, 7, 1, 8, 4];const sum = arr.reduce(function(accumulator, currentValue) { return accumulator + currentValue;});// prints 25console.log(sum);