Skip to main content

Mongoose Model

CHS
0 likes • Mar 11, 2021 • 0 views
JavaScript
Loading...

More JavaScript Posts

greatest common denominator

0 likes • Nov 19, 2022 • 0 views
JavaScript
const gcd = (...arr) => {
const _gcd = (x, y) => (!y ? x : gcd(y, x % y));
return [...arr].reduce((a, b) => _gcd(a, b));
};
gcd(8, 36); // 4
gcd(...[12, 8, 32]); // 4

Clone an array

0 likes • Nov 19, 2022 • 0 views
JavaScript
// `arr` is an array
const clone = arr => arr.slice(0);
// Or
const clone = arr => [...arr];
// Or
const clone = arr => Array.from(arr);
// Or
const clone = arr => arr.map(x => x);
// Or
const clone = arr => JSON.parse(JSON.stringify(arr));
// Or
const clone = arr => arr.concat([]);

Flatten an array

0 likes • Nov 19, 2022 • 0 views
JavaScript
const flat = arr => [].concat.apply([], arr.map(a => Array.isArray(a) ? flat(a) : a));
// Or
const 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-flat
const flat = arr => arr.flat();
// Example
flat(['cat', ['lion', 'tiger']]); // ['cat', 'lion', 'tiger']

geometric progression

0 likes • Nov 19, 2022 • 0 views
JavaScript
const geometricProgression = (end, start = 1, step = 2) =>
Array.from({
length: Math.floor(Math.log(end / start) / Math.log(step)) + 1,
}).map((_, i) => start * step ** i);
geometricProgression(256); // [1, 2, 4, 8, 16, 32, 64, 128, 256]
geometricProgression(256, 3); // [3, 6, 12, 24, 48, 96, 192]
geometricProgression(256, 1, 4); // [1, 4, 16, 64, 256]

Get timezone as a string

0 likes • Nov 19, 2022 • 0 views
JavaScript
const getTimezone = () => Intl.DateTimeFormat().resolvedOptions().timeZone;
// Example
getTimezone();

typewriter-effect in Vanilla JS and React

CHS
0 likes • Jan 25, 2023 • 7 views
JavaScript
// 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';
<Typewriter
options={{ 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();
}}
/>