Searching an Array of Named Breakpoints with Javascript Find | Task

Ole Ersoy
Feb - 04  -  1 min

Scenario

We have the following array of named breakpoints.

interface Breakpoint { 
    name: string;
    width: number;
}

const MEDIA_BREAKPOINTS:Breakpoint[] = [
{
    name: 'l',
    width: 0
},
{
    name: 'sm',
    width: 400
},
{
    name: 'md',
    width: 576
},
{
    name: 'lg',
    width: 768
},
{
   name: 'xl',
   width: 992
}
]

We want the find the breakpoint corresponding to a given width.

Approach

We iterate over the MEDIA_BREAKPOINTS using find and if we find a breakpoint with a width that is greater than the current breakpoint and less than the width of the next breakpoint we return it.

Also if the width argument is greater than the width of the current breakpoint, and there are not more breakpoints left, we also return the breakpoint.

If there is no match we return undefined.

function findBreakpoint(width: number): Breakpoint | undefined {
    return breakpoints.find( ( p: Breakpoint, index: number ) => {
        const next = breakpoints[index + 1]
        return width >= p.width 
               && (!next || width < next.width);
        }) || undefined;
}

Demo