Skip to content

Commit c2a816f

Browse files
committed
feat: add arrays similar solution
1 parent ca96aef commit c2a816f

File tree

3 files changed

+62
-0
lines changed

3 files changed

+62
-0
lines changed

codewars/arrays-similar/README.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# Arrays Similar
2+
3+
## Description
4+
5+
Write a function that determines whether the passed in sequences are similar. Similar means they contain the same elements, and the same number of ocurrences of elements.
6+
7+
```js
8+
var arr1 = [1, 2, 2, 3, 4],
9+
arr2 = [2, 1, 2, 4, 3],
10+
arr3 = [1, 2, 3, 4],
11+
arr4 = [1, 2, 3, '4']
12+
```
13+
14+
```js
15+
arraysSimilar(arr1, arr2); // should equal true
16+
arraysSimilar(arr2, arr3); // should equal false
17+
arraysSimilar(arr3, arr4); // should equal false
18+
```

codewars/arrays-similar/solution.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
const arraysSimilar = (arr1, arr2) => {
2+
if (arr1.length !== arr2.length) {
3+
return false;
4+
}
5+
arr1 = arr1.sort((a, b) => a - b);
6+
arr2 = arr2.sort((a, b) => a - b);
7+
return arr1.every((el, index) => el === arr2[index]);
8+
};
9+
10+
module.exports = arraysSimilar;
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
const arraysSimilar = require('./solution');
2+
3+
describe('Arrays Similar', () => {
4+
const testCases = [
5+
{
6+
input: [[1, 2, 3, 4, 5], [2, 3, 4, 1, 5]],
7+
output: true,
8+
},
9+
{
10+
input: [[1, 2, 3, 4, 5, 6, 7, 8, 9, 0], [5, 2, 3, 4, 7, 8, 9, 1, 0, 6]],
11+
output: true,
12+
},
13+
{
14+
input: [[1, 2, 3, '4', 5], [2, 3, 4, '1', 5]],
15+
output: false,
16+
},
17+
{
18+
input: [[1, 2, 3, '3', 5], [2, 3, 4, '1', 5]],
19+
output: false,
20+
},
21+
{
22+
input: [[2, 3], [1, 2, 4]],
23+
output: false,
24+
},
25+
];
26+
27+
it('should return a boolean type', () => {
28+
expect(typeof arraysSimilar([1, 2], [2, 1])).toBe('boolean');
29+
});
30+
31+
it.each(testCases)('should return $output', (testCase) => {
32+
expect(arraysSimilar(...testCase.input)).toBe(testCase.output);
33+
});
34+
});

0 commit comments

Comments
 (0)