export const toUnixTimestamp = (date, seconds=true) => {
const divider = seconds ? 1000 : 1;
return (date.getTime() / divider) | 0;
};
export function asyncWrap(promise) {
return promise.then(result => [null, result]).catch(err => [err]);
}
Example Usage
const [error, response] = await asyncWrap(searchUsers(search_string));
if (!error) {
//DO Something. Look MA No Try catch
}
export const number_format = (val, decimals = 2) => parseFloat(+val).toFixed(decimals);
Example usage
number_format(totals, 2);
export function downloadBlob({ blob, fileName = 'download' }) {
const a = document.createElement('a');
a.href = blob;
a.style.display = 'none';
a.download = fileName;
a.setAttribute('download', fileName);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(blob);
}
Example usage
const { data: response } = await axios({
url: 'path-to-excel-file',
responseType: 'blob',
});
const blob = window.URL.createObjectURL(new Blob([response]));
const fileName = `excel.xls`;
downloadBlob({ blob, fileName });
export const delay = (ms = 100) => new Promise(resolve => setTimeout(() => resolve(), ms));
Example usage
await delay(500);
//do something else after 500 ms delay.
export function downloadFile(fileURL, fileName) {
let save = document.createElement('a');
save.href = fileURL;
save.target = '_blank';
let filename = fileName || fileURL.substring(fileURL.lastIndexOf('/') + 1);
save.download = filename;
if (
navigator.userAgent.toLowerCase().match(/(ipad|iphone|safari)/) &&
navigator.userAgent.search('Chrome') < 0
) {
document.location = save.href;
// window event not working here
} else {
let evt = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: false,
});
save.dispatchEvent(evt);
(window.URL || window.webkitURL).revokeObjectURL(save.href);
}
}
export const sortOnKeys = keysArray => (a, b) => {
return keysArray.reduce((result, key) => {
if (result) return result;
if (a[key] > b[key]) return 1;
else if (a[key] < b[key]) return -1;
return 0;
}, 0);
};
Example usage
array.sort(sortOnKeys(['propertyA', 'propertyB']))
const formattedDate = (d, options) => new Intl.DateTimeFormat('default', options).format(d);
Example Usage
const options = {
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
year: '2-digit',
hour12: true,
month: 'numeric',
day: 'numeric',
};
console.log(formattedDate(new Date(), options));
const renameKeys = (keysMap, obj) =>
Object.keys(obj).reduce(
(acc, key) => ({
...acc,
...{ [keysMap[key] || key]: obj[key] },
}),
{}
);
Example Usage
renameKeys({productId: 'product_id', productName: 'product_name'}, { productId: 4, productName: 'Keyboard'});
const copyToClipboard = str => {
const el = document.createElement('textarea');
el.value = str;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
};
Example usage
<button onClick={()=> copyToClipboard("I'm awesome"); }> Copy </button>
const indexArrayBy = key => array =>
array.reduce((acc, cur) => {
acc[cur[key]] = cur;
return acc;
}, {});
Example usage
const arr = [{id: 1, name: 'Github'}, {id: 2, name: 'Gitlab'}, {id: 3, name: 'Bitbucket'}];
const indexBy = indexArrayBy('id');
const arrById = indexBy(arr);
export const ceiling = (num, multiple = 1) => {
if (multiple === 0 || isNaN(multiple) || isNaN(num)) {
console.error(ERROR_MESSAGE);
throw new Error(ERROR_MESSAGE);
}
const multiplier = 1 / multiple;
return Number((Math.ceil(num * multiplier) / multiplier).toFixed(1));
};
Example usage
ceiling(41.8, 0.5); //Would return 42.0
ceiling(41.23, 0.5); //Would return 41.5
ceiling(41.26, 0.5); //Would return 41.5
const measure = (fn) => (...args) => {
const t0 = performance.now();
var result = fn(...args);
const t1 = performance.now()
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.")
return result;
}
function countTill(n=5e3){
for(let i=0; i<n; i++){
console.log(`${i} of ${n}`);
}
}
measure(countTill)();
//This displays the time countTill runs in ms and returns the result.
const ConditionalWrapper = ({ condition, wrapper, children }) =>
condition ? wrapper(children) : children;
Example usage
<ConditionalWrapper
condition={addLink}
wrapper={children => <a href={link}>{children}</a>}
>
<span> This will be link based on a condition </span>
</ConditionalWrapper
const ConditionalWrapper = ({ condition, wrapper, children }) =>
condition ? React.cloneElement(wrapper,{children}) : children;
Example usage
<ConditionalWrapper
condition={addLink}
wrapper={<a href={link} />}
>
<span> This will be link based on a condition </span>
</ConditionalWrapper
import React from "react";
const Dum = wrapParent(DummyComponent);
export default function App() {
return (
<div className="App">
<Dum style={{ color: "yellow" }} include={false}>
This is a dummy component wrapped or not you decide
</Dum>
</div>
);
}
function DummyComponent({ children, ...rest }) {
return <p {...rest}>{children}</p>;
}
function wrapParent(WrappedComponent) {
return (props) => {
const { include, children, ...rest } = props;
return include ? (
<WrappedComponent {...rest}> {children} </WrappedComponent>
) : (
<>{children}</>
);
};
}