Skip to content

Instantly share code, notes, and snippets.

@rkhaslarov
Last active May 22, 2021 17:03
Show Gist options
  • Save rkhaslarov/2cfcdcbfa8704c601cb62c25c3054571 to your computer and use it in GitHub Desktop.
Save rkhaslarov/2cfcdcbfa8704c601cb62c25c3054571 to your computer and use it in GitHub Desktop.
// Given an array of strings, return another array containing all of its longest strings.
function getAllLongestStrings(inputArray) {}
describe('getAllLongestStrings', () => {
it('should be empty if a given inputArray is empty', () => {
// Arrange
const inputArray = [];
// Act
const result = getAllLongestStrings(inputArray);
// Assert
expect(result).to.be.empty;
});
});
function getAllLongestStrings(inputArray) {
if (!inputArray.length) {
return [];
}
}
describe('getAllLongestStrings', () => {
it('should be empty if a given inputArray is empty', () => {
const inputArray = [];
const result = getAllLongestStrings(inputArray);
expect(result).to.be.empty;
});
it('should be empty if a given inputArray is not an array', () => {
const inputArray = null;
const result = getAllLongestStrings(inputArray);
expect(result).to.be.empty;
});
});
function getAllLongestStrings(inputArray) {
if (!Array.isArray(inputArray) || !inputArray.length) {
return [];
}
}
describe('getAllLongestStrings', () => {
it('should be defined as function', () => {
expect(getAllLongestStrings).to.be.a('function');
});
it('should be empty if a given inputArray is empty', () => {
const inputArray = [];
const result = getAllLongestStrings(inputArray);
expect(result).to.be.empty;
});
it('should be empty if a given inputArray is not an array (null)', () => {
const inputArray = null;
const result = getAllLongestStrings(inputArray);
expect(result).to.be.empty;
});
it('should be empty if a given inputArray is not an array (undefined)', () => {
const inputArray = undefined;
const result = getAllLongestStrings(inputArray);
expect(result).to.be.empty;
});
it('should return the longest strings in a given inputArray', () => {
const inputArray = ['aba', 'aa', 'ad', 'vcd', 'aba'];
const expected = ['aba', 'vcd', 'aba'];
const result = getAllLongestStrings(inputArray);
expect(result).to.deep.equal(expected);
});
it('should return the longest strings in a given inputArray even if it has a single element', () => {
const inputArray = ['aba'];
const expected = ['aba'];
const result = getAllLongestStrings(inputArray);
expect(result).to.deep.equal(expected);
});
});
function getAllLongestStrings(inputArray) {
if (!Array.isArray(inputArray) || !inputArray.length) {
return [];
}
const [first, ...array] = inputArray;
return array.reduce((result, current) => {
if (result[0].length === current.length) {
result.push(current);
}
if (result[0].length < current.length) {
result = [current];
}
return result;
}, [first]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment