Skip to content

Instantly share code, notes, and snippets.

@mewdriller
Created November 8, 2019 16:24
Show Gist options
  • Save mewdriller/ad202a66a7b614dc0c844122012e952e to your computer and use it in GitHub Desktop.
Save mewdriller/ad202a66a7b614dc0c844122012e952e to your computer and use it in GitHub Desktop.
plur.js
const getItemAt = (list, index) =>
list[Math.min(list.length - 1, Math.max(0, index))];
const plur = (...counts) => (strings, ...values) => {
let i = 0;
return strings
.reduce((result, string, index) => {
const value = values[index];
return Array.isArray(value)
? [...result, string, getItemAt(value, getItemAt(counts, i++) - 1)]
: typeof value === 'function'
? [...result, string, value(getItemAt(counts, i++))]
: [...result, string, value];
}, [])
.join('');
};
export default plur;
import plur from './plur';
const sub2 = ['singular', 'plural'];
const sub3 = ['one', 'two', 'many'];
const value = 10;
const fSub = n => (n % 2 === 0 ? 'even' : 'odd');
test('should ignore value', () => {
const actual = plur(1)`${value}`;
expect(actual).toEqual('10');
});
test('should replace option w/ first', () => {
const actual = plur(1)`${sub3}`;
expect(actual).toEqual('one');
});
test('should replace option w/ middle', () => {
const actual = plur(2)`${sub3}`;
expect(actual).toEqual('two');
});
test('should replace w/ last', () => {
const actual = plur(3)`${sub3}`;
expect(actual).toEqual('many');
});
test('should replace w/ first when under', () => {
const actual = plur(-10)`${sub3}`;
expect(actual).toEqual('one');
});
test('should replace w/ last when over', () => {
const actual = plur(10)`${sub3}`;
expect(actual).toEqual('many');
});
test('should replace using function', () => {
const actual = plur(2)`${fSub}`;
expect(actual).toEqual('even');
});
test('should replace multiple times', () => {
const actual = plur(1, 2, 3)`${sub2}, ${value}, ${sub3}, ${fSub}`;
expect(actual).toEqual('singular, 10, two, odd');
});
test('should replace using previous count', () => {
const actual = plur(1)`${sub2}, ${value}, ${sub3}`;
expect(actual).toEqual('singular, 10, one');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment