Photo by Pawel Czerwinski on Unsplash
Proxy cool array methods
Re implement cool array methods with js proxy
Here is a list of array operations that you can review, such as blitz.
From now on, we'll be working with these arrays.
const numbers: number[] = [0, 1, 2];
const alphabet: string[] = ['a', 'b', 'c'];
Indexing
numbers.indexOf(2) // 2
numbers.indexOf(10) // -1
numbers[5] // undefined
numbers[-1] // undefined
numbers[Infinity] // undefined
numbers['1'] // 1
Bonus tips (negative index)
numbers.at(-1); // 2, (builtin at method)
const coolNumbers = new Proxy(numbers, {
get(target, props) {
const index: number = +(<string>props)
if (index < 0)
return Reflect.get(target, index + target.length)
return Reflect.get(target, props)
},
})
coolNumbers[-1] // 2
Cool operation on an array
flat, joining with tagged templates
// **flat** ES2019
const nested = [0, [1], [[2]], [[[3]]], [[[[4], 3], 2], 1]]
nested.flat() // [ 0, 1, [ 2 ], [ [ 3 ] ], [ [ [4], 3 ], 2 ], 1 ], default level 1
nested.flat(3) // [0, 1, 2, 3, [ 4 ], 3, 2, 1]
nested.flat(Infinity) // [0, 1, 2, 3, 4 , 3, 2, 1]
// joining
alphabet.join(',') // a,b,c
// @ts-ignore
alphabet.join`,` // a,b,c
alphabet.toString() // a,b,c
Make a similar cool python range method with proxy
/* cool python range */
const range = (start: number, stop?: number, step?: number) => {
if (step === undefined) step = 1
if (stop === undefined) {
stop = start
start = 0
}
return Array.from(
{ length: (stop - start) / step },
(_, i) => start + i * step!,
)
}
for (const i of range(5, 10)) console.log(i)
// 5, 6, 7, 8, 9