Skip to content

Instantly share code, notes, and snippets.

@arasevic
Created January 18, 2018 12:06
Show Gist options
  • Save arasevic/1291bd563eff411042524f8c086562db to your computer and use it in GitHub Desktop.
Save arasevic/1291bd563eff411042524f8c086562db to your computer and use it in GitHub Desktop.
examples of some new (and older) features of JS
let test = ["Nikola", "Aleksandra", "Andreja", "Luka"]
let name1, name2, name3, name4;
[name1, name2, name3, name4] = [...test]
console.log(name4) // Luka
const result = test.reduce((x,y) => x + y, "")
const joined = test.join("")
const filtered = test.filter( name => name < "Marko")
const mapped = test.map( name => name.padStart(15, "***"))
console.log(result) // NikolaAleksandraAndrejaLuka
console.log(filtered) // [ 'Aleksandra', 'Andreja', 'Luka' ]
console.log(mapped) // [ '*********Nikola', '*****Aleksandra', '********Andreja', '***********Luka' ]
console.log(joined) // NikolaAleksandraAndrejaLuka
// async example
<script>
function breathe(amount) {
return new Promise((resolve, reject) => {
if (amount < 500) {
reject('That is too small of a value');
}
setTimeout(() => resolve(`Done for ${amount} ms`), amount);
});
}
function catchErrors(fn) {
return function (...args) {
return fn(...args).catch((err) => {
console.error('Ohhhh nooo!!!!!');
console.error(err);
});
}
}
async function go(name, last) {
console.log(`Starting for ${name} ${last}!`);
const res = await breathe(1000);
console.log(res);
const res2 = await breathe(300);
console.log(res2);
const res3 = await breathe(750);
console.log(res3);
const res4 = await breathe(900);
console.log(res4);
console.log('end');
}
const wrappedFunction = catchErrors(go);
wrappedFunction('Andrej', 'Rasevic');
</script>
// generator example
const inventors = [
{ first: 'Albert', last: 'Einstein', year: 1879 },
{ first: 'Isaac', last: 'Newton', year: 1643 },
{ first: 'Galileo', last: 'Galilei', year: 1564 },
{ first: 'Marie', last: 'Curie', year: 1867 },
{ first: 'Johannes', last: 'Kepler', year: 1571 },
{ first: 'Nicolaus', last: 'Copernicus', year: 1473 },
{ first: 'Max', last: 'Planck', year: 1858 },
];
function* loop(arr) {
console.log(inventors);
for (const item of arr) {
yield item;
}
}
const inventorGen = loop(inventors);
// Custom Promise example
const p = new Promise((resolve, reject) => {
//setTimeout(() => {
//reject(Error('Err Throwing an error to reject'));
//}, 1000);
setTimeout(() => {
resolve('asycn is where it is at!!');
}, 1000);
});
p
.then(data => {
console.log(data);
})
.catch(err => {
console.error(err);
});
function breathe(amount) {
return new Promise((resolve, reject) => {
if (amount < 500) {
reject('That is too small of a value');
}
setTimeout(() => resolve(`Done for ${amount} ms`), amount);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment