Skip to content

Instantly share code, notes, and snippets.

@SergProduction
Last active September 13, 2019 12:25
Show Gist options
  • Select an option

  • Save SergProduction/72a206cb08fbe377de28819b3b0d4f1e to your computer and use it in GitHub Desktop.

Select an option

Save SergProduction/72a206cb08fbe377de28819b3b0d4f1e to your computer and use it in GitHub Desktop.
compose = (...fns) =>
fns.reduceRight((prevFn, nextFn) =>
(...args) => nextFn(prevFn(...args)),
value => value
)
composeWithState = (...fns) => (res) => fns.reduceRight((value, fn) => fn(value, res), res)
const closest = (arr, g) =>
arr.reduce((prev, cur) =>
Math.abs(cur-g) < Math.abs(prev-g) ? cur : prev);
const random = (min=5, max=15) => {
var rand = min - 0.5 + Math.random() * (max - min + 1)
rand = Math.round(rand);
return rand;
}
const objSlice = (obj, sort, ...slice) => (
Object.entries(obj)
.sort((a, b) => sort(a[1], b[1]))
.slice(...slice)
.reduce((all, [key, value]) =>
Object.assign(all, { [key]: value }), {})
)
const stringifyValues = (x) => Object.entries(x).reduce((acc, [key, value]) => typeof value !== 'object'
? Object.assign(acc, {[key]: JSON.stringify(value) })
: Object.assign(acc, {[key]: stringifyValues(value) }), {})
/* // example
stringifyValues({a:{b:{c:5}}})
*/
const incrimentCircle = (arr=[1,2,3], i=0) => (step=arr) => {
if (!step[i]) {
i = 0
}
const current = step[i]
i += 1
return current
}
/* // example
const incriment = incrimentCircle()
for(let i=0; i<20; i++) {
const count = incriment()
console.log(count)
}
*/
const diffArrays = (arr1, arr2, prop) => {
const array1 = arr1.length > arr2.length ? arr1.slice() : arr2.slice()
const array2 = arr1.length < arr2.length ? arr1.slice() : arr2.slice()
if (array2.length === 0)
return array1
let indexLessArr = 0
array1.sort((a, b) => a[prop] - b[prop])
array2.sort((a, b) => a[prop] - b[prop])
return array1.filter(it => {
if (array2[indexLessArr][prop] === it[prop]) {
indexLessArr += 1
return false
}
return true
})
}
const PromiseAllFinaly = (promises, mapError) => {
const results = []
let completedPromises = 0
return new Promise((resolve, reject) => {
promises.forEach((promise, index) => {
promise.then((value) => {
results[index] = value
completedPromises += 1
if (completedPromises === promises.length) {
resolve(results)
}
}).catch(function (error) {
results[index] = mapError(error)
completedPromises += 1
if (completedPromises === promises.length) {
resolve(results)
}
})
})
})
}
const multiSplit = (str, delimeters) => {
let right = str;
const result = [];
for (let i = 0; i < delimeters.length; i++) {
const indexDel = right.indexOf(delimeters[i]);
if (indexDel === -1) continue;
result.push(right.slice(0, indexDel));
right = right.slice(indexDel + 1);
}
result.push(right);
return result;
};
const multiJoin = ([hStr, ...tStr], [hDel, ...tDel]) =>
hStr && hDel ? hStr + hDel + multiJoin(tStr, tDel)
: hStr ? hStr
: "";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment