Guest User

Untitled

a guest
Dec 11th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. const _ = require('lodash');
  2. const checkWords = require('check-word');
  3. const englishWords = checkWords('en');
  4.  
  5. /**
  6. *
  7. * @param character {string}
  8. * @returns {boolean}
  9. */
  10. function isUpper(character) {
  11. return character === character.toUpperCase();
  12. }
  13.  
  14. function capitalizeFirstCharacter(word) {
  15. return `${word[0].toUpperCase()}${word.slice(1)}`;
  16. }
  17.  
  18. function putInArray(value) {
  19. if (typeof value !== 'object') return [value];
  20. return value;
  21. }
  22.  
  23. function concat(...args) {
  24. args = args.map(putInArray);
  25. return _.compact([].concat(...args));
  26. }
  27.  
  28. /**
  29. * Split any amount of english words joined into one word into an array of words
  30. * e.g.: "helloworld" => ["hello", "world"]
  31. * @param word {string}
  32. * @returns {*}
  33. */
  34. module.exports = function split(word) {
  35. const split = module.exports;
  36.  
  37. let maxIndex = word.length;
  38. for (let index in word) {
  39. let indexDiff = maxIndex - index;
  40.  
  41. let leftCompound = word.slice(0, indexDiff);
  42. let rightCompound1 = word.slice(indexDiff, maxIndex);
  43. let rightCompound2 = word.slice(indexDiff + 1, maxIndex);
  44.  
  45. let rightCompound1Upper, rightCompound2Upper;
  46. if (rightCompound1) {
  47. rightCompound1Upper = isUpper(rightCompound1[0]);
  48. }
  49. if (rightCompound2) {
  50. rightCompound2Upper = isUpper(rightCompound2[0]);
  51. }
  52.  
  53. if (index > 0 && leftCompound.length > 1 && !englishWords.check(leftCompound)) {
  54. leftCompound = capitalizeFirstCharacter(leftCompound);
  55. }
  56.  
  57. let isLeftCompoundValidWord = leftCompound.length > 1 && englishWords.check(leftCompound);
  58. if (isLeftCompoundValidWord
  59. && ((split(rightCompound1) !== '' && !rightCompound1Upper)
  60. || rightCompound1 === '')) {
  61. return concat(leftCompound, split(rightCompound1));
  62. }
  63. else if (isLeftCompoundValidWord
  64. && word.slice(indexDiff, indexDiff + 1) === 's'
  65. && ((split(rightCompound2) !== '' && !rightCompound2Upper)
  66. || rightCompound2 === '')
  67. ) {
  68. return concat(leftCompound, split(rightCompound2));
  69. }
  70. }
  71.  
  72. if (word !== '' && englishWords.check(word)) return [word];
  73. else if (word !== '' && englishWords.check(capitalizeFirstCharacter(word)))
  74. return [capitalizeFirstCharacter(word)];
  75. else return '';
  76. };
Add Comment
Please, Sign In to add comment