Skip to content

Commit

Permalink
Map-based implementation of permutationOf
Browse files Browse the repository at this point in the history
Fixes moll#38

This should make `permutationOf` work correctly for arrays containing values other than strings, numbers and booleans.
  • Loading branch information
radekn committed Jan 31, 2016
1 parent aec8673 commit a643e71
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions must.js
Original file line number Diff line number Diff line change
Expand Up @@ -611,12 +611,26 @@ function isPermutationOf(actual, expected) {
if (!Array.isArray(actual) || !Array.isArray(expected)) return false
if (actual.length !== expected.length) return false

actual = actual.slice().sort()
expected = expected.slice().sort()
for (var i = 0; i < actual.length; i++) {
if (actual[i] !== expected[i]) return false
var expectedElementCount = new Map()
for (var i = 0; i < expected.length; ++i) {
var element = expected[i]
var count = expectedElementCount.get(element) || 0
expectedElementCount.set(element, count + 1)
}

for (var i = 0; i < actual.length; ++i) {
var element = actual[i]
var count = expectedElementCount.get(element)
if (!count) return false
if (count === 1) {
expectedElementCount.delete(element)
} else {
expectedElementCount.set(element, count - 1)
}
}

if (expectedElementCount.size) return false

return true
}

Expand Down

0 comments on commit a643e71

Please sign in to comment.