Skip to content

Instantly share code, notes, and snippets.

@rehia
Created March 4, 2017 16:01
Show Gist options
  • Save rehia/997d9c0ef01fd408654e4cabe232a18b to your computer and use it in GitHub Desktop.
Save rehia/997d9c0ef01fd408654e4cabe232a18b to your computer and use it in GitHub Desktop.
how to go functional?
'use strict';
const _ = require('lodash');
const chai = require('chai');
const should = chai.should();
describe('filter groups behavior', () => {
const X = [
{name: 'a'},
{name: 'b'},
{name: 'c'},
{name: 'd'},
{name: 'e'},
{name: 'f'},
];
const Y = [
{name: 'b'},
{name: 'c'},
{name: 'd'}
];
const Z = ['a', 'b', 'e', 'g'];
describe('the original way', () => {
function groupsToAdd(originGroups, groupsToFilter, groupsToKeep) {
const groups = _.filter(originGroups, (elt) => _.findIndex(groupsToFilter, {name: elt.name}) < 0);
return _.filter(groups, (elt) => _.indexOf(groupsToKeep, elt.name) > -1);
}
function groupsToDelete(originGroups, groupsToFilter) {
return _.filter(originGroups, (elt) => _.indexOf(groupsToFilter, elt.name) < 0);
}
it('should keep groups in X that are in Z but not in Y', () => {
const groups = groupsToAdd(X, Y, Z);
groups.should.have.a.lengthOf(2);
groups[0].name.should.equal('a');
groups[1].name.should.equal('e');
});
it('should keep groups in X that are not in Z', () => {
const groups = groupsToDelete(X, Z);
groups.should.have.a.lengthOf(3);
groups[0].name.should.equal('c');
groups[1].name.should.equal('d');
groups[2].name.should.equal('f');
});
});
describe('the functional way', () => {
const filter = (fn) => (array) => _.filter(array, fn);
const existsIn = (array) => (fn) => (element) =>_.indexOf(array, fn(element)) > -1;
const doesNotExistsIn = (array) => (fn) => (element) => _.indexOf(array, fn(element)) < 0;
const getName = o => o.name;
const map = (array) => (fn) => array.map(fn);
function groupsToAdd(originGroups, groupsToFilter, groupsToKeep) {
const firstFilter = filter(doesNotExistsIn(map(groupsToFilter)(getName))(getName));
const secondFilter = filter(existsIn(groupsToKeep)(getName));
return secondFilter(firstFilter(originGroups));
}
function groupsToDelete(originGroups, groupsToFilter) {
return filter(doesNotExistsIn(groupsToFilter)(e => e.name))(originGroups);
}
it('should keep groups in X that are in Z but not in Y', () => {
const groups = groupsToAdd(X, Y, Z);
groups.should.have.a.lengthOf(2);
groups[0].name.should.equal('a');
groups[1].name.should.equal('e');
});
it('should keep groups in X that are not in Z', () => {
const groups = groupsToDelete(X, Z);
groups.should.have.a.lengthOf(3);
groups[0].name.should.equal('c');
groups[1].name.should.equal('d');
groups[2].name.should.equal('f');
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment