Refactoring Similar Functions to Reduce Repetition in TypeScript

Hey all,

I have these two relatively simple functions:

const calculateTotalDistance = ([leftList, rightList]: number[][]) =>
    pipe(
        leftList,
        Array.sort(Order.number),
        Array.reduce(0, (total, current, index) => total + Math.abs(current - rightList.sort(Order.number)[index]))
    )

const calculateSimilarity = ([leftList, rightList]: number[][]) =>
    pipe(
        leftList,
        Array.reduce(0, (total, leftNum) => total + (leftNum * rightList.filter(n => n === leftNum).length))
    )


As you can see they are somewhat similar, both having a pipe() and passing leftList as a first value. I was trying to play around with ways to make this less repetitive but wasn't able to find a solution that works myself. Any ideas would be appreciated!
Was this page helpful?