Skip to content

Instantly share code, notes, and snippets.

@beardedtim
Last active April 17, 2017 01:15
Show Gist options
  • Save beardedtim/99aabe3b08ba58037b20d65343ed9d20 to your computer and use it in GitHub Desktop.
Save beardedtim/99aabe3b08ba58037b20d65343ed9d20 to your computer and use it in GitHub Desktop.
Weird Ramda Stuff
import counter from '../';
describe('counter', () => {
test('counter returns an array of objects with keys `value`, `count`, and `indexes`', () => {
const words = ['a', 'b', 'a', 'c', 'a'];
counter(words).forEach((word) => {
expect(word.count).toBeDefined();
expect(word.value).toBeDefined();
expect(word.indexes).toBeDefined();
});
});
test('counter returns an array of objects with value of string', () => {
const words = ['a', 'b', 'a', 'c', 'a'];
counter(words).forEach((word) => {
expect(typeof word.value).toBe('string');
});
});
test('counter returns an array of objects with count of number', () => {
const words = ['a', 'b', 'a', 'c', 'a'];
counter(words).forEach((word) => {
expect(typeof word.count).toBe('number');
});
});
test('counter returns an array of objects with indexes of array', () => {
const words = ['a', 'b', 'a', 'c', 'a'];
counter(words).forEach((word) => {
expect(Array.isArray(word.indexes)).toBe(true);
});
});
});
describe('counter usage', () => {
test('counter counts the words and their index in the given list of words', () => {
const words = ['a', 'b', 'a', 'c', 'a'];
expect(counter(words)).toEqual([
{
value: 'a',
count: 3,
indexes: [0, 2, 4],
},
{
value: 'b',
count: 1,
indexes: [1],
},
{
value: 'c',
count: 1,
indexes: [3],
},
]);
});
});
export default words => words.reduce((final, word, index) => {
const found = final.find(({ value }) =>
value.toLowerCase() === word.toLowerCase()
);
if (found) {
found.count++;
found.indexes.push(index);
} else {
final.push({
value: word.toLocaleLowerCase(),
count: 1,
indexes: [index],
});
}
return final;
}, []);
import { reduce, addIndex } from 'ramda';
const reduceWithIndex = addIndex(reduce);
export default reduceWithIndex((final, word, index) => {
const found = final.find(({ value }) =>
value.toLowerCase() === word.toLowerCase()
);
if (found) {
found.count++;
found.indexes.push(index);
} else {
final.push({
value: word.toLocaleLowerCase(),
count: 1,
indexes: [index],
});
}
return final;
}, []);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment