Skip to content

Commit

Permalink
opt: opt ohlc size calc
Browse files Browse the repository at this point in the history
  • Loading branch information
liihuu committed Dec 11, 2023
1 parent 3f7386d commit de198fa
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
24 changes: 24 additions & 0 deletions src/common/utils/performance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
* limitations under the License.
*/

import { isFunction, isValid } from './typeChecks'

export function throttle (func: (...args: any[]) => any, wait?: number): () => void {
let previous = 0
return function () {
Expand All @@ -22,3 +24,25 @@ export function throttle (func: (...args: any[]) => any, wait?: number): () => v
}
}
}

export function memoize<R1 = any, R2 = any> (func: (...args: any[]) => R1, resolver?: (...args: any[]) => R2): (...args: any[]) => R1 {
if (!isFunction(func) || (isValid(resolver) && !isFunction(resolver))) {
throw new TypeError('Expected a function')
}
const memoized = function (...args: any[]): any {
const key = isFunction(resolver) ? resolver.apply(this, args) : args[0]
const cache = memoized.cache

if (cache.has(key)) {
return cache.get(key)
}
const result = func.apply(this, args)
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
memoized.cache = cache.set(key, result) || cache
return result
}
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
memoized.cache = new (memoize.Cache || Map)()
return memoized
}
memoize.Cache = Map
7 changes: 6 additions & 1 deletion src/view/CandleBarView.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import BarSpace from '../common/BarSpace'
import { EventHandler } from '../common/SyntheticEvent'
import { ActionType } from '../common/Action'
import { CandleType, CandleBarColor, RectStyle, PolygonType } from '../common/Styles'
import { memoize } from '../common/utils/performance'

import ChartStore from '../store/ChartStore'

Expand Down Expand Up @@ -62,6 +63,10 @@ export default class CandleBarView extends ChildrenView {
}
}

private readonly _calcOhlcSize = memoize((gapBarSpace: number) => {
return Math.min(Math.max(Math.round(gapBarSpace * 0.1), 1), 3)
})

private _drawCandleBar (
ctx: CanvasRenderingContext2D,
axis: Axis,
Expand Down Expand Up @@ -158,7 +163,7 @@ export default class CandleBarView extends ChildrenView {
styles: { color: wickColor }
})
} else {
const size = Math.min(Math.max(Math.round(barSpace.gapBar * 0.1), 1), 3)
const size = this._calcOhlcSize(barSpace.gapBar)
rects = [
{
name: 'rect',
Expand Down

0 comments on commit de198fa

Please sign in to comment.