Last active
November 16, 2018 20:36
-
-
Save esausilva/2c9289aa613796caaf9e832f561cf75e to your computer and use it in GitHub Desktop.
JavaScript Snippets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Forms and inputs are available via properties on document.forms. You might not need a selector | |
<form name="norm"> | |
<input type="text" name="first" value="wes"> | |
<input type="checkbox" name="toppings" value"pickles"> | |
<input type="checkbox" name="toppings" value"mustard" checked> | |
<input type="checkbox" name="toppings" value"hot sause"> | |
<input type="checkbox" name="toppings" value"cheese" checked> | |
</form> | |
<script> | |
// all the forms are available via their name on document.forms | |
console.log(document.forms.norm); // <form name="norm"> | |
// if their inputs have names, they are accessible via properties on that object | |
console.log(document.forms.norm.first); // <input type="text" name="first" value="wes"> | |
console.log(document.forms.norm.first.value); // wes | |
//get an array of checked toppings | |
const toppings = Array | |
.of(document.forms.norm.toppings) // convert from RadioNodeList to Array | |
.filter(input => input.checked) // filter for chelched inputs | |
.map(input => input.value) // get only the values | |
console.log(toppings); // ["mustard", "cheese"] | |
// cool | |
</script> | |
<!-- Source: https://twitter.com/wesbos/status/868142797936877569/photo/1 --> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Object Spread is coming soon to a JS runtime near you! Handy for creating shallow copies of an object without Object.assign() | |
const countryCodes = { | |
US: 'United States', | |
CA: 'Canada' | |
} | |
const sales = [ | |
{ code: 'US', count: 233 }, | |
{ code: 'CA', count: 200 } | |
] | |
const salesMix = sales.map(sale => { | |
return { | |
...sale, // object spread takes does a shallow copy of the sale object | |
country: countryCodes[sale.code] | |
}; | |
}); | |
// or the hotshot way with implicit return | |
const salesMix = sales.map(sale => ({...sale, country: countryCodes[sale.code]}); | |
console.table(salesMix); | |
/* | |
> 0: {code: "US", count: 233, country: "United States"} | |
> 1: {code: "CA", count: 200, country: "Canada"} | |
*/ | |
// Source: https://twitter.com/wesbos/status/874689718235037698/photo/1 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Pass a function that expects separate multiple arguments | |
// Much like Function.prototype.apply() does | |
let numbers = [9,4,7,1]; | |
Math.min(...numbers); // 1 | |
// Convert NodeList to Array | |
let divsArray = [...document.querySelectorAll('div')]; | |
// Convert Arguments to Array | |
let argsArray = [...arguments] | |
// Source: https://twitter.com/davidwalshblog/status/888452832378146816 | |
// ============================================================================= | |
/* Flatten Arrays */ | |
const nestedarray = [[[1, [1.1]], 2, 3], [4, 5], 5, "dfd", ["esau", "silva"]] | |
const flatten = arr => ( | |
arr.reduce((flat, toFlatten) => ( | |
flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten) | |
), []) | |
); | |
const flattened = flatten(nestedarray) | |
console.log(flattened); // [1, 1.1, 2, 3, 4, 5, 5, "dfd", "esau", "silva"] | |
// ============================================================================= | |
/* Assign properties dynamically */ | |
const fields = { | |
location: 'Texas', | |
bio: '', | |
blog: 'esausilva.com' | |
} | |
const data = Object.keys(fields).reduce((data, key) => { | |
if (fields[key].trim() !== '') { | |
data[key] = fields[key]; | |
} | |
return data; | |
}, {}) | |
console.log(data); | |
/* | |
Object { | |
blog: "esausilva.com", | |
location: "Texas" | |
} | |
*/ | |
// ============================================================================= | |
/* Array.of and Array.from */ | |
// Array.of will take all it's arguments and turn it into an array | |
Array.of('Hey',5,'π₯','π©'); | |
// -> ["Hey",5,"π₯","π©"] | |
//Array.from() will take anything that is array-ish / iterable and turn it into a legit array | |
Array.from({ length: 5 }); // a length property is array-like | |
// -> [undefined,undefined,undefined,undefined,undefined] | |
Array.from({ length: 5 }, x => 'π©'); // Array.from also can also take a map function | |
// -> ["π©","π©","π©","π©","π©"] | |
const students = new Set(); // ES6 Sets are iterable and can be converted into an array | |
students.add('wes'); | |
students.add('kait'); | |
students.add('snickers'); | |
students | |
// -> Set(3) {"wes","kait","snickers"} | |
Array.from(students); | |
// -> ["wes","kait","snickers"] | |
// Source: https://twitter.com/wesbos/status/894919568250089472 | |
// ============================================================================= | |
/* 4 Ways to handle the double promise with fetch */ | |
const url = 'http://api.github.com/users/websos'; | |
async function go() { | |
// 1: tack a primise unto the end | |
const d1 = await fetch(url).then(data => data.json()); | |
// 2: Double Await, BEDMAS rules everything around me | |
const d2 = await (await fetch(url)).json(); | |
// 3: capture promise in a variable | |
const data = await fetch(url); | |
// then convert it on the next line | |
const d3 = await data.json(); | |
// 4: create a utility function that returns the .json() promise. | |
// See below | |
const d4 = await getJSON(url); | |
} | |
// we use a ...rest to capture all arguments | |
function getJSON(...butter) { | |
// then ...spread it like butter into the fetch function | |
return fetch(...butter).then(data => data.json()); | |
} | |
go(); | |
// Or just use axiosd | |
// Source: https://twitter.com/wesbos/status/955831817118146560 | |
// ============================================================================= | |
/* If the Fetch API seems a little cumbersome and you donβt want to reach for | |
Axios, you can always make a handy little function that applies your defaults | |
(assumes JSON) and can be overwritten if needed */ | |
async function soFetch(input, settings = {}) { | |
const res = await fetch(input, { | |
headers: { | |
Accept: 'application/json, text/plain, */*', | |
'Content-Type': 'application/json' | |
}, | |
...settings | |
}); | |
return res.json(); | |
} | |
async function useIt() { | |
// GET request | |
const notes = await soFetch(endpoint); | |
// POST request | |
const createdNote = await soFetch(endpoint, { | |
method: 'POST', | |
body: JSON.stringify({ title: 'new note' }); | |
}); | |
} | |
// Source: https://twitter.com/wesbos/status/1063515277911052290 | |
// ============================================================================= |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment