Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evilbuck/965bcc8d48bf5d1976b47e2d74a96853 to your computer and use it in GitHub Desktop.
Save evilbuck/965bcc8d48bf5d1976b47e2d74a96853 to your computer and use it in GitHub Desktop.
Adapter pattern in javascript using data munging example.
const v1Data = {
metrics: {
weightLb: 400,
heightFt: 6
},
macros: {
gramsFat: 1000
}
};
const v2Data = [400, 6, 1000];
function fetchData() {
return axios.get(url);
}
function v1Adapter(data) {
return {
weightLb: data.metrics.weightLb,
heightFt: data.metrics.heightFt,
gramsFat: data.macros.gramsFat
};
}
function v2Adapter(data) {
return {
weightLb: data[0],
heightFt: data[1],
gramsFat: data[2]
};
}
function saveDataOrAnythingElse(data) {
this.setState({ d: adapter(data) });
}
// save data with v1 format
fetchData()
.then(v1Adapter)
.then(saveDataOrAnythingElse);
// save data with v2 format
fetchData()
.then(v2Adapter)
.then(saveDataOrAnythingElse);
// The final output should always be the format:
// { weightLb, heightFt, gramsFat; }
// if we need to change the format, or the api return changes,
// then we only need to create a new adapter and plug that in. One thing to test
// and well separated from the rest of the code.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment