Last active
May 27, 2023 15:13
-
-
Save swvitaliy/0f2db30c9b36b0853396dfcaacf4535a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const range = (arr, start, len) => { | |
len = len || Math.max(0, arr.length - start); | |
const end = Math.min(arr.length, start + len); | |
return { | |
current: start, | |
length: len, | |
next: function() { | |
if (this.current >= end) return {done: true}; | |
else return {done: false, value: arr[this.current++]}; | |
}, | |
[Symbol.iterator]: function() { | |
this.current = start; | |
return this; | |
}, | |
at(i) { | |
return arr.at(start + i); | |
}, | |
}; | |
}; | |
const range_get = (arr, start, len) => { | |
len = len || Math.max(0, arr.length - start); | |
return new Proxy(range(arr, start, len), { | |
get(r, key) { | |
if (key && key.constructor === Symbol) return r[key]; | |
if (key === 'length') return len; | |
if (Number.isSafeInteger(+key)) return arr[+key + start]; | |
return r[key]; // call range methods | |
}, | |
}); | |
}; | |
let a = [1, '2', {a: 3}]; | |
let aa = range_get(a, 1); | |
console.log('a[0]=' + aa[0]); // '2' | |
console.log('a.at(0)=' + aa.at(0)); // '2' | |
console.log('a.len=' + aa.length); // 2 | |
for (let ai of aa) console.log(ai); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface IArrayRange<T> extends IterableIterator<T> { | |
current: number; | |
readonly length: number; | |
next(): IteratorResult<T>; | |
at(i: number): T | undefined; | |
} | |
function range<T>( | |
arr: T[], | |
start: number, | |
len: number = arr.length | |
): IArrayRange<T> { | |
len = len || Math.max(0, arr.length - start); | |
const end = Math.min(arr.length, start + len); | |
return { | |
current: start, | |
length: len, | |
next(): IteratorResult<T> { | |
if (this.current >= end) return {value: undefined, done: true}; | |
else return {done: false, value: arr[this.current++]}; | |
}, | |
[Symbol.iterator](): IterableIterator<T> { | |
this.current = start; | |
return this; | |
}, | |
at(i): T | undefined { | |
return arr.at(start + i); | |
}, | |
}; | |
} | |
let a = [1, '2', {a: 3}]; | |
let aa = range(a, 1); | |
console.log('a.at(0)=' + aa.at(0)); // '2' | |
console.log('a.len=' + aa.length); // 2 | |
for (let ai of aa) console.log(ai); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment