Skip to content

wescpdx/clever-javascript

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 

Repository files navigation

clever-javascript

A simple collection of JavaScript snippets that I find interesting.

Arrays

Cast a Whole Array

const mixedType = ["1", 5, "2.84"];
const onlyNumbers = mixedType.map(x => parseInt(x));

Array.map()

Get Last Array Element

const myArray = [1, 2, 3, 4];
const lastElement = myArray.slice(-1);  // 4

Array.slice()

Remove Empty Array Elements

let myArray = [1, 2, null, , 3, 4];
myArray = myArray.filter(n => n);

Array.filter()

Coerce Array

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"]

Array.from()

Functions

Template Literal Function Call

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 ] ]

Template Literals

Math

Faster Math.Floor

~~2 === Math.floor(2);  // true
~~2.82398 === Math.floor(2.82398)  // true

Bitwise NOT Tilde or the Floor?

Promises

Concurrent Promises

const thingsToDo = [
    fetch("http://server/api/first-endpoint/"),
    fetch("http://server/api/second-endpoint/"),
]
const returnStatus = await Promise.all(thingsToDo);

Promise.all()

Promise Polling

const timeout = (time) => new Promise((resolve) => setTimeout(() => resolve(true), time));

while (!isReady()) {
    await timeout(1000);
}

More reusable version

Other Stuff

Sequential IDs with a Generator

function* getNextId() {
    let counter = 1000;
    while (1) {
        yield counter++;
    }
}

Generators

Replace Using a Callback

function styleHyphenFormat(propertyName) {
  function upperToHyphenLower(match, offset, string) {
    return (offset > 0 ? "-" : "") + match.toLowerCase();
  }
  return propertyName.replace(/[A-Z]/g, upperToHyphenLower);
}

String.replace()

Console Timer

console.time("performance-loop");
for (let i = 0; i < 10000; i++) {
    someFunction();
}
console.timeEnd("performance-loop");  // performance-loop: 1.075927734375 ms

console.time()

About

A collection of clever JavaScript tricks that I don't want to lose track of

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published