Skip to content

Instantly share code, notes, and snippets.

View JamesTheHacker's full-sized avatar

0xDEADBEEF JamesTheHacker

  • United Kingdom
View GitHub Profile
// 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);
// 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
// This is how you shallow clone an object
const shallowClone = Object.assign({}, state);
// Change the twitter handle
shallowClone.twitter = '@zuck';
// Origional state isn't changed
console.log(state.twitter); // @JamesJefferyUK
// Changed
const state = {
twitter: '@JamesJefferyUK',
tweets: [
{
tweet: 'I <3 JavaScript',
read: false
},
{
tweet: 'React is so cooool',
read: false
[
"nodejs ",
[
[
"\u003cb\u003enode js\u003c\/b\u003e \u003cb\u003etutorial\u003c\/b\u003e",
0,
[
10
],
{
const util = require('util');
// This function waits for an unknown amount of time
const wait = (delay, callback) => {
// setInterval returns an ID. We need this to stop the timer
const id = setInterval(() => {
// Generate a random number between 0 and 1
const rand = Math.random();
if (rand > 0.95) {
const wait = (delay, callback) => { /* … */ };
const util = require('util');
// Here we use util.promisify to convert the function to a promise
const waitAsync = util.promisify(wait);
//And here we use the promisified function. Cool huh?
waitAsync(1000)
.then(data => console.log(data))
.catch(err => console.error(`[Error]: ${err}`));
node promisify.js
Waiting ...
Waiting ...
Waiting ...
Waiting ...
Waiting ...
Waiting ...
Waiting ...
Waiting ...
node promisify.js
Waiting ...
Waiting ...
Waiting ...
Waiting ...
Waiting ...
Congratulations, you have finished waiting.