md-utils/lib/md-utils.js
martind2000 a6b91770ae 0.0.3
Added tests
2016-04-10 11:45:44 +01:00

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;
}
};