Develop #8
@@ -1,5 +1,8 @@
|
|||||||
|
// TODO: Create a class from that file.
|
||||||
export default (data, keyToFind) => {
|
export default (data, keyToFind) => {
|
||||||
const result = [];
|
let result = [];
|
||||||
|
|
||||||
|
// Keep only levels with { isFruit: true }.
|
||||||
JSON.stringify(data, (_, nestedValue) => {
|
JSON.stringify(data, (_, nestedValue) => {
|
||||||
if (nestedValue && nestedValue[keyToFind]) {
|
if (nestedValue && nestedValue[keyToFind]) {
|
||||||
result.push(nestedValue);
|
result.push(nestedValue);
|
||||||
@@ -7,9 +10,50 @@ export default (data, keyToFind) => {
|
|||||||
return nestedValue;
|
return nestedValue;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Check for a Fruit structure.
|
||||||
|
result = result.filter(fruit => {
|
||||||
|
return fruit_structure(fruit, [
|
||||||
|
"color",
|
||||||
|
"description",
|
||||||
|
"expires",
|
||||||
|
"id",
|
||||||
|
"image",
|
||||||
|
"isFruit",
|
||||||
|
"name",
|
||||||
|
"price",
|
||||||
|
"taste"
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Sort fruits by id.
|
||||||
result.sort((a, b) => {
|
result.sort((a, b) => {
|
||||||
return a.id - b.id;
|
return a.id - b.id;
|
||||||
});
|
});
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check for a Fruit structure.
|
||||||
|
*
|
||||||
|
* @param {Object} obj
|
||||||
|
* @param {Array} attrs
|
||||||
|
*/
|
||||||
|
function fruit_structure(obj, attrs) {
|
||||||
|
// Check if a field is missing.
|
||||||
|
for (let i = 0; i < attrs.length; ++i) {
|
||||||
|
if (!Object.prototype.hasOwnProperty.call(obj, attrs[i])) return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check for additional fields.
|
||||||
|
Object.fromEntries(
|
||||||
|
// eslint-disable-next-line no-unused-vars
|
||||||
|
Object.entries(obj).filter(([key, value]) => {
|
||||||
|
// It mutates the initial object by reference.
|
||||||
|
if (key === "does") delete obj[key];
|
||||||
|
return attrs.includes(key);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user