Skip to content

Instantly share code, notes, and snippets.

@schabluk
Last active May 20, 2021 10:56
Show Gist options
  • Save schabluk/b5818cae13fde39de0d87b077d59ca6a to your computer and use it in GitHub Desktop.
Save schabluk/b5818cae13fde39de0d87b077d59ca6a to your computer and use it in GitHub Desktop.
Array / Object Tools
// First value.
Array.from(foo).find(i => i)
Array.from(foo).shift()
// Last value.
Array.from(foo).pop()
const last = map => Array.from(map).pop()
/* Genrate seuence of index values.*/
const indexProducer = function * (i = 0) { while (true) yield i++ }
const indexSequence = indexProducer(-1)
// Split array into equal chunks
const result = new Array(Math.ceil(images.length / 4)).fill().map(_ => images.splice(0, 4))
// Intersect two arrays
.reduce((a, b) => b.filter(f => a.length ? a.indexOf(f) > -1 : true), [])
// Array.prototype
(function Functor(x){
const z = []
return {
map: (fn) => {
for(i = 0; i <= x.length - 1; i++) {
z.push(fn(x[i]))
}
return Functor(z)
},
filter: (fn) => {
for(i = 0; i <= x.length - 1; i++) {
if (fn(x[i]) === true) {
z.push(x[i])
}
}
return Functor(z)
},
forEach: (fn) => {
for(i = 0; i <= x.length - 1; i++) {
fn(x[i])
}
return Functor(x)
},
reduce: (fn, initial) => {
// No time, sorry.
return x.reduce(fn, initial)
},
valueOf: () => x
}
})([1, 2, 3, 4, 5]).map(x => x * 2).filter(x => x < 5).forEach(element => console.log(element)).reduce((p, c) => p + c, 10).valueOf()
## JSON => CSV
fetch('https://address.com/rest/api/2/field')
.then(data => data.json())
.then(data => data.map(({id, name, custom}) => ([id, name, custom]).join('|')).join("\n"))
.then(console.log)
## Request body
fetch('https://address.com/rest/api', {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
timestamp: Date.now(),
message,
stack,
componentStack,
}),
}).catch(console.log)
/**
Content-Type: 'application/octet-stream; charset=utf-8'
Content-Disposition: attachment; filename="filename.jpg"; filename*="filename.jpg"
Content-Length: <size in bytes>
*/
## Download file
fetch('https://beagle.internal.epo.org/user-area/userarea-mailbox-backend-intg/bff/communications/EJNADU07DHELML1/content', {
method: 'GET',
mode: 'no-cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/octet-stream; charset=utf-8',
'Content-Disposition': 'attachment; filename="filename.pdf"; filename*="filename.pdf"'
},
}).catch(console.log)
const randomIntFromRange = (min, max) => {
return Math.floor(Math.random()*(max-min+1)+min)
}
const randomFromTo = function randomFromTo(from, to){
return Math.floor(Math.random() * (to - from + 1) + from)
}
/*
* Cartesian product of multiple sets.
* http://stackoverflow.com/a/43053803
*/
const f = (a, b) => [].concat(...a.map(d => b.map(e => [].concat(d, e))))
export const cartesian = (a, b, ...c) => (b ? cartesian(f(a, b), ...c) : a)
/*
* Power set.
* https://rosettacode.org/wiki/Power_set#ES6
*/
export const powerset = xs => xs.reduceRight((a, x) => a.concat(a.map(y => [x].concat(y))), [[]])
// Read directory async way
const path = require('path')
const fs = require('fs')
function list(dir) {
return fs.statSync(dir).isDirectory()
? [].concat(...fs.readdirSync(dir).map(f => list(path.join(dir, f))))
: dir
}
list('./src/images').map(file => {
const { name, ext } = path.parse(file)
const absolutePath = path.resolve(__dirname, file)
//...
})
// Is empty
const empty = {}
Object.keys(empty).length === 0 && empty.constructor === Object
// Unique Values
['FOO', 'BAR', 'BAR'].filter((v, i, a) => a.findIndex(e => e === v) === i)
Array.from(new Set(['FOO', 'BAR', 'BAR']))
// Unique from Object.
[
{id: 'a', value: 0},
{id: 'b', value: 1},
{id: 'b', value: 2},
{id: 'b', value: 3}
].filter((v, i, a) => a.findIndex(e => e.id === v.id) === i)
// Unique by Object key.
[
{a: {id: 'a', value: 0}},
{b: {id: 'b', value: 1}},
{b: {id: 'b', value: 2}},
{b: {id: 'b', value: 3}}
].filter((v, i, a, [k] = Object.keys(v)) => a.findIndex(e => e[k]) === i)
// First & Last
const {0: first, length, [length - 1]: last} = ['a', 'b', 'c', 'd', 'e']
// First & Last object property from array.
const [{ index }] = [{ index: 'test', size: '100' }, { index: 'data', size: '200' }]
const {length, [length - 1]: { index }} = [{ index: 'test', size: '100' }, { index: 'data', size: '200' }]
// Destructuring Objects
const {length, [length - 1]: [orderBy, {order: direction}]} = Object.entries({ _id: { order: 'desc' } })
// Find by index using destructuring.
const { [inspectedIndex]: { id: inspectedId } = {} as Object } = items;
// Conditional destructuring
return {
...(isTrue && { icon: 'foo' }),
isOpen: false,
}
// Destructuring strings
const { firstname, lastname } = userInfo ?? {
firstname: 'Unknown',
lastname: 'Unknown',
}
const [[first], [last]] = [firstname, lastname]
// Remove from object by Key.
case ActionTypes.REMOVE_DRAFT:
const { [action.payload]: value, ...rest } = state.drafts;
return {
...state,
drafts: {
...rest,
},
};
// Declarative reverse
['a', 'b', 'c', 'd', 'e'].reduce((prev, curr, i, {length, [length - i - 1]: last}) => prev.concat(last), [])
['a', 'b', 'c', 'd', 'e'].reduce((prev, curr, i, {length, [length - i - 1]: last}) => {
prev.push(last) // faster
return prev
}, [])
// Check length boolean
const isChecked: boolean = Boolean(tasks.length)
// Reducing/Mapping Object - how to map the content of nested properties and return the same structure.
const mapping = {
"logs": {
"mappings": {
"properties": {
"message": { "type": "text" },
"name": { "type": "keyword"},
}
}
},
"test": {
"mappings": {
"properties": {
"amount": { "type": "long" },
"category": { "type": "keyword" },
}
}
}
}
Object.keys(mapping).reduce(
(p, c, i, a, { mappings: { properties: props } } = mapping[c]) => ({
...p,
[c]: Object.keys(props).map(name => ({ name, ...props[name] })),
}),
{},
)
// Group by Path
(function groupBy(array, path) {
return array.reduce((prev, curr, i, a) => {
const key = curr[path]
const existing = prev[key]
return {
...prev,
[key]: existing ? [curr].concat(existing) : [curr],
}
}, {})
})([{id: 'a', value: 0}, {id: 'b', value: 1}, {id: 'b', value: 2}, {id: 'b', value: 3}], 'id')
(function groupBy(array, path) {
return array.reduce((p, c, i, a, k = c[path], e = p[k]) => ({ ...p, [k]: e ? [c].concat(e) : [c] }), {})
})([{id: 'a', value: 0}, {id: 'b', value: 1}, {id: 'b', value: 2}, {id: 'b', value: 3}], 'id')
// Delaying response
let delay = time => result => new Promise(resolve => setTimeout(() => resolve(result), time))
const result = await fetch(endpoint).then(delay(1000)).then(data => data.json())
// Mocking Fetch
window.fetch = function () {
const body = { hello: "world" }
const blob = new Blob([JSON.stringify(body, null, 2)], { type : 'application/json' })
const init = { "status": 200 , "statusText": "MKEY" }
const resp = new Response(blob, init)
return new Promise(resolve => setTimeout(() => resolve(resp), 100))
}
//
import addDays from 'date-fns/addDays'
import endOfToday from 'date-fns/endOfToday'
/* eslint-disable prefer-rest-params */
declare global {
interface Window {
fetch: any
}
}
const originalFetch = fetch
if (typeof window === 'object') {
window.fetch = function () {
const [url] = Array.from(arguments)
if (url.includes('/bff/tasks/pending')) {
return Promise.resolve({
json: () =>
Promise.resolve({
items: Array.from({ length: 100 }, (_, i) => i).map((i) => ({
applicationNumber: 'EP06711973',
id: `939ea316-b4a6-${i}1eb-8cff-3e59b2cb6859`,
mfeUrl:
'https://nef-non-prod.internal.epo.org/filing/test/ui/static/nef-igra-mf-ui.js',
processId: '939ea316-b4a6-11eb-8cff-3e59b2cb6859',
taskCreatedDate: 1618821184000,
taskDueToDate: ((index) => {
switch (index) {
case 0:
return addDays(Date.now(), -5) // Overdue
case 1:
return endOfToday().getTime()
case 2:
return addDays(Date.now(), 1) // Due in 1 day
case 3:
return addDays(Date.now(), 5) // Due in x days
case 4:
return addDays(Date.now(), 14) // Due in 2 weeks
default:
return addDays(Date.now(), 30)
}
})(i),
taskName: 'Lorem Ipsum Dolor Sit Amet',
userReference: `REF000000${i}`,
})),
total: 1,
}),
})
} else {
return originalFetch.call(this, ...arguments)
}
}
}
fetch('https://api.tvmaze.com/search/shows?q=batman').then(data => data.json()).then(console.log).catch(console.error)
import { capitalize } from 'lodash'
// Capitalize / Camel Casing
const getDesc = name => name.split('_').map(c => capitalize(c)).join(' ')
// CSV parsing
const parseCSV = (data, csv, separator = ',', newline = '\n') => {
return data
.split(newline)
.map(line => line.split(separator))
.map(([name, type, length]) => ({ name, type, length }))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment