Skip to content

Instantly share code, notes, and snippets.

@KooiInc
KooiInc / SplitIntoWordsParser.js
Created November 9, 2023 11:41
Split a string into words with or without single spaces, where multiple subsequent spaces are considered words.
/*
Split a string into words with or without single spaces,
where multiple subsequent spaces are considered words.
*/
function parseWords(txt, includeSingleSpaces = false) {
let result = [txt[0]];
txt = txt.slice(1).split('');
while (txt.length) {
@KooiInc
KooiInc / LocalizeStringifiedDateFactory.js
Created September 4, 2023 09:00
Create a localized date from stringified date
/**
* This factory delivers a function to create a date from a
* stringified Date (new Date().toString()) without the
* offset/locale information. Especially useful for comparison
* between dates in different timezones (e.g. client and server).
* See https://stackblitz.com/edit/web-platform-ek83hd?file=script.js
* for a use case.
*/
function localizeStringifiedDateFactory() {
const months2Object = (acc, v, i) => ({...acc, [v]: i});
@KooiInc
KooiInc / StringInterpolateFactory.js
Last active December 23, 2023 14:02
String interpolator
function interpolateFactory(defaultReplacer) {
const isStringOrNumber = v => [String, Number].find(vv => vv === Object.getPrototypeOf( v ?? {} )?.constructor);
const isObject = v => Object.getPrototypeOf( v ?? `` )?.constructor === Object;
const invalidate = key => String(defaultReplacer ?? `{${key}}`);
const replacement = (key, t) => !isStringOrNumber(t[key]) ? invalidate(key) : String(t[key]);
const replacer = token => (...args) => replacement( args.find(a => a.key).key ?? `_`, token );
const replace = (str, token) => str.replace( /\{(?<key>[a-z_\d]+)}/gim, replacer(token) );
const mergeToken = obj => {
const entries = Object.entries(obj);
const [key, values] = entries.shift();
@KooiInc
KooiInc / randomNumber.js
Created May 18, 2023 16:13
Create random number using crypto
function randomNumber (min = 0, max = Number.MAX_SAFE_INTEGER) {
return Math.floor( ( [...crypto.getRandomValues( new Uint32Array(1))][0] / 2**32 ) * (max - min + 1) + min );
}
@KooiInc
KooiInc / shuffleArray.js
Created May 18, 2023 16:09
Shuffle Array randomly (Fisher-Yates, use crypto)
function shuffle(array) {
const someNr = (min = 0, max = Number.MAX_SAFE_INTEGER) =>
Math.floor( ( [...crypto.getRandomValues( new Uint32Array(1))][0] / 2**32 ) *
(max - min + 1) + min );
const swap = (i1, i2) => [array[i1], array[i2]] = [array[i2], array[i1]];
return (Array(array.length).fill(0).forEach( (_, i) => swap( i, someNr(0, i) ) ), array);
};
@KooiInc
KooiInc / DateProxyFactory.js
Created March 3, 2023 15:46
A small Date (proxy) helper
function dateProxyFactory() {
const props = {
year: (d, v) => v && d.setFullYear(v) || d.getFullYear(),
month: (d, v) => v && d.setMonth(v - 1) || d.getMonth() + 1,
date: (d, v) => v && d.setDate(v) || d.getDate(),
hours: (d, v) => v && d.setHours(v) || d.getHours(),
minutes: (d, v) => v && d.setMinutes(v) || d.getMinutes(),
seconds: (d, v) => v && d.setSeconds(v) || d.getSeconds(),
ms: (d, v) => v && d.setMilliseconds(v) || d.getMilliseconds(),
all: d => [ d.getFullYear(), d.getMonth(), d.getDate(),
@KooiInc
KooiInc / IS.js
Last active February 11, 2023 08:03
Check all js type
const ISOneOf = (obj, ...params) => !!params.find( param => IS(obj, param) );
function IS(obj, ...shouldBe) {
if (shouldBe.length > 1) { return ISOneOf(obj, ...shouldBe); }
shouldBe = shouldBe.shift();
const invalid = `Invalid parameter(s)`;
const self = obj === 0 ? Number : obj === `` ? String :
!obj ? {name: invalid} :
Object.getPrototypeOf(obj)?.constructor;
return shouldBe ? shouldBe === self?.__proto__ || shouldBe === self :
self?.name ?? invalid;
@KooiInc
KooiInc / regexpCreator.js
Last active August 31, 2022 07:43
ES - tagged template function to create a regular expression with comments and whitespace
export default (regexStr, ...args) => {
const flags = Array.isArray(args.slice(-1)) ? args.pop().join('') : ``;
return new RegExp(
(args.length &&
regexStr.raw.reduce( (a, v, i ) => a.concat(args[i-1] || ``).concat(v), ``) ||
regexStr.raw.join(``))
.split(`\n`)
.map( line => line.replace(/\s|\/\/.*$/g, ``).trim().replace(/@s/g, ` `) )
.join(``), flags );