-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunique-in-order.js
More file actions
47 lines (36 loc) · 1.25 KB
/
Copy pathunique-in-order.js
File metadata and controls
47 lines (36 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/* 6kyu
* https://www.codewars.com/kata/5287e858c6b5a9678200083c/javascript
* Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements.
*/
// First passing Solution
var uniqueInOrder = function (iterable) {
let arr = [];
if (typeof iterable === 'object') {
if (iterable.length === 0) {
return [];
}
arr = iterable;
}
if (typeof iterable === 'string') {
arr = iterable.split('');
}
const uniqueInOrder = [];
arr.forEach((letter) => {
const includesLetter = uniqueInOrder.includes(letter);
const indexOfNextLetter =
uniqueInOrder[uniqueInOrder.lastIndexOf(letter) + 1];
if (!includesLetter) return uniqueInOrder.push(letter);
if (indexOfNextLetter !== undefined && indexOfNextLetter !== letter)
return uniqueInOrder.push(letter);
return;
});
return uniqueInOrder;
};
//Refactored Solution
var uniqueInOrder = function (iterable) {
return typeof iterable == 'object'
? iterable.filter((_, idx, array) => array[idx] !== array[idx + 1])
: iterable
.split('')
.filter((_, idx, array) => array[idx] !== array[idx + 1]);
};