Skip to content

Instantly share code, notes, and snippets.

@stolksdorf
Last active July 19, 2022 05:18
Show Gist options
  • Save stolksdorf/0a1826b05ad2d35f5c5e3b53cc5aed60 to your computer and use it in GitHub Desktop.
Save stolksdorf/0a1826b05ad2d35f5c5e3b53cc5aed60 to your computer and use it in GitHub Desktop.
A collection of useful one-liners I tend to use
/* Non-mutating */
const map = (obj,fn)=>Object.keys(obj).map((key)=>fn(obj[key],key));
const reduce = (obj,fn,init)=>Object.keys(obj).reduce((a,key)=>fn(a,obj[key],key),init);
const filter = (obj,fn)=>Object.keys(obj).reduce((a,key)=>!!fn(obj[key],key)?a.concat(obj[key]):a,[]);
const times = (n,fn)=>Array.apply(null,{length:n}).map((_,i)=>fn(i));
const construct = (obj,fn)=>Object.keys(obj).reduce((a,key)=>{const [k,v]=fn(obj[key],key);a[k]=v;return a;},{});
const sequence = async (obj,fn)=>Object.keys(obj).reduce((a,key)=>a.then((r)=>fn(obj[key],key,r)), Promise.resolve());
/* Prototype Mutating */
const mutate = (name, func)=>Object.defineProperty(Object.prototype, name, { enumerable : false, value : func.bind(this, this)});
/* String Case Conversion */
const snakeCase = (text)=>text.toLowerCase().replace(/[^a-zA-Z0-9\s]/g, '').replace(/\s/g, '_');
const titleCase = (text)=>text.replace(/\w\S*/g, (txt)=>txt.charAt(0).toUpperCase()+txt.substr(1).toLowerCase());
const kebobCase = (text)=>text.toLowerCase().replace(/[^\w]+/g, '-');
const camelCase = (text)=>text.replace(/^([A-Z])|[\s-_]+(\w)/g, (_, a, b)=>b?b.toUpperCase():a.toLowerCase());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment