Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Method like windows() in rust but for javascript?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading