All files / utils attract.ts

100% Statements 10/10
100% Branches 4/4
100% Functions 3/3
100% Lines 7/7

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 225x           8x         9x   9x 9x         2x 2x  
const identity = (v: any): any => v
 
/**
 * Creates an attractor that, given a strength constant, origin and value,
 * will calculate value as attracted to origin.
 */
export const createAttractor = (alterDisplacement: Function = identity) => (
    constant: number,
    origin: number,
    v: number
) => {
    const displacement = origin - v
    const springModifiedDisplacement =
        -(0 - constant + 1) * (0 - alterDisplacement(Math.abs(displacement)))
    return displacement <= 0
        ? origin + springModifiedDisplacement
        : origin - springModifiedDisplacement
}
 
export const attract = createAttractor()
export const attractExpo = createAttractor(Math.sqrt)