ホーム 暮らし Trying to define a Tuple in Node.js!

Trying to define a Tuple in Node.js!

八木 麻衣 八木 麻衣 • 更新: • 公開: • 読了約 80 分
目次

Hello again, it's Keshitan. This time, I wrote an article titled

“Trying to define a Tuple in Node.js!”

As most of you reading this article probably know, as of January 2023, the Tuple data type implemented in other programming languages has not been implemented in JavaScript.

However, in such a situation, you might feel that "I want Tuples in JavaScript too!"

“Then let's just make them!!!!”

...is the theme of this article. I have summarized the motivation for creating them, the thoughts and skills that led to their completion, the problems I encountered, and so on, in this article in an orderly fashion.

Also, I personally believe that the content of this article is not limited to Tuples, but can be applied to "the general act of creating your own library (class)." If you are interested, I hope you will read it.

Now, here is the table of contents!

Execution environment and verification environment

First, as a major premise, this article is written under the following environment [1]:

  • Node.js v18.12.1

  • npm 8.19.2

  • Python 3.11.0

  • TypeScript Version 4.9.4

  • Windows 11 22H2 (OS Build Version 10.0.22000.1335)

$ node -v
v18.12.1

$ npm -v
8.19.2

$ python --version
Python 3.11.0

$ npx tsc -v
Version 4.9.4

$ ver
Microsoft Windows [Version 10.0.22000.1335]

What is a Tuple?

n4f4f32f3f291

Tuple refers to a data type similar to an array that groups together an ordered set. Although implementation varies by language specification, it is implemented in many languages such as C#, C++, Python, and TypeScript. [2]

However, on the other hand, there is no tuple at the language level in JavaScript, and arrays (Array) and typed arrays (TypedArray) are implemented. As a feature of JavaScript, you can prevent redefinition and reassignment by using const for variable declaration. Although redefinition and reassignment are covered, the definition and modification of properties are still possible:

/
 * RGBカラーモデルにおけるRed(赤)
 /
const RED = [255, 0, 0]

RED[0] = -200
console.log(RED) //=> [ -200, 0, 0 ]
/
 * RGBカラーモデルにおけるRed(赤)
 */
const RED = Uint8Array.of(255, 0, 0)

RED[0] = -200
console.log(RED) //=> Uint8Array(3) [ 56, 0, 0 ]

A famous solution for this is to freeze the Array object with Object.freeze(). Under strict mode, the code above will throw an error:

"use strict"
/
 * RGBカラーモデルにおけるRed(赤)
 */
const RED = [255, 0, 0]
Object.freeze(RED)
RED[0] = -200
/     ^

TypeError: Cannot assign to read only property '0' of object '[object Array]'/

Also, if the editor is Visual Studio Code, the type inference derived from TypeScript works well, and destructive methods are excluded from the candidates in advance in IntelliSense:

 In other words, in this case, concat and map and other non-destructive methods [3] can be used without any issues.

 However

“Although I thought of it as an 'immutable [4]Array', the methods return a 'normal Array'”

This feels a bit uncomfortable.

 The concept of a 'Tuple', which is the subject of this article, fits this vision of an 'immutable Array'. To define a tuple in Node.js, I would like to look at implementation examples in Python and TypeScript where tuples are implemented.

 I'm not very familiar with tuples other than Python and TypeScript...

Implementation examples in Python and TypeScript

Python tuples are

This is how it is written in code:

t0 = tuple()
t0 = ()

t1 = tuple([1])
t1 = (1,)

t2 = tuple([1, "2"])
t2 = (1, "2")

t3 = tuple([1, "2", 3.0])
t3 = (1, "2", 3.0)

type(t0)  # -> <class 'tuple'>
0 in t1   # -> False
2 in t2   # -> True
t3[2]     # -> 3.0
t3[-2]    # -> "2"

TypeScript tuples are

This is how it is written in code:

const t0: readonly [] = []
// const t0 = []

const t1: readonly [number] = [1]
// const t1 = [1]

const t2: readonly [number, string] = [1, "2"]
// const t2 = [1, "2"]

const t3: readonly any[] = [1, "2", 3]
// const t3 = [1, "2", 3]

