Is there a method in javascript that does the same thing as windows in rust?
I want to iterate over an array in js comparing 2 values each time like you can with windows() in rust but not sure if there is a method for this.
Anyone know a method or a similar way to recreate it?
EXAMPLE:
let slice = ['r', 'u', 's', 't'];
let mut iter = slice.windows(2);
assert_eq!(iter.next().unwrap(), &['r', 'u']);
assert_eq!(iter.next().unwrap(), &['u', 's']);
assert_eq!(iter.next().unwrap(), &['s', 't']);
assert!(iter.next().is_none());
Thanks
>Solution :
generator function is a good fit for this
function* windows(array, count=1) {
if (typeof count !== 'number') {
throw new Error("paramater must be a number");
}
let index = 0;
while(index < array.length) {
yield array.slice(index, index+count);
index++;
}
}
const x = windows(['r', 'u', 's', 't'], 2);
[...x].forEach(v=>console.log(v))
Additionally, if you aren’t averse to adding methods to built-in types
You can do it like this
Array.prototype.windows = function*(count) {
if (typeof count !== 'number') {
throw new Error("paramater must be a number");
}
let index = 0;
while(index < this.length) {
yield this.slice(index, index+count);
index++;
}
}
const array = ['r', 'u', 's', 't'];
[...array.windows(2)].forEach(v=>console.log(v))
This way, all Array’s just have the windows method