FP Style fast row

const quickSort = (list) => {
    if (!list || !list.length) return [];
    if (list.length === 1) return list;

    const [middle, ...rest] = list;
    const reducer = (acc, x) => (
        x <= middle ? 
        { ...acc, left: [...acc.left, x] } : 
        { ...acc, right: [...acc.right, x] }
    );
    const { left, right } = rest.reduce(reducer, { left: [], right: [] });
    return [...quickSort(left), middle, ...quickSort(right)];
};

const list = [2, 3, 1, 8, 8, 1, 2, 18, 6, 2333];
const sorted = quickSort(list); // [ 1, 1, 2, 2, 3, 6, 8, 8, 18, 2333 ]

 

Guess you like

Origin www.cnblogs.com/little-ab/p/11123443.html