Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method like windows() in rust but for javascript?

Tags:

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?

windows() 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());
like image 217
Cathal Avatar asked Jan 27 '26 10:01

Cathal


1 Answers

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 - count + 1) {
    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 - count + 1) {
    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

Additionally ... here's some naive code that mimics in part the code you have in the question

Array.prototype.windows = function*(count) {
  if (typeof count !== 'number') {
    throw new Error("paramater must be a number");
  }
  let index = 0;
  while(index < this.length - count + 1) {
    yield this.slice(index, index+count);
    index++;
  }
}
const assert_eq = (a, b) => {
  a = a.toString();
  b = b.toString();
  if (a !== b) {
    throw "fail";
  }
  console.log('ok');
};

const slice = ['r', 'u', 's', 't'];
const iter = slice.windows(2);
assert_eq(iter.next().value, ['r', 'u']);
assert_eq(iter.next().value, ['u', 's']);
assert_eq(iter.next().value, ['s', 't']);
assert_eq(iter.next().done, true);

Bonus note: if you want to implement "chunks"

while(index < this.length) {
    yield this.slice(index, index+count);
    index+=count;
}
like image 139
Jaromanda X Avatar answered Jan 30 '26 01:01

Jaromanda X



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!