Searching an Array of Named Breakpoints with Javascript Find

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 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

console.log(findBreakpoint(-1));//undefined
console.log(findBreakpoint(200));//xm
console.log(findBreakpoint(500));//sm
console.log(findBreakpoint(1000));//xl

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ole Ersoy

Ole Ersoy

Founder of Firefly Semantics Corporation