bui-entry.el 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. ;;; bui-entry.el --- 'Entry' type -*- lexical-binding: t -*-
  2. ;; Copyright © 2015-2016 Alex Kost <alezost@gmail.com>
  3. ;; This program is free software; you can redistribute it and/or modify
  4. ;; it under the terms of the GNU General Public License as published by
  5. ;; the Free Software Foundation, either version 3 of the License, or
  6. ;; (at your option) any later version.
  7. ;;
  8. ;; This program is distributed in the hope that it will be useful,
  9. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. ;; GNU General Public License for more details.
  12. ;;
  13. ;; You should have received a copy of the GNU General Public License
  14. ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. ;;; Commentary:
  16. ;; This file provides an API for 'entry' type which is just an alist of
  17. ;; KEY/VALUE pairs (KEY should be a symbol) with the required 'id' KEY.
  18. ;;; Code:
  19. (require 'dash)
  20. (require 'bui-utils)
  21. (defvar bui-void-value 'VOID
  22. "Value returned by `bui-entry-value' if a parameter does not exist.")
  23. (defun bui-void-value? (value)
  24. "Return non-nil, if VALUE is `bui-void-value'."
  25. (eq value bui-void-value))
  26. (defun bui-entry-value (entry param)
  27. "Return value of the ENTRY PARAM.
  28. If ENTRY does not have PARAM at all, return `bui-void-value'."
  29. (--if-let (assq param entry)
  30. (cdr it)
  31. bui-void-value))
  32. (defun bui-entry-non-void-value (entry param)
  33. "Like `bui-entry-value' but return nil if value is void."
  34. (--when-let (bui-entry-value entry param)
  35. (and (not (bui-void-value? it)) it)))
  36. (defun bui-entry-id (entry)
  37. "Return ENTRY ID."
  38. (bui-entry-value entry 'id))
  39. (defun bui-entry-by-id (entries id)
  40. "Return an entry from ENTRIES by its ID."
  41. (--find (equal (bui-entry-id it) id)
  42. entries))
  43. (defun bui-entries-by-ids (entries ids)
  44. "Return entries with IDS (a list of identifiers) from ENTRIES."
  45. (--filter (member (bui-entry-id it) ids)
  46. entries))
  47. (defun bui-entry-by-param (entries param value &optional compare)
  48. "Return an entry from ENTRIES with PARAM's value equal VALUE.
  49. The values are compared using COMPARE function (`equal' by default)."
  50. (or compare (setq compare #'equal))
  51. (--find (funcall compare (bui-entry-value it param) value)
  52. entries))
  53. (defun bui-replace-entry (entries id new-entry)
  54. "Replace an entry with ID from ENTRIES by NEW-ENTRY.
  55. Return a list of entries with the replaced entry."
  56. (--map-first (equal id (bui-entry-id it))
  57. new-entry
  58. entries))
  59. (provide 'bui-entry)
  60. ;;; bui-entry.el ends here