Can someone explain how this piece of code works? The output is a vector with the letters of input but without repetition.
var uniqueInOrder = function (iterable) {
return [].filter.call(iterable, (function (a, i) {
return iterable[i - 1] !== a
}));
}
console.log(uniqueInOrder("aaaaaBBBDSJJJJ"))
Let's break this down:
return [].filter.call(iterable,(function (a, i) { return iterable[i - 1] !== a }));
*. we are returning an Array.
*. using .filter.call(iterable,
allows us to use the Array.prototype.filter
method on the iterable
which is a string (making the function treat the string as an array of chars) as the first parameter that call
gets is the context.
*. the filter function returns a subset of the array for each element that returns true. so when doing return iterable[i - 1] !== a
every time we check if the element in index i-1
which is basically the previous element is not equal to the current element which is a
if it is not equal we return true so the a
element is a part of the subset array which is being returned.
note that the easiest way for you to understand is debug just paste this code in the developer toolbar console:
var uniqueInOrder = function (iterable)
{debugger;
return [].filter.call(iterable,(function (a, i) { return iterable[i - 1] !== a }));
}
console.log(uniqueInOrder("aaaaaBBBDSJJJJ"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With