3

I'd like to understand how Arrays are specified and built.

I'm mixing arrays with extra methods and trying to pass in Array.isArray(). I can pass instanceof and Poly-filled isArray

var protoOfArray = Object.getPrototypeOf([])

var tools4Arrays = Object.defineProperty(
  Object.create(protoOfArray),
  'sum', {
    'value': function sum() {
      return this.reduce((a, b) => a + b, 0)
    }
  }
)
tools4Arrays[Symbol.toStringTag] = 'Array'

var fakeArray = Object.defineProperty(
  Object.create(
    tools4Arrays
  ),
  'length', {
    'value': 0,
    'writable': true
  }
)

console.log(`fakeArray instanceof Array: ${fakeArray instanceof Array}`)
console.log(`polyfill.isArray(fakeArray): ${Object.prototype.toString.call(fakeArray) === '[object Array]'}`)
console.log(`Array.isArray(fakeArray): ${Array.isArray(fakeArray)}`)

If I use: fakeArray = Object.setPrototypeOf([], tools4Arrays) the last log is true too.

What else separates arrays of objects? Can I mock it?

2
  • Do you mean what else separates arrays from objects? Or are you asking something specifically regarding arrays containing objects? Commented Jan 5, 2019 at 15:15
  • @joe: It's not about an array of objects. Can I build an array editing from an object? Whats transformations need to construct an array over regulars object? My fakeArray don't pass Array.isArray(). How do I get closer? Are this transitions possible? Or are array irreducible from objects? Commented Jan 5, 2019 at 19:29

2 Answers 2

1

In order to mimic an Array you'd have to pass the internals of isArray which has the following checks (defined here):

  1. If Type(arg) is not Object, return false.
  2. If the value of the [[Class]] internal property of arg is "Array", then return true.
  3. Return false.

The Type here appears to be the same as instanceof, which you've been able to pass just fine. However, the second step points at some internal [[Class]] property, which I'm not sure we have write access to.

Sign up to request clarification or add additional context in comments.

2 Comments

its give me some paths to search:change class Symbol.species
es9 isArray talks about exotics and proxy arrays I did not even know.
0

I got what I needed, but I still do not have the answer... A fake array is very slower than a regular array, maybe have many internal optimizations and mimic it will lose that speed.

subclass an array without a class

my use case

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.