-
Notifications
You must be signed in to change notification settings - Fork 10.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
David Hewitt
committed
Jan 30, 2018
1 parent
85f654d
commit 9caafa7
Showing
2 changed files
with
49 additions
and
15 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,38 +1,65 @@ | ||
const _ = require(`lodash`) | ||
|
||
class Normalizer { | ||
|
||
/** | ||
* Normalizer Constructor | ||
* | ||
* @param {Array} entitys | ||
* @param {Object} args | ||
* @return {Object} this | ||
*/ | ||
constructor(entitys, args) { | ||
this.entitys = entitys | ||
this.args = args | ||
this.normalizers = [] | ||
this.queue = [] | ||
} | ||
|
||
/** | ||
* Set Normalizers | ||
* | ||
* @param {Function} normalizer | ||
* @param {null|Number} priority | ||
* @return {Object} | ||
*/ | ||
set(normalizer, priority = null) { | ||
// if the priority is null push last | ||
this.normalizers.push({ | ||
let property = priority === null ? `queue` : `normalizers` | ||
|
||
this[property].push({ | ||
normalizer, | ||
priority, | ||
}) | ||
|
||
return this | ||
} | ||
|
||
/** | ||
* Normalize the entities | ||
* | ||
* @return {Array} | ||
*/ | ||
async normalize() { | ||
let ordered = this.normalizers.sort((a, b) => a.priority - b.priority) | ||
|
||
for (let i = 0; i < ordered.length; i++) { | ||
var normalizedEntities = await ordered[i].normalizer(this.entitys, this.args) | ||
|
||
if (typeof normalizedEntities !== `object`) { | ||
continue | ||
} | ||
|
||
this.entitys = normalizedEntities | ||
var normalizers = this.getNormalizers() | ||
for (let i = 0; i < normalizers.length; i++) { | ||
this.entitys = await normalizers[i].normalizer(this.entitys, this.args) | ||
} | ||
|
||
return this.entitys | ||
} | ||
|
||
/** | ||
* Concat the queue and prioritised normalizers | ||
* | ||
* @return {Array} | ||
*/ | ||
getNormalizers() { | ||
return _.concat( | ||
this.normalizers.sort((a, b) => a.priority - b.priority), | ||
this.queue | ||
) | ||
} | ||
|
||
} | ||
|
||
module.exports = Normalizer |