typeof t0           //=> "object"
t1 instanceof Array //=> true
0 in t2             //=> true
t3[2]               //=> 3
t3[-1]              //=> undefined
t3.at(-1)           //=> 3

 Based on the above, I think the design perspectives can be roughly listed as follows (this is just one example):

 When actually defining it, it is inseparable from built-in objects like Array (ArrayLike) and JavaScript language specifications, so it must be defined in a way that ensures consistency.

 Let's take a break here; there is an interesting story that I'm sure you will all like.

Records and Tuples 【Stage: 2 】

 I mentioned earlier that 'JavaScript does not have tuples', but strictly speaking, that is 'at this stage'. JavaScript is also undergoing updates, and discussions are being held with experts and others. Among these, what is expected to be implemented is 'Records and Tuples'.

 ECMAScript proposal for the Record and Tuple value types. suggests the addition of new data types, Record and Tuple, and the concept is explained as follows:

 In other words, a Tuple is like an "immutable Array," where what can be held as a value is limited to "primitives + Tuples, Records" and cannot be changed. A Record is implemented like a dictionary type of the same kind. It is said that the code will be written as follows:

const tuple = #[0, 1, 2]
// Tuple(...[0, 1, 2])

const record = # x: 10, y: 20 
// Record( x: 10, y: 20 )

Note's syntax highlighting is not supported, so it is commented out

 Object.freeze() 's #example and the link mentioned earlier #Why deep immutability? also mention that objects frozen with Object.freeze() are shallowly frozen. In the code example below, the treasure hidden deep inside is stolen despite being frozen:

const SEA = 
  shallow: 
    deep: "My Treasure"
  

Object.freeze(SEA)
SEA.shallow.deep = ""
console.log(SEA)
//=>  shallow:  deep: ''  

 Therefore, Tuples and Records have limited their elements to only primitives (including Tuples and Records), which gives them deep immutability without any uncertainty. Personally, I think this is a very good philosophy.

Node.js for creating a Tuple!

 We have taken a rough look at implementation examples in other languages (sample size 2) and the planned tuples in JS. Based on that, what kind of implementation would be desirable if we were to "define a Tuple in Node.js"?

 In this article, I have thought about the specifications as follows. I will also explain the problems when incorporating them into code.

Specification Design

 The Tuple I am aiming for this time is considered with the following specifications:

 Accordingly, the way of writing code will be limited. In particular, the specification that is similar to Array,

✅Declaration possible both with and without new

 is very "troublesome".

Class declaration? Function declaration?

 Among the conditions, there is

 but what does this mean? To make it easier to understand, let's look at an example using a class expression. Let's compare with the following code:

//Arrayを継承して、変数はprivateでないもの
let Tuple = class extends Array 
  constructor(...items) 
    super(...items)
    this.items = items
  
  get length () 
    return this.items.length
  


let tuple = new Tuple(1, 2)
tuple instanceof Array //=> true
tuple instanceof Tuple //=> true

tuple.items            //=> [ 1, 2 ]
tuple.length           //=> 2
tuple.items = "Array??"
tuple.length           //=> 7

//要件を満たすもの
Tuple = class 
items = []
  constructor(...items) 
    this.#items = items
  
  get length () 
    return this.#items.length
  


tuple = new Tuple(1, 2)
tuple instanceof Array //=> false
tuple instanceof Tuple //=> true

tuple.items            //=> undefined
tuple.length           //=> 2
tuple.items = "Array??"
tuple.length           //=> 2

tuple.#items = "Array??"
/   ^

SyntaxError: Private field '#items' must be declared in an enclosing class/

 The former extends Array, so instanceof Array is true, and the length value is messed up due to rewriting internal variables.

 The fact that instanceof Array is true means it inherits from the prototype [5], allowing Array methods to be used, which slightly contradicts the significance of an "immutable Array." Also, having exposed properties can lead to writing unintended code.

 In that respect, the latter does not inherit from Array, and by using private class features, it successfully avoids the problem. Using class declarations provides benefits in terms of inheritance-related operations and encapsulation of internal variables. [6]

 However, there is a condition that neither the former nor the latter satisfies, which is the one I previously called "troublesome"

—that condition. You can see it if you actually try it:

let ary = new Array(1, 2)
let array = Array(1, 2)
let tpl = new Tuple(1, 2)
let tuple = Tuple(1, 2)
/          ^

TypeError: Class constructor Tuple cannot be invoked without 'new'/

 In other words, as long as it is declared as a "class", "new" is indispensable, meaning you are cursed to always have to attach "new".........

