str.fnl 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. ;;; Lispy-Fennel (LF) --- The Functional Fennel Library
  2. ;;;
  3. ;;; Copyright (C) 2020 Kevin "The Nuclear" Bloom <nuclearkev@dragora.org>
  4. ;;;
  5. ;;; This file is part of LF.
  6. ;;;
  7. ;;; LF is free software: you can redistribute it and/or modify
  8. ;;; it under the terms of the MIT License.
  9. ;;;
  10. ;;; LF is distributed in the hope that it will be useful,
  11. ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;;; MIT License for more details.
  14. ;;;
  15. ;;; You should have received a copy of the MIT License
  16. ;;; along with LF. If not, see <https://opensource.org/licenses/MIT>.
  17. (local str {})
  18. (fn str.take [s ind]
  19. (string.sub s 1 ind))
  20. (fn str.drop [s ind]
  21. (string.sub s ind))
  22. (fn str.split [s by]
  23. (var current s)
  24. (var tbl-of-strings [])
  25. (var spliting? true)
  26. (while spliting?
  27. (var (start end) (string.find current by))
  28. (if start
  29. (do (table.insert tbl-of-strings (str.take current (- start 1)))
  30. (set current (str.drop current (+ end 1))))
  31. (do (table.insert tbl-of-strings current)
  32. (set spliting? false))))
  33. tbl-of-strings)
  34. ;; TODO: Work when FIR and LST are the same
  35. (fn str.substring-between [s fir lst]
  36. "Returns a substring of S defined by 2 strings, FIR and LST.
  37. The benefit of this is that if there are other instances of LST before the
  38. instance you want, they won't get caught.
  39. I.e.: You wish to get the value of the second line of \"this \n is a \n test\",
  40. You would just use (string-between str \"is a\" \"\n\")"
  41. (if (and s fir lst)
  42. (let [fir-pos (string.find s fir)]
  43. (if fir-pos
  44. (let [up-to-fir (str.drop s fir-pos)
  45. lst-pos (string.find up-to-fir lst)]
  46. (if lst-pos
  47. (str.take up-to-fir lst-pos)))))))
  48. str