Skip to content

Instantly share code, notes, and snippets.

@martinheidegger
Created September 3, 2018 05:37
Show Gist options
  • Save martinheidegger/0ee4fb456dc70f6121ef1bd984c4328a to your computer and use it in GitHub Desktop.
Save martinheidegger/0ee4fb456dc70f6121ef1bd984c4328a to your computer and use it in GitHub Desktop.
Construct Huge arrays made out of parts ^_^
function partArray (...parts) {
let lengths = parts.map(part => part.length)
let length = lengths.reduce((total, length) => total + length)
function* iterator () {
for (const part of parts)
for (const value of part) yield value
}
function item (index) {
let partIndex = 0
for (const part of parts) {
if (index < part.length) {
return part[index]
}
index -= lengths[partIndex]
partIndex += 1
}
}
return new Proxy([], {
get (obj, key) {
if (key === Symbol.iterator) {
return iterator
}
if (key === 'length') {
return length
}
if (key === 'toString') {
return function () {
let result = '[ '
for (var i = 0; i < length; i ++) {
if (i !== 0) {
result += ', '
}
result += item(i)
}
return result + ' ]'
}
}
if (key === 'push') {
return function (value) {
parts.push(value)
lengths.push(1)
return length++
}
}
if (key === 'concat') {
return function (...values) {
const newParts = parts.concat()
newParts.push(values)
return partArray(...newParts)
}
}
// TODO: implement the rest...
if (typeof key === 'symbol' || isNaN(key) || key >= length || key < 0) {
return undefined
}
return item(key | 0)
}
})
}
function multiply (input, count) {
input = input.concat()
const parts = []
for (let i = 0; i<count; i++) {
parts.push(input)
}
return partArray(...parts)
}
const input = ['a', 'b', 'c']
const result = multiply(input, 3)
console.log(result instanceof Array)
console.log(Array.isArray(result))
console.log(result.length)
console.log(result[3])
console.log(result[-1])
input.pop()
input.push('d')
input.push('e')
console.log(result.length)
console.log(result[3])
console.log(result.concat('e').toString())
console.log(result.push('f'))
for (const char of result) {
console.log(char)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment