Compara duas listas em Javascript usando conjuntos.
const areListsEqual = (firstList, secondList) => {
if (firstList.length !== secondList.length) {
return false
}
const firstListAsSet = new Set(firstList)
const secondListAsSet = new Set(secondList)
if (firstListAsSet.size !== secondListAsSet.size) {
return false
}
for (const item of firstListAsSet) {
if (!secondListAsSet.has(item)) {
return false
}
}
return true
}
module.exports = {
areListsEqual,
}
Testes:
const { areListsEqual } = require('./lists')
describe('areListsEqual', () => {
it('should return true for two equal lists', () => {
const firstList = [1, 2, 3]
const secondList = [1, 2, 3]
expect(areListsEqual(firstList, secondList)).toBe(true)
})
it('should return false for two lists with different lengths', () => {
const firstList = [1, 2, 3]
const secondList = [1, 2, 3, 4]
expect(areListsEqual(firstList, secondList)).toBe(false)
})
it('should return false for two lists with different elements', () => {
const firstList = [1, 2, 3]
const secondList = [1, 2, 4]
expect(areListsEqual(firstList, secondList)).toBe(false)
})
it('should return true for two lists with the same elements in different order', () => {
const firstList = [1, 2, 3]
const secondList = [3, 2, 1]
expect(areListsEqual(firstList, secondList)).toBe(true)
})
it('should return true for two lists with the same elements in different order and repeated elements', () => {
const firstList = [1, 2, 3, 3]
const secondList = [3, 2, 1, 3]
expect(areListsEqual(firstList, secondList)).toBe(true)
})
it('should return false for two lists with the same elements in different order and different number of repeated elements', () => {
const firstList = [1, 2, 3, 3]
const secondList = [3, 2, 1, 3, 3]
expect(areListsEqual(firstList, secondList)).toBe(false)
})
})