Function: hash-merge

hash-merge is a byte-compiled function defined in hasht.el.

Signature

(hash-merge &rest HASH-TABLES)

Documentation

Merge any number of HASH-TABLES. Return resultant hash table.

A single argument consisting of a list of hash tables may also be given. Return an empty hash table if any argument from the merge list is other than nil or a hash table.

Use the value of hash-merge-values-function to merge the values of entries whose keys are the same.

Source Code

;; Defined in ~/.emacs.d/elpa/hyperbole-20260414.325/hasht.el
(defun hash-merge (&rest hash-tables)
  "Merge any number of HASH-TABLES.  Return resultant hash table.
A single argument consisting of a list of hash tables may also be given.
Return an empty hash table if any argument from the merge list is other
than nil or a hash table.

Use the value of `hash-merge-values-function' to merge the values of entries
whose keys are the same."
  (let ((empty-ht (hash-make 1)))
    (and (not (hash-table-p (car hash-tables)))
	 (listp (car hash-tables))
	 ;; Handle situation where a list of hash-tables is passed in as a
	 ;; single argument, rather than as multiple arguments.
	 (setq hash-tables (car hash-tables)))
    (if (memq nil (mapcar (lambda (ht) (or (null ht) (hash-table-p ht)))
			  hash-tables))
	;; Return an empty hash table if any argument from the merge list is other
	;; than nil or a hash table
	empty-ht
      ;; Remove empty hash tables
      (setq hash-tables
	    (delq nil (mapcar (lambda (ht)
				(if (hash-table-empty-p ht) nil ht))
			      hash-tables)))
      (let ((len (length hash-tables)))
	(cond ((= len 0) empty-ht)
	      ((= len 1) (car hash-tables))
	      ;; Make the merged hash-table be 20% larger than the number of
	      ;; entries filled in all hash-tables to be merged, so that
	      ;; hash misses are minimized.
	      (t (let ((htable (hash-make
				(ceiling
				 (* 1.2 (apply '+ (mapcar 'hash-table-count
							  hash-tables))))))
		       key value)
		   (mapc
		     (lambda (ht)
		       (hash-map (lambda (val-key-cons)
				   (setq value (car val-key-cons)
					 key (cdr val-key-cons))
				   (if (gethash key htable)
				       ;; Merge values
				       (puthash
					key
					(funcall hash-merge-values-function
						 (gethash key htable)
						 value)
					htable)
				     (puthash key value htable)))
				 ht))
		     hash-tables)
		   htable)))))))