Skip to content

Instantly share code, notes, and snippets.

@mfix22
Last active October 26, 2021 12:15
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mfix22/acba311bfced1924d78ccbb6a0a5ad3c to your computer and use it in GitHub Desktop.
Save mfix22/acba311bfced1924d78ccbb6a0a5ad3c to your computer and use it in GitHub Desktop.
Fun functional programming examples, without error handling

A bunch of random, contrived functions with maybe some value. Mostly small proof-of-concepts.

Examples

destructure()

Operates just like const sanitize = ({ id, email, date }) => ({ id, email, date }) but with destructure you can store your included keys in an array, say, in your config.

const keysToInclude = ['id', 'email', 'date']
const sanitize = destructure(keysToInclude)

return getUsers().map(sanitize)
pluckAll()

Has zero error handling, but is fun for getting to the bottom of a deeply nested JSON object (e.g. graphql or DynamoDB responses).

// contrived response
const GraphQLRes = {
  data: {
    users: [
      {
        id: 'mfix22',
        friends: [
          {
            id: 'briandennis'
          }
        ]
      },
      {
        id: 'briandennis',
        friends: [
          {
            id: 'jakedex'
          }
        ]
      }
    ]
  }
}
const myFirstFriend = pluckDeep('data.users.0.friends.0.id')
console.log(myFirstFriend(GraphQLRes));
// -> briandennis
compose()

One-line left-to-rightcompose

const cap = str => str.toUpperCase()
const swear = str => str.replace(/(a|e|i|o|u)/ig, '*')
const exclaim = str => `${str}!`

const BLOW_UP = compose(cap, swear, exclaim)

console.log(BLOW_UP('Today is good day'))
// -> T*D*Y *S G**D D*Y!
countMap()
const everyOtherLetter = countMap(x => String.fromCharCode(x + 65), 26 / 2, 2)
console.log(everyOtherLetter);
// -> [ 'A', 'C', 'E', 'G', 'I', 'K', 'M', 'O', 'Q', 'S', 'U', 'W', 'Y' ]
// ARRAY UTILS
// Find
const byKeyString = key => (a, b) => String(a[key]).localeCompare(String(b[key]))
const byKeyNumber = key => (a, b) => (Number(a[key]) - Number(b[key]))
// Sort
const byKeyValue = (k, v) => o => o[k] === v
const destructure = keys => obj => keys.reduce((accum, key) => {
if (obj[key]) accum[key] = obj[key]
return accum
}, {})
const pluckDeep = key => obj => key.split('.').reduce((accum, key) => accum[key], obj)
const compose = (...fns) => res => fns.reduce((accum, next) => next(accum), res)
const unfold = (f, seed) => {
const go = (f, seed, acc) => {
const res = f(seed)
return res ? go(f, res[1], acc.concat([res[0]])) : acc
}
return go(f, seed, [])
}
function countMap(f, c, step=1) {
return unfold((x) => {
if (x < c * step) return [f(x), x + step]
}, 0)
}
const promisify = fn => (...args) =>
new Promise((resolve, reject) =>
fn(...args, (err, data, ...rest) =>
err ? reject(err) : rest.length ? resolve([data, ...rest]) : resolve(data)))
const groupBy = fn => xs =>
xs.reduce((group, x) =>
Object.assign(group, { [fn(x)]: (group[fn(x)] ? [...(group[fn(x)]), x] : [x]) }, group), {})
@saharathkleips
Copy link

Wow thank you, very helpful 👍 🇹🇭

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment