[commodity-utils] refactor gnc:pricelist-price-find-nearest

instead of O(3n), this implementation is O(n)
This commit is contained in:
Christopher Lam 2019-07-21 20:35:28 +08:00
parent 1387c05f4d
commit e5b756fada

View File

@ -295,27 +295,21 @@ construct with gnc:make-gnc-monetary and gnc:monetary->string instead.")
;; pricelist comes from ;; pricelist comes from
;; e.g. gnc:get-commodity-totalavg-prices. Returns a <gnc-numeric> or, ;; e.g. gnc:get-commodity-totalavg-prices. Returns a <gnc-numeric> or,
;; if pricelist was empty, #f. ;; if pricelist was empty, #f.
(define (gnc:pricelist-price-find-nearest (define (gnc:pricelist-price-find-nearest pricelist date)
pricelist date) (let lp ((pricelist pricelist))
(let* ((later (find (lambda (p) (cond
(< date (car p))) ((null? pricelist) #f)
pricelist)) ((null? (cdr pricelist)) (cadr (car pricelist)))
(earlierlist (take-while (else
(lambda (p) (let ((earlier (car pricelist))
(>= date (car p))) (later (cadr pricelist)))
pricelist)) (cond
(earlier (and (not (null? earlierlist)) ((< (car later) date)
(last earlierlist)))) (lp (cdr pricelist)))
((< (- date (car earlier)) (- (car later) date))
(if (and earlier later) (cadr earlier))
(if (< (abs (- date (car earlier))) (else
(abs (- date (car later)))) (cadr later))))))))
(cadr earlier)
(cadr later))
(or
(and earlier (cadr earlier))
(and later (cadr later))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Functions to get one price at a given time (i.e. not time-variant). ;; Functions to get one price at a given time (i.e. not time-variant).