2
0
mirror of https://github.com/frappe/books.git synced 2025-01-25 16:18:33 +00:00
books/utils/index.js

84 lines
2.2 KiB
JavaScript
Raw Normal View History

2018-03-26 14:23:46 +05:30
Array.prototype.equals = function( array ) {
return this.length == array.length &&
this.every( function(item,i) { return item == array[i] } );
}
2018-02-07 18:53:52 +05:30
module.exports = {
2018-03-26 17:48:07 +05:30
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 17:55:07 +05:30
},
2018-03-05 22:15:21 +05:30
getRandomString() {
2018-02-01 16:37:36 +05:30
return Math.random().toString(36).substr(3);
},
2018-01-12 17:55:07 +05:30
async sleep(seconds) {
return new Promise(resolve => {
setTimeout(resolve, seconds * 1000);
});
2018-02-07 18:53:52 +05:30
},
_(text, args) {
// should return translated text
return this.stringReplace(text, args);
2018-02-07 18:53:52 +05:30
},
stringReplace(str, args) {
2018-02-07 18:53:52 +05:30
if (!Array.isArray(args)) {
args = [args];
}
if(str==undefined) return str;
let unkeyed_index = 0;
return str.replace(/\{(\w*)\}/g, (match, key) => {
if (key === '') {
key = unkeyed_index;
unkeyed_index++
}
if (key == +key) {
return args[key] !== undefined
? args[key]
: match;
}
});
2018-03-26 17:48:07 +05:30
},
getQueryString(params) {
if (!params) return '';
2018-03-26 18:26:21 +05:30
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 17:48:07 +05:30
},
asyncHandler(fn) {
return (req, res, next) => Promise.resolve(fn(req, res, next))
.catch((err) => {
console.log(err);
// handle error
res.status(err.status_code || 500).send({error: err.message});
});
},
/**
* Returns array from 0 to n - 1
* @param {Number} n
*/
range(n) {
return Array.from(Array(4)).map((d, i) => i)
},
unique(list, key = it => it) {
var seen = {};
return list.filter(item => {
var k = key(item);
return seen.hasOwnProperty(k) ? false : (seen[k] = true);
});
}
2018-02-07 18:53:52 +05:30
};