Is there any way to get rid of new...?

 ...And that brings us to function declarations.

Good old function declarations

 If you ask whether I want to get rid of "new" even at the cost of losing the benefits of classes, that's a fair point, but there is a certain romance to it. JavaScript, a prototype-based language, originally had no concept of classes and instead used functions as follows:

"use strict"

function Tuple(...items) 
  this._items = items

  return this


let double = new Tuple(1, 2)
let triple = new Tuple(1, 2, 3)

/console.log(double, triple) =>
  Tuple  _items: [ 1, 2 ] 
  Tuple  _items: [ 1, 2, 3 ] 
/

 As a convention for the writing style above, it is customary to prefix variables you want to treat as private with an "_". This is intended to physically prevent unintended access to variables (though in reality, they are still normally accessible).

 This is common as a traditional way of writing in JS, but if left as is, "new" will stick around. By using new.target inside function Tuple, it becomes possible to declare it without new, making it a reality:

"use strict"

function Tuple(...items) 
  if (new.target) 
    this._items = items

    return this
  else 
    return new Tuple(...items)
  

let double = new Tuple(1, 2)
let triple = Tuple(1, 2, 3)

/console.log(double, triple) =>
  Tuple  _items: [ 1, 2 ] 
  Tuple  _items: [ 1, 2, 3 ] 
/

 Now that we have resolved the declaration issue, let's look at making variables private.

Making variables private?

 Suppose Tuple has an internal variable called items and we want to define static/instance methods to manipulate it. Specifically,

is what we assume. Among these, let's first consider the definition of instance methods. The first thing that comes to mind is defining methods directly on the "this" returned by new Tuple:

"use strict"

function Tuple(...items) 
  if (new.target) 
    this.length = items.length

    return this
   else 
    return new Tuple(...items)
  


let double = new Tuple(1, 2)
let triple = Tuple(1, 2, 3)

double.length //=> 2
triple.length //=> 3

 This satisfies the requirements, but length is defined every time an instance is created, and you don't get the benefits of the prototype (i.e., memory becomes strained). To be smart, it must be defined as Tuple.prototype.method outside of function Tuple.

 In other words, this requires "access to internal variables from outside the scope." So, now that the question of how to do that has arisen, WeakMap enters the scene. [7]

Privatizing variables using WeakMap

 First, are you familiar with WeakMap? It is not something you encounter very often, but it exists as a built-in JavaScript object.

 Normally, JavaScript associative arrays only accept strings as keys, but WeakMap is like an associative array where you can specify an object as a key. Because you can specify an object as a key, the relationship between the object and the value is uniquely determined (think of it like biometric authentication):

let man1 = 
  age: 27,
  height: 180,
  face: "handsome",


let man2 = 
  age: 27,
  height: 180,
  face: "handsome",


let safe = new WeakMap()
safe.set(man1, "money")

safe.get(man1) //=> 'money'
safe.get(man2) //=> undefined
man1 === man2  //=> false 

 As seen in the example above, the relationship between the object and the value is uniquely determined by WeakMap. This allows you to privatize variables. The following code demonstrates this:

"use strict"

const PRIVATE_FIELD = new WeakMap()

function Tuple(...items) 
  if (new.target) 
    PRIVATE_FIELD.set(this, items)

    return this
   else 
    return new Tuple(...items)
  


Tuple.prototype = 
  get length() 
    return PRIVATE_FIELD.get(this).length
  


let double = new Tuple(1, 2)
let triple = Tuple(1, 2, 3)

double.length //=> 2
triple.length //=> 3

 When instantiated, the internal variable items is stored in PRIVATE_FIELD (WeakMap) using this (the instance itself) as the key. Then, inside Tuple.prototype.length, it references and manipulates items using this (the instance itself; double or triple in the example) as the key.

 By combining WeakMap and this, it has become a smart definition that does not put pressure on memory compared to the method of defining methods directly [8], and can receive the benefits of the prototype.

Traps with Proxy and this

 Next, we will define the static method Tuple.from(arrayLike). At that time, in order to drop the state of the original arrayLike into the Tuple as it is, we will allow the elements of the Tuple to be discontinuous and define it as such [9]:

"use strict"

