compromise
Version:
natural language processing in the browser
142 lines (126 loc) • 2.66 kB
JavaScript
;
// typeof obj == "function" also works
// but not in older browsers. :-/
exports.isFunction = function (obj) {
return Object.prototype.toString.call(obj) === '[object Function]';
};
//coerce any input into a string
exports.ensureString = (input) => {
if (typeof input === 'string') {
return input;
} else if (typeof input === 'number') {
return '' + input;
}
return '';
};
//coerce any input into a string
exports.ensureObject = (input) => {
if (typeof input !== 'object') {
return {};
}
if (input === null || input instanceof Array) {
return {};
}
return input;
};
//string utilities
exports.endsWith = function (str, suffix) {
if (str && str.substr(-suffix.length) === suffix) {
return true;
}
return false;
};
exports.startsWith = function (str, prefix) {
if (str && prefix) {
if (str.substr(0, prefix.length) === prefix) {
return true;
}
}
return false;
};
exports.titleCase = (str) => {
return str.charAt(0).toUpperCase() + str.substr(1);
};
//turn a nested array into one array
exports.flatten = function (arr) {
let all = [];
arr.forEach(function (a) {
all = all.concat(a);
});
return all;
};
//shallow-clone an object
exports.copy = (o) => {
let o2 = {};
o = exports.ensureObject(o);
Object.keys(o).forEach((k) => {
o2[k] = o[k];
});
return o2;
};
//shallow-merge an object
exports.extend = (o, o2) => {
if (!o) {
return o2;
}
if (!o2) {
return o;
}
Object.keys(o2).forEach((k) => {
o[k] = o2[k];
});
return o;
};
//a very naaive inflector for
//our public-facing one is in ./terms/noun/info
exports.toPlural = (str) => {
const irregular = {
Glue: 'Glue'
};
if (irregular[str]) {
return irregular[str];
}
if (str.match(/y$/i)) {
return str.replace(/y$/i, 'ies');
}
if (str.match(/person$/i)) {
return str.replace(/person$$/i, 'people');
}
if (str.match(/s$/i)) {
return str;
}
return str + 's';
};
exports.values = (obj) => {
return Object.keys(obj).map((k) => {
return obj[k];
});
};
// exports.toObj = (arr) => {
// let obj = {}
// for (let i = 0; i < arr.length; i++) {
// obj[arr[i]] = true
// }
// return obj
// }
exports.sum = (arr) => {
return arr.reduce((sum, i) => {
return sum + i;
}, 0);
};
exports.rightPad = function (str, width, char) {
char = char || ' ';
str = str.toString();
while (str.length < width) {
str += char;
}
return str;
};
exports.leftPad = function (str, width, char) {
char = char || ' ';
str = str.toString();
while (str.length < width) {
str += char;
}
return str;
};