Loading...
More JavaScript Posts
const flat = arr => [].concat.apply([], arr.map(a => Array.isArray(a) ? flat(a) : a));// Orconst flat = arr => arr.reduce((a, b) => Array.isArray(b) ? [...a, ...flat(b)] : [...a, b], []);// Or// See the browser compatibility at https://caniuse.com/#feat=array-flatconst flat = arr => arr.flat();// Exampleflat(['cat', ['lion', 'tiger']]); // ['cat', 'lion', 'tiger']
// `date` is a `Date` objectconst formatYmd = date => date.toISOString().slice(0, 10);// ExampleformatYmd(new Date()); // 2020-05-06
// promisify(f, true) to get array of resultsfunction promisify(f, manyArgs = false) {return function (...args) {return new Promise((resolve, reject) => {function callback(err, ...results) { // our custom callback for fif (err) {reject(err);} else {// resolve with all callback results if manyArgs is specifiedresolve(manyArgs ? results : results[0]);}}args.push(callback);f.call(this, ...args);});};}// usage:f = promisify(f, true);f(...).then(arrayOfResults => ..., err => ...);
const linearSearch = (arr, item) => {for (const i in arr) {if (arr[i] === item) return +i;}return -1;};linearSearch([2, 9, 9], 9); // 1linearSearch([2, 9, 9], 7); // -1
const heapsort = arr => {const a = [...arr];let l = a.length;const heapify = (a, i) => {const left = 2 * i + 1;const right = 2 * i + 2;let max = i;if (left < l && a[left] > a[max]) max = left;if (right < l && a[right] > a[max]) max = right;if (max !== i) {[a[max], a[i]] = [a[i], a[max]];heapify(a, max);}};for (let i = Math.floor(l / 2); i >= 0; i -= 1) heapify(a, i);for (i = a.length - 1; i > 0; i--) {[a[0], a[i]] = [a[i], a[0]];l--;heapify(a, 0);}return a;};heapsort([6, 3, 4, 1]); // [1, 3, 4, 6]
// Vanilla JS Solution:var app = document.getElementById('app');var typewriter = new Typewriter(app, { loop: true });typewriter.typeString("I'm John and I'm a super cool web developer").pauseFor(3000).deleteChars(13) // "web developer" = 13 characters.typeString("person to talk with!") // Will display "I'm John and I'm a super cool person to talk with!".start();// React Solution:import Typewriter from 'typewriter-effect';<Typewriteroptions={{ loop: true }}onInit={typewriter => {typewriter.typeString("I'm John and I'm a super cool web developer").pauseFor(3000).deleteChars(13) // "web developer" = 13 characters.typeString("person to talk with!") // Will display "I'm John and I'm a super cool person to talk with!".start();}}/>