/ Node.js側で解釈可能なシンボル /
const customInspectSymbol = Symbol.for('nodejs.util.inspect.custom')

/
.
.
.
/

const PRIVATE_FIELD = new WeakMap()

function Tuple(...items) 
  if (new.target) 
    PRIVATE_FIELD.set(this, items)

    return this
   else 
    return new Tuple(...items)
  


Tuple.from = (arrayLike) => 
  let tuple = new Tuple()
  PRIVATE_FIELD.set(tuple, convertArray(arrayLike))
  return tuple


Tuple.prototype = 
  get length() 
    return PRIVATE_FIELD.get(this).length
  ,
  [customInspectSymbol]: function (_, , inspect) 
    return inspect(PRIVATE_FIELD.get(this),  colors: true ).replace("[", "#[")
  


let tuple = Tuple.from([0, 1, 2, , , 5])

console.log(tuple, "length:", tuple.length)
//=> #[ 0, 1, 2, <2 empty items>, 5 ] length: 6

 In Tuple.from(arrayLike), after declaring tuple inside the method, we rewrite the internal variable items of tuple using PRIVATE_FIELD.set() to maintain the information that the elements are empty (please consider the convertArray used at that time as a function that returns a new Array with empty elements) [10].

 By returning the tuple afterwards, a "tuple derived from a newly created ArrayLike" has been created by a static method. console.log() shows that there are no problems with the behavior.

 Since the static method was defined smoothly, I would like to add one of the specifications mentioned at the beginning here:

 In other words, this means "I want to intervene (interpose) some kind of operation on access to elements." Therefore, we will utilize the built-in object Proxy.

 Proxy is a built-in object that allows you to define behavior for various calls to a target object. In the example, even though the robot originally has no heart, it behaves as if it does [11]:

let Robot = 

const handler = 
  has: (target, property) => 
    if (property === "emotions") 
      return true
     else 
      return false
    
  


Robot = new Proxy(Robot, handler)

console.log("emotions" in Robot)
//=> true

 Here, handler.has is a method for trapping (intervening) the in operator. Besides this, there are handler.set (trap for assignment to a property) and handler.get (trap for access to a property), and you can change the behavior of an object using Proxy.

 Now, let's actually incorporate it into Tuple. Since the object we want to target for the trap is the object after instantiation that has elements, instead of return this, we will set it to return new Proxy(this, handler) (here, for clarity, handler.get is defined to let things pass through almost entirely):

"use strict"

/ Node.js側で解釈可能なシンボル /
const customInspectSymbol = Symbol.for('nodejs.util.inspect.custom')

/
.
.
.
/

const handler = 
  get: (target, property) => 
    if (property in target) 
      return target[property]
    
  


const PRIVATE_FIELD = new WeakMap()

function Tuple(...items) 
  if (new.target) 
    PRIVATE_FIELD.set(this, items)

    return new Proxy(this, handler)
   else 
    return new Tuple(...items)
  


Tuple.from = (arrayLike) => 
  let tuple = new Tuple()
  PRIVATE_FIELD.set(tuple, convertArray(arrayLike))
  return tuple


Tuple.prototype = 
  get length() 
    return PRIVATE_FIELD.get(this).length
  ,
  [customInspectSymbol]: function (_, , inspect) 
    return inspect(PRIVATE_FIELD.get(this),  colors: true ).replace("[", "#[")
  


let tuple = Tuple.from([0, 1, 2, , , 5])

