Functional Programming in Javascript: each, keys, isObject

function each(collection, iteratee) {  for (const value of collection) {    iteratee(value);  }}
module.exports = each;
// map/index.js
const each = require('../each');
function map(collection, mapper) { const result = []; each(collection, (value) => result.push(mapper(value))); return result;}
module.exports = map;
// filter/index.jsconst each = require('../each');function filter(collection, predicate) {  const result = [];  each(collection, (value) => {    if (predicate(value)) {      result.push(value);    }  });  return result;}
module.exports = filter;
// functions.test.jstest('map', () => {  expect(map(usersMock, ({ id }) => id)).toStrictEqual([1, 2, 3, 4, 5, 6]);  expect(map(null, ({ id }) => id)).toStrictEqual([]);  expect(map({}, ({ id }) => id)).toStrictEqual([]);});test('filter', () => {  expect(filter(usersMock, ({ age }) => age > 20).length).toBe(4);  expect(filter(null, ({ age }) => age > 20).length).toBe(0);  expect(filter({}, ({ age }) => age > 20).length).toBe(0);});
object[key]
// functions.test.js(...)const keys = require('./keys');(...)test('keys', () => {  expect(keys([0, 1, 2, 3, 4, 5]))
.toStrictEqual(['0', '1', '2', '3', '4', '5']);
expect(keys({ a: 'aaa', b: 'bbb', c: 'ccc' }))
.toStrictEqual(['a', 'b', 'c']);
});
// keys/index.js
function keys(object) { return Object.keys(object);}
module.exports = keys;
// functions.test.js
test('keys', () => { (...) expect(keys(null)).toStrictEqual([]); // Fail...});
function keys(object) {  const isObject = object && typeof object === 'object';  return isObject ? Object.keys(object) : [];}
// isObject/index.jsfunction isObject(object) {  return object && typeof object === 'object';}module.exports = isObject;
// keys/index.jsconst isObject = require('../isObject');function keys(object) {  return isObject(object) ? Object.keys(object) : [];}module.exports = keys;
const keys  = require('../keys');function each(collection, iteratee) {  const collectionKeys = keys(collection);  for (const key of collectionKeys) {    iteratee(collection[key]);  }}module.exports = each;
  1. If the collection is an iterable object, the collection keys will be an array of indexes.
  2. If the collection is not an iterable object, the collection keys will be an array of object’s keys.
  3. If the collection is falsy value, the collection keys will be an empty array.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store