2
0
mirror of https://github.com/frappe/books.git synced 2024-11-13 00:46:28 +00:00
books/frappe/utils/index.js

79 lines
1.7 KiB
JavaScript
Raw Normal View History

2022-03-21 05:58:52 +00:00
import { pesa } from 'pesa';
2022-03-21 05:58:52 +00:00
export function slug(str) {
return str
.replace(/(?:^\w|[A-Z]|\b\w)/g, function (letter, index) {
return index == 0 ? letter.toLowerCase() : letter.toUpperCase();
})
.replace(/\s+/g, '');
}
2018-01-12 12:25:07 +00:00
2022-03-21 05:58:52 +00:00
export function getRandomString() {
return Math.random().toString(36).substr(3);
}
2018-02-01 11:07:36 +00:00
2022-03-21 05:58:52 +00:00
export async function sleep(seconds) {
return new Promise((resolve) => {
setTimeout(resolve, seconds * 1000);
});
}
2018-02-07 13:23:52 +00:00
2022-03-21 05:58:52 +00:00
export function getQueryString(params) {
if (!params) return '';
let parts = [];
for (let key in params) {
if (key != null && params[key] != null) {
parts.push(
encodeURIComponent(key) + '=' + encodeURIComponent(params[key])
);
}
}
return parts.join('&');
}
2018-03-26 12:18:07 +00:00
2022-03-21 05:58:52 +00:00
export function asyncHandler(fn) {
return (req, res, next) =>
Promise.resolve(fn(req, res, next)).catch((err) => {
console.log(err);
// handle error
res.status(err.statusCode || 500).send({ error: err.message });
});
}
/**
* Returns array from 0 to n - 1
* @param {Number} n
*/
2022-03-21 05:58:52 +00:00
export function range(n) {
return Array(n)
.fill()
.map((_, i) => i);
}
2022-03-21 05:58:52 +00:00
export function unique(list, key = (it) => it) {
var seen = {};
return list.filter((item) => {
var k = key(item);
return seen.hasOwnProperty(k) ? false : (seen[k] = true);
});
}
2022-03-21 05:58:52 +00:00
export function getDuplicates(array) {
let duplicates = [];
for (let i in array) {
let previous = array[i - 1];
let current = array[i];
if (current === previous) {
if (!duplicates.includes(current)) {
duplicates.push(current);
}
}
}
return duplicates;
}
2022-03-21 05:58:52 +00:00
export function isPesa(value) {
return value instanceof pesa().constructor;
}