logo

pleroma-fe

My custom branche(s) on git.pleroma.social/pleroma/pleroma-fe git clone https://hacktivis.me/git/pleroma-fe.git

completion.js (1637B)


  1. import { reduce, find } from 'lodash'
  2. export const replaceWord = (str, toReplace, replacement) => {
  3. return str.slice(0, toReplace.start) + replacement + str.slice(toReplace.end)
  4. }
  5. export const wordAtPosition = (str, pos) => {
  6. const words = splitByWhitespaceBoundary(str)
  7. const wordsWithPosition = addPositionToWords(words)
  8. return find(wordsWithPosition, ({ start, end }) => start <= pos && end > pos)
  9. }
  10. export const addPositionToWords = (words) => {
  11. return reduce(words, (result, word) => {
  12. const data = {
  13. word,
  14. start: 0,
  15. end: word.length
  16. }
  17. if (result.length > 0) {
  18. const previous = result.pop()
  19. data.start += previous.end
  20. data.end += previous.end
  21. result.push(previous)
  22. }
  23. result.push(data)
  24. return result
  25. }, [])
  26. }
  27. export const splitByWhitespaceBoundary = (str) => {
  28. const result = []
  29. let currentWord = ''
  30. for (let i = 0; i < str.length; i++) {
  31. const currentChar = str[i]
  32. // Starting a new word
  33. if (!currentWord) {
  34. currentWord = currentChar
  35. continue
  36. }
  37. // current character is whitespace while word isn't, or vice versa:
  38. // add our current word to results, start over the current word.
  39. if (!!currentChar.trim() !== !!currentWord.trim()) {
  40. result.push(currentWord)
  41. currentWord = currentChar
  42. continue
  43. }
  44. currentWord += currentChar
  45. }
  46. // Add the last word we were working on
  47. if (currentWord) {
  48. result.push(currentWord)
  49. }
  50. return result
  51. }
  52. const completion = {
  53. wordAtPosition,
  54. addPositionToWords,
  55. splitByWhitespaceBoundary,
  56. replaceWord
  57. }
  58. export default completion