Skip to content

Instantly share code, notes, and snippets.

@Phoenix35
Last active April 1, 2020 18:07
Show Gist options
  • Save Phoenix35/bf6adbef90cdbc401f19920d1b97a00b to your computer and use it in GitHub Desktop.
Save Phoenix35/bf6adbef90cdbc401f19920d1b97a00b to your computer and use it in GitHub Desktop.
// Courtesy of Kusu
/*
for (const value of obj) {
// loop body
}
*/
{
const it = obj[Symbol.iterator]();
try {
for (let step; step = it.next(), !step.done; ) {
const value = step.value;
// loop body
}
}
catch(e) { throw e; }
finally { it.return(); }
}
/*
for (const key in obj) {
// loop body
}
*/
{
let current = obj;
do {
const keys = Reflect.ownKeys(current);
const keysLength = keys.length;
for (let i = 0; i < keysLength; ++i) {
const key = keys[i];
if (!Object.getOwnPropertyDescriptor(current, key).enumerable) continue;
// loop body
}
if (current === Object.prototype) break;
current = Object.getPrototypeOf(current);
if (current === null) break;
} while(true);
}
// Courtesy of MrLeebo
/* <forEach vs. for of */
// for...of: control flow
for (const obj of arr) {
if (obj.skip) continue;
if (obj.terminate) break;
return obj.name;
}
// no .forEach equivalent
// for...of: visible side effect
for (const obj of arr) {
obj.sendEmailNotification();
}
const processObject = obj => obj.sendEmailNotification();
// forEach: side effect declaration and execution are separated
arr.forEach(processObject);
/* forEach vs. for of> */
// Expected async behaviour. One request after the other
for (const entity of entities) {
await fetch(
remote,
{
headers: {
"Content-Type": "application/json; charset=utf-8",
},
body: JSON.stringify(entity),
}
);
}
// Spam requests!
entities.forEach(async (entity) => {
await fetch(
remote,
{
headers: {
"Content-Type": "application/json; charset=utf-8",
},
body: JSON.stringify(entity),
}
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment