A simple collection of JavaScript snippets that I find interesting.
const mixedType = ["1", 5, "2.84"];
const onlyNumbers = mixedType.map(x => parseInt(x));
const myArray = [1, 2, 3, 4];
const lastElement = myArray.slice(-1); // 4
let myArray = [1, 2, null, , 3, 4];
myArray = myArray.filter(n => n);
const people = [
{ name: "Bob", age: 25},
{ name: "Joan", age: 33},
{ name: "Mike", age: 29},
{ name: "Candice", age: 54},
];
const allNames = Array.from(people, ({name}) => name);
// allNames = ["Bob","Joan","Mike","Candice"]
function f(...args) {
return args;
}
f`true is ${true}, false is ${false}, array is ${[1, 2, 3]}`;
// -> [ [ 'true is ', ', false is ', ', array is ', '' ],
// -> true,
// -> false,
// -> [ 1, 2, 3 ] ]
~~2 === Math.floor(2); // true
~~2.82398 === Math.floor(2.82398) // true
Bitwise NOT Tilde or the Floor?
const thingsToDo = [
fetch("http://server/api/first-endpoint/"),
fetch("http://server/api/second-endpoint/"),
]
const returnStatus = await Promise.all(thingsToDo);
const timeout = (time) => new Promise((resolve) => setTimeout(() => resolve(true), time));
while (!isReady()) {
await timeout(1000);
}
function* getNextId() {
let counter = 1000;
while (1) {
yield counter++;
}
}
function styleHyphenFormat(propertyName) {
function upperToHyphenLower(match, offset, string) {
return (offset > 0 ? "-" : "") + match.toLowerCase();
}
return propertyName.replace(/[A-Z]/g, upperToHyphenLower);
}
console.time("performance-loop");
for (let i = 0; i < 10000; i++) {
someFunction();
}
console.timeEnd("performance-loop"); // performance-loop: 1.075927734375 ms