Sobes.tech
Middle+

Implement a function mapper that takes data (source), fields (fields), a filter (filter), and sorting (order). It should: validate parameters (fields should be an array, source/filter/order should be functions, fields should be present in the data), get data via source(), filter through filter, sort through order, and return only the requested fields from fields.

sobes.tech AI

Answer from AI

javascript function mapper({ source, fields, filter, order }) { // Parameter validation if (!Array.isArray(fields)) { throw new TypeError('fields must be an array'); } if (typeof source !== 'function') { throw new TypeError('source must be a function'); } if (typeof filter !== 'function') { throw new TypeError('filter must be a function'); } if (typeof order !== 'function') { throw new TypeError('order must be a function'); }

const data = source();

if (!Array.isArray(data)) { throw new TypeError('source must return an array of objects'); }

// Check that all fields in fields exist in data for (const field of fields) { if (!data.every(item => field in item)) { throw new Error(Field '${field}' is missing in data); } }

// Filtering const filtered = data.filter(filter);

// Sorting const sorted = filtered.sort(order);

// Selecting only the required fields return sorted.map(item => { const result = {}; for (const field of fields) { result[field] = item[field]; } return result; }); }

Example usage:

const source = () => [
  { id: 1, name: 'Alice', age: 30 },
  { id: 2, name: 'Bob', age: 25 },
  { id: 3, name: 'Charlie', age: 35 }
];

const fields = ['id', 'name'];
const filter = item => item.age >= 30;
const order = (a, b) => a.name.localeCompare(b.name);

const result = mapper({ source, fields, filter, order });
console.log(result);
// [{ id: 1, name: 'Alice' }, { id: 3, name: 'Charlie' }]
Implement a function mapper that takes data (source)… - sobes.tech