Skip to content

Instantly share code, notes, and snippets.

@crtl
Created July 5, 2019 09:48
Show Gist options
  • Save crtl/46df038fdf7dd2ef1a1f01eb0b9aaa60 to your computer and use it in GitHub Desktop.
Save crtl/46df038fdf7dd2ef1a1f01eb0b9aaa60 to your computer and use it in GitHub Desktop.
Simple script to retrieve values based on mediaQueries. Can be adapted to work with any comparison conditions. Returns the first match only.
const WINDOW_HEIGHT = 1080;
const WINDOW_WIDTH = 1920;
/**
* Comparators check against WINDOW_WIDTH and WINDOW_HEIGHT vars, but can be any check you want.
* v refers to the value of the condition
**/
const comparators = {
width: (v) => WINDOW_WIDTH === v,
height: (v) => WINDOW_HEIGHT === v,
minWidth: (v) => WINDOW_WIDTH >= v,
minHeight: (v) => WINDOW_HEIGHT >= v,
maxWidth: (v) => WINDOW_WIDTH <= v,
maxHeight: (v) => WINDOW_HEIGHT <= v
};
//Cache keys
const comparatorKeys = Object.keys(comparators);
/**
*
* @param Arrray mediaQueries First match counts.
* @returns {*} The .data of the matched query or null
*/
function media_query(mediaQueries) {
let result = mediaQueries.find(function (config) {
return Object.keys(config)
.filter(key => comparatorKeys.indexOf(key) >= 0)
.reduce((truthy, key) => {
//If a previous condition has failed keep result
if (!truthy) return truthy;
//Call comparator
return truthy = comparators[key].call(null, config[key]), truthy;
}, true)
});
return result ? result.data : null;
}
let result = media_query([
{
maxWidth: 1820,
maxHeight: 1080,
data: {
query: 1
}
},
{
width: 1000,
data: {
query: 2,
}
},
{
minWidth: 1000,
data: {
query: 3
}
}
]);
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment