Skip to content

Instantly share code, notes, and snippets.

@darotar
Created February 15, 2021 11:25
Show Gist options
  • Save darotar/7d2cb8a6cd51743bde55edaa025ea4b7 to your computer and use it in GitHub Desktop.
Save darotar/7d2cb8a6cd51743bde55edaa025ea4b7 to your computer and use it in GitHub Desktop.
ListAdapter
/* The function takes some set of data (preferable structural types), and assuming some
* default expectations of output (in my case, fields to be 'text' and 'value - returns back adapter structure */
/* Used GOF Patterns - Adapter and Strategy */
export default function adaptToList(data = [], textField = '', valueField = '') {
if (!data.length) {
return [];
}
return data.map(item => {
if (typeof item === 'object') {
if (Array.isArray(item)) {
return nestedArrayStrategy(item);
} else {
return objectStrategy(item, textField, valueField);
}
} else {
return primitiveStrategy(item);
}
});
};
function nestedArrayStrategy(item) {
return {
text: item[0],
value: item[1],
};
}
function objectStrategy(item = {}, textField = '', valueField = '') {
if (!textField || !valueField) {
if (item.text && item.value) {
return {
text: item.text,
value: item.value,
};
}
return {};
}
return {
text: item[textField],
value: item[valueField],
};
}
function primitiveStrategy(item = '') {
return {
text: item,
value: item,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment