mirror of
https://gitlab.silvrtree.co.uk/martind2000/md-utils.git
synced 2025-01-10 20:45:07 +00:00
a6b91770ae
Added tests
99 lines
2.4 KiB
JavaScript
99 lines
2.4 KiB
JavaScript
'uses strict';
|
|
/**
|
|
* *
|
|
* User: Martin Donnelly
|
|
* Date: 2016-03-15
|
|
* Time: 15:08
|
|
*
|
|
*/
|
|
|
|
|
|
module.exports = {
|
|
newObjectFrom(source, fields) {
|
|
var rObj = {};
|
|
for (var item in fields) {
|
|
if (source.hasOwnProperty(fields[item])) {
|
|
rObj[fields[item]] = source[fields[item]];
|
|
}
|
|
}
|
|
return rObj;
|
|
}, reDashObject(source) {
|
|
var rObj = {};
|
|
for (var item in source) {
|
|
if (source.hasOwnProperty(item)) {
|
|
var newName = item.replace('_', '-');
|
|
rObj[newName] = source[item];
|
|
}
|
|
}
|
|
|
|
return rObj;
|
|
}, unDashObject(source) {
|
|
var rObj = {};
|
|
for (var item in source) {
|
|
if (source.hasOwnProperty(item)) {
|
|
var newName = item.replace('-', '_');
|
|
rObj[newName] = source[item];
|
|
}
|
|
}
|
|
|
|
return rObj;
|
|
}, populateObject(source, dest) {
|
|
var rObj = dest;
|
|
for (var item in source) {
|
|
if (source.hasOwnProperty(item)) {
|
|
rObj[item] = source[item];
|
|
}
|
|
}
|
|
|
|
return rObj;
|
|
}, sanitiseObj(obj, methods) {
|
|
for (var item in methods) {
|
|
if (obj.hasOwnProperty(item)) {
|
|
if (typeof obj[item] === 'string') {
|
|
obj[item] = this.strip(obj[item], methods[item]);
|
|
}
|
|
}
|
|
}
|
|
return obj;
|
|
}, strip: function(text, loose) {
|
|
var _loose = loose || false;
|
|
var ch;
|
|
var s = [];
|
|
var SCRIPT_REGEX = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi;
|
|
|
|
var CHECKCHARS = '0123456789' + // Numeric
|
|
'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + // Alphabetic
|
|
"abcdefghijklmnopqrstuvwxyz-'" + (_loose === false ? '' : "_,.!~*()@:+/\\");// jscs:ignore validateQuoteMarks
|
|
|
|
if (typeof text === 'string') {
|
|
while (SCRIPT_REGEX.test(text)) {
|
|
text = text.replace(SCRIPT_REGEX, '');
|
|
}
|
|
|
|
for (var i = 0; i < text.length; i++) {
|
|
ch = text.charAt(i);
|
|
if (ch === ' ') {
|
|
s.push(' ');
|
|
} else if (ch.charCodeAt(0) < 255 && CHECKCHARS.indexOf(ch) !== -1) {
|
|
s.push(ch);
|
|
}
|
|
}
|
|
text = s.join('').trim();
|
|
}
|
|
return text;
|
|
}, cloneTrim(from) {
|
|
var _out = {};
|
|
if (typeof from === 'object' && Object.keys(from).length !== 0) {
|
|
// Copy the required fields into the data object..
|
|
for (var key in from) {
|
|
|
|
if (from.hasOwnProperty(key)) {
|
|
_out[key] = typeof from[key] === 'string' ? from[key].trim() : from[key];
|
|
}
|
|
}
|
|
}
|
|
return _out;
|
|
}
|
|
|
|
};
|