Skip to content

Commit

Permalink
chapter 02: refactoring genericEncoder to use the encoder factory
Browse files Browse the repository at this point in the history
  • Loading branch information
devcorpio committed Mar 30, 2019
1 parent a08b781 commit a14b46f
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions chapter-02-the-open-closed-principle/refactor/genericEncoder.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
function genericEncoder(encoderFactory) {
function encodeToFormat(data, format) {
const encoder = encoderFactory.createForFormat(format);

data = prepareData(data, format);

return encoder.encode(data);
}

function prepareData(data, format) {
switch (format) {
case 'json': {
data = this.forceArray(data);
data = this.fixKeys(data);
}
case 'xml': {
data = this.fixAttributes(data);
break;
}
default: {
throw new Error('Format not supported');
}
}

return data;
}

return {
encodeToFormat,
};
}

module.exports = genericEncoder;

0 comments on commit a14b46f

Please sign in to comment.