Playing with Algorithms and Styles: findMax

node v8.17.0
version: 4.0.0
endpointsharetweet
function findMaxImperative(...args) { let largest; const stack = args; while (stack.length > 0) { const candidate = stack.pop(); if (Array.isArray(candidate)) { stack.push(...candidate); } else if (largest === undefined || candidate > largest) { largest = candidate; } } return largest; } findMaxImperative(1, 10, [5, 9], [12, [900], [34, 56, 7600]], 34);
function findMaxRecursive(...args) { let largest; for (let candidate of args) { if (Array.isArray(candidate)) { candidate = findMaxRecursive(...candidate); } if (largest === undefined || candidate > largest) { largest = candidate; } } return largest; } findMaxRecursive(1, 10, [5, 9], [12, [900], [34, 56, 7600]], 34);
function flatten(...args) { return args.reduce((acc, item) => [ ...acc, ...(Array.isArray(item) ? flatten(...item) : [item]) ], []); }
function findMaxFunctional(...args) { const largest = (a, b) => ( [a = b, b = a] = [a, b], a > b ? a : b ); return flatten(args).reduce(largest, undefined); } findMaxFunctional(1, 10, [5, 9], [12, [900], [34, 56, 7600]], 34);
function findMaxFunctionalSort(...args) { const ascendingOrder = (a, b) => (a < b ? -1 : a > b ? 1 : 0); return flatten(args) .sort(ascendingOrder) .pop(); } findMaxFunctionalSort(1, 10, [5, 9], [12, [900], [34, 56, 7600]], 34);
Loading…

no comments

    sign in to comment