Skip to content

Instantly share code, notes, and snippets.

View JamesTheHacker's full-sized avatar

0xDEADBEEF JamesTheHacker

  • United Kingdom
View GitHub Profile
// Change the tweet on our clone
shallowClone.tweets[3].tweet = 'Hijacking your tweets bruh!';
// Changed :)
console.log(shallowClone.tweets[3]);
// Noooooo! Also change!
console.log(state.tweets[3]);
// Both properties reference the same object
// Deep clone an object
const deepClone = JSON.parse(JSON.stringify(state));
deepClone.tweets[3].tweet = 'Hijacking your tweets bruh!';
// Origional tweet is unchanged
console.log(state.tweets[3].tweet);
// Cloned tweet is changed
console.log(deepClone.tweets[3].tweet);
const deepFreeze = o => Object
.getOwnPropertyNames(o)
.forEach(n=> {
if (typeof o[n] == 'object' && o[n] !== null)
deepFreeze(o[n]);
return Object.freeze(o);
});
// Shallow freeze
Object.freeze(state);
// This will not work
state.twitter = '@zuck';
// Look, it's still @JamesJefferyUK
console.log(state.twitter);
// But this works because we're modifying a reference value (an object)
/*
* This class is a high level view of how Redux works under the hood.
* This example includes no error handling or immutability and is used
* purely as an example to demonstrate how Redux works.
*/
class FauxRedux {
// Just like Redux we accept a reducer, and some initial state
constructor(reducer, initialState = {}) {
this.store = [ initialState ];
const initialState = {
fetchingTweets: false,
tweets: []
};
const store = new FauxRedux(reducer, initialState);
store.dispatch({
type: ‘TWEETS_RECEIVED’,
isFetching: false,
tweets: [
{
username: ‘JamesJefferyUK’,
message: ‘💜 I ❤ Redux!’
},
{
username: ‘JamesJefferyUK’,
// This is a reducer, same as Redux's
const reducer = (state, action) => {
switch(action.type) {
case 'FETCHING_TWEETS':
return {...state, fetchingTweets: true};
break;
case 'TWEETS_RECEIVED':
return { ...state,
fetchingTweets: false,
tweets: action.tweets
// Subscribe to receive notifications
store.subscribe(action => {
// Check the type of action
if(action == ‘TWEETS_RECEIVED’) {
// Clear notification
document.getElementById(‘notification’).innerText = ‘’;
// Construct the HTML for the tweets list
// Returns the last element from the state store
getState() {
return this.store[this.store.length - 1];
}