console.log(tuple, "length:", tuple.length)
//=> #[ 0, 1, 2, <2 empty items>, 5 ] length: 0

 Actually, there is one place where the execution result has changed from before. It might be a little hard to understand, but tuple.length is not outputting the expected value of 6, but is outputting 0.

 There are several points (or rather, pitfalls) to this:

  1. (As is clear from the new Proxy and new declaration, this ≠ new Proxy(this, handler) under new.target, and the return value new Proxy(this, handler) did not serve as a key for changing items in PRIVATE_FIELD.set(tuple, convertArray(arrayLike)).

  2. The this referenced in Tuple.prototype.length is equal to the this at the time of new.target, and it is accessing the initially generated private items.

  3. Inside a function called by a symbol key like Tuple.prototype.[symbol], the referenced this is equal to new Proxy(this, handler), and it is calling the items on the Proxy side that were newly generated when the modification failed.

...and just by listing the situation lightly, you can see that something terrible is happening. To state the solution to this first, we will use pass-by-reference for the object.

Pass-by-reference

 Whether JavaScript has pass-by-reference or not... [12] Something complicated that seems likely to stir up various debates has appeared.

 First, there is the following code:

let a = 3.14
let b = a
console.log(b) //=> 3.14

 This is simple,

I think many people would answer that. Since nothing has been done to b itself, b is a, and since a was 3.14 when looked at, if you are asked what the value of b is at that time, it is 3.14. That is certainly true, and it sounds like elementary school arithmetic, but the reality is slightly different.

 So, for the sake of understanding, I will change my perception just for this moment. I have been drilled that "=" in JavaScript is "assignment," but for this occasion, please read it as a "mathematical equals." In other words, "Although 'a' and 'b' are certainly different as characters, a and b are essentially the same thing, b is another expression of a, and a is also another expression of b."

 I don't think everyone will understand this, but there is the famous Euler's formula

eiθ=cos⁡θ+isin⁡θe^i\theta = \cos\theta + i\sin\theta

 This is a formula stating that the polar form (right side) derived in the complex plane and eiθe^i\theta (left side) defined as a complex function are equivalent. Although their starting points are historically different, they have been shown to be equivalent. Once shown, each points to essentially the same thing, and I think it can be said that each is a different expression of the other.

 The topic has drifted a little, but what I want you to correct from the initial interpretation is that "even if it seems like we are talking about b, since b and a are the same person, it is inevitably talking about a" (that's a bit vague, isn't it).

 Well, there is no point in hesitating, so let's talk about the main topic of pass-by-reference. Let's have a hold an object this time:

let a =  MyFavoriteNumber: 3.14 
let b = a
a.MyFavoriteNumber = 2.71
console.log(b) //=> ??

 Now, what about this case? b becomes

MyFavoriteNumber: 2.71

This is what is called "pass-by-reference." As for the meaning of the term, I think it feels like "I didn't intend to change b, but when I changed the original a, it changed! It seems like it's referencing a, so I'll call let b = a for an object pass-by-reference!"

(It's not like b was completely replaced, and if you assume b is talking about a, it feels natural, but...)

 ...So, the conclusion! You can use pass-by-reference if you use an object. I made it unnecessarily complicated, but the corrected version of the code using pass-by-reference is as follows (using an objectmediator to bridge the outside and the inside):

"use strict"

/ Node.js側で解釈可能なシンボル /
const customInspectSymbol = Symbol.for('nodejs.util.inspect.custom')

/
.
.
.
/

const handler = 
handler.get = (target, prop) => 
  if (prop in target) 
    return target[prop]
  


const PRIVATE_FIELD = new WeakMap()

function Tuple(...items) 
  if (new.target) 
      let mediator =  items 
      let rslt = new Proxy(this, handler)

      PRIVATE_FIELD.set(this, mediator)
      PRIVATE_FIELD.set(rslt, mediator)

      return rslt
   else 
    return new Tuple(...items)
  


Tuple.from = (arrayLike) => 
  let tuple = new Tuple()
  PRIVATE_FIELD.get(tuple).items = convertArray(arrayLike)
  return tuple


Tuple.prototype = 
  get length() 
    return PRIVATE_FIELD.get(tuple).items.length
  ,
  [customInspectSymbol]: function (_, , inspect) 
    return inspect(PRIVATE_FIELD.get(tuple).items,  colors: true ).replace("[", "#[")
  


let tuple = Tuple.from([0, 1, 2, , , 5])

console.log(tuple, "length:", tuple.length)
//=> #[ 0, 1, 2, <2 empty items>, 5 ] length: 6

 With this, I was able to write a program that works without any problems. All that's left is to add various options according to the specifications!

Completion and Application

 Finally, I would like to share my personal completed version(?):

"use strict"

/ Node.js側で解釈可能なシンボル /
const customInspectSymbol = Symbol.for('nodejs.util.inspect.custom')

function convertArray(arrayLike) 
  const length = arrayLike.length ?? 0
  let results = []
  for (let i = 0; i < length; i++) 
    if (i in arrayLike) 
      results[i] = arrayLike[i]
     else 
      results.length += 1
    
  
  return results


function ensureArray(array) 
  if (array.some(v => (v instanceof Object && !(v instanceof Tuple)))) 
    throw Error("Tuple elements are incorrect.")
  


var Tuple = (() => 
  const handler = 
  handler.get = (target, prop) =>  prop in target) 
      return target[prop]
     else if (/^-?\d+$/.test(prop)) 
      let n = Number(prop)
      let items = PRIVATE_FIELD.get(target).items
      let length = items.length
      if (0 <= n && n < length) 
        return items.at(n)
       else if (-length <= n && n < 0) 
        return items.at(n)
       else 
        return undefined
      
    
  
  handler.has = (target, prop) => 
    if (typeof prop === "symbol") 
      return prop in target
     else if (/^-?\d+$/.test(prop)) 
      let n = Number(prop)
      let length = target.length
      if (0 <= n && n < length) 
        return true
       else if (-length <= n && n < 0) 
        return true
       else 
        return false
      
     else 
      return prop in target
    
  
  handler.set = () =>  throw Error("Tuple is readonly Object.") 

  const PRIVATE_FIELD = new WeakMap()

  function Tuple(...items) 
    if (new.target) 
      ensureArray(items)

      let mediator =  items 
      let rslt = new Proxy(this, handler)

      PRIVATE_FIELD.set(this, mediator)
      PRIVATE_FIELD.set(rslt, mediator)

      return rslt
     else 
      return new Tuple(...items)
    
  

  Tuple.from = (arrayLike) => 
    let tuple = new Tuple()
    let items = convertArray(arrayLike)
    ensureArray(items)

    PRIVATE_FIELD.get(tuple).items = items
    return tuple
  

  Tuple.of = (...items) => new Tuple(...items)
  Tuple.isTuple = (arg) => arg instanceof Tuple
  Tuple.toString = () => 'function Tuple()  [JavaScript code] '

  Tuple[customInspectSymbol] = (_, options) => 
    return options.stylize("[Function: Tuple]", "special")
  

  Tuple.prototype = 
    get length() 
      return PRIVATE_FIELD.get(this).items.length
    ,
    [Symbol.iterator]: function () 
      yield* PRIVATE_FIELD.get(this).items
    ,
    [Symbol.isConcatSpreadable]: true,
    [Symbol.toStringTag]: () => "Tuple",
    [customInspectSymbol]: function (_, , inspect) 
      return inspect(PRIVATE_FIELD.get(this).items,  colors: true ).replace("[", "#[")
    ,
    toString: function () 
      return PRIVATE_FIELD.get(this).items.toString()
    ,
    toArray: function () 
      const length = this.length ?? 0
      let results = []
      let value
      for (let i = 0; i < length; i++) 
        if (i in this) 
          value = this[i]
          if (value instanceof Tuple) 
            results[i] = value.toArray()
           else 
            results[i] = value
          
         else 
          results.length += 1
        
      
      return results
    ,
    toJSON: function () 
      return PRIVATE_FIELD.get(this).items
    
  

  return Tuple
)()

let tuple = Tuple.from([0, 1, 2, , , 5])

console.log(tuple, "length:", tuple.length)
//=> #[ 0, 1, 2, <2 empty items>, 5 ] length: 6

 Also, I will provide a template:

var Class = (() => 
  const handler = 
  const PRIVATE_FIELD = new WeakMap();

  function Class(...args) 
    if (new.target) 
      let mediator =  args 
      let rslt = new Proxy(this, handler)

      PRIVATE_FIELD.set(this, mediator)
      PRIVATE_FIELD.set(rslt, mediator)

      return rslt
     else 
      return new Class(...args)
    
  

  Class.isClass = (arg) => arg instanceof Class

  Class.prototype = 
    get args()  return PRIVATE_FIELD.get(this).args ,
  

  return Class
)()

 As an application example of this template, for the first kind Chebyshev polynomials

x=cos⁡θ∈[−1,1], Tn(x)≔cos⁡nθ  (n=0,1,2,…)x=\cos\theta\in[-1,1],\,T_n(x)\colonequals\cosn\theta\,\,(n=0,1,2,…)

the recurrence relation

Tn(x)=2xTn−1(x)−Tn−2(x) (n≥1)T_n(x) = 2xT_n-1(x)-T_n-2(x)\,(n\ge1)

was defined recursively as follows:

"use strict"

var T = (() => 
  const PRIVATE_FIELD = new WeakMap();

  function Tx(n) 
    let ary = PRIVATE_FIELD.get(this).memo
    let x = ary[1]
    if (n in ary) 
      return ary[n]
     else 
      ary[n] = 2 * x * Tx.call(this, n - 1) - Tx.call(this, n - 2)
      return ary[n]
    
  

  const handler = 
  handler.get = (target, prop) => 
    if (/\d+/.test(prop)) 
      let n = Number(prop)
      if (Number.isSafeInteger(n)) 
        return Tx.call(target, n)
       else 
        throw new Error("Non-safe integer")
      
     else if (prop in target) 
      return target[prop]
     else 
      throw new Error("incorrect")
    
  

  function T(x) 
    if (new.target) 
      let memo = [1, x]
      let mediator =  memo 
      let rslt = new Proxy(this, handler)

      PRIVATE_FIELD.set(this, mediator)
      PRIVATE_FIELD.set(rslt, mediator)

      return rslt
     else 
      return new T(x)
    
  
  T.prototype = 
    get memo()  return PRIVATE_FIELD.get(this).memo 
  

  return T
)()

let theta = Math.PI / 2
let x = Math.cos(theta)
console.log(T(x)[9])
//=> 5.51091059616309e-16 ≈ 0

 By the way, using the same template, I was able to define the aforementioned Record in the same way (it is included in the distributed file below).

About distribution

 The program created this time is distributed and published in this article and on Github under the MIT License. Please feel free to tinker with it and enjoy!

Conclusion

 Thank you for sticking with me this far! Please feel free to check out my other articles as well.

 See you next time!

Footnotes

[1]Reference: Summary of how to write environment information - Qiita

[2]From Tuple - Wikipedia.

[3]For destructive/non-destructive Array methods, [JavaScript] Array method destructive/non-destructive cheat sheet - Qiita is easy to understand.

[4]In programming, immutable objects are called immutable objects, and the footnote location is used in that sense.

[5]If you change an Array using a Proxy, you can no longer say it is "definitely inherited," but it is normal to think of it as unchanged, and in JavaScript, modifying built-in objects is discouraged and should be avoided.

[6] There are many other advantages to class declarations, but since we will not be using class declarations in this article, detailed knowledge is not required. However, the concept of class is in the background when creating these, and since class is the mainstream in projects, it is very important.

[7] Even if you try to set up an "associative array for storing items" outside the function as a method that does not use WeakMap, a new problem arises where the access key must be exposed (which is essentially no different from this._times). In the first place, the "associative array for storing items" itself falls into a state of putting pressure on memory, so it is unsuitable. It can be seen that WeakMap is indispensable.

[8] Although not explained in detail in this article, the items of a Tuple that are no longer needed are automatically deleted by a mechanism called garbage collection, which is also friendly to memory, making it doubly pleasing.

[9]Util Node.js v18.12.1 Documentation#util.inspect.custom From this, I am using the Node.js API to customize the state output to the console to make it easier to understand. Depending on the execution environment, the formatting may be disrupted.

[10] The code is not included because it deviates from the purpose, but convertArray was done as follows during testing:

function convertArray(arrayLike) 
  let results = []
  const length = arrayLike.length ?? 0
  for (let i = 0; i < length; i++) 
    if (i in arrayLike) 
      results[i] = arrayLike[i]
     else 
      results.length += 1
    
  
  return results

Here, ArrayLike refers to ECMAScript® 2023 Language Specification - TC39 7.3.19 LengthOfArrayLike ( obj ) as stated in , it refers to something that has a length property and can be correctly interpreted as a non-negative integer by Number(obj.length).
Reference: What exactly is an array-like object? Differences from iterable ... - Qiita

[11] In the case of an implementation as simple as this, for those who are accustomed to it, a shorter

let Robot = 

const handler1 = 
  has: (_, prop) => prop === "emotions"


Robot = new Proxy(Robot, handler1)

console.log("emotions" in Robot)
//=> true

code would probably be better.

[12] Reference: There is no such thing as pass-by-reference/pass-by-value in JavaScript - Qiita

同じカテゴリの記事

八木 麻衣
トレンドリサーチャー 八木 麻衣
プロフィールを見る →

全記事の事実確認を担当。一次情報・公式発表・公開資料の三点を確認できない場合は公開を見送る判断をします。

おすすめの関連記事