iT邦幫忙

2025 iThome 鐵人賽

DAY 23
0

昨天將地址的原始資料整理成
節點與相連節點的資料結構

今天繼續看接下來的部分
節錄覺得實用的描述

如果你正從物件導向程式設計下手,可能開始為各種元素定義物件,然後為類別設定屬性,儲存它們當前狀態,但某些東西的感覺上像是物件不代表可以自動帶入為程式中的物件。反射性為應用程式中的每個概念撰寫類別,往往會留下一組相互關聯的物件。每個物件內部各自有不斷變化的狀態。這一類的程式通常最後都難以理解,因此容易發生程式中斷的問題。
相反的,要定義最小的集合值,將村莊的狀態濃縮在集合值裡,集合值包含所有機器人當前位置和所有尚未配送的包裹,每個包裹下有目前所在位置和目的地位置

機器人移動時不改變這個狀態,等機器人移動後才計算出新的狀態

以下為範例程式碼

// define the smallest collections of parcel state and places
      class VillageState {
        constructor(place, parcels) {
          this.place = place;
          this.parcels = parcels;
        }
        move(destination) {
          /* 
          check if the destination is connect to the current place
          if not, the moving is invalid, so stop and return the original state
          if true, update the state of parcels
           */
          if (!roadGraph[this.place].includes(destination)) {
            return this;
          } else {
            let parcels = this.parcels
              /*
              if p.place equals to this place, means the parcel has arrived
              update the current place as destination then filter out the arrived parcel
              */
              .map((p) => {
                console.log(p);
                if (p.place !== this.place) return p;
                return { place: destination, address: p.address };
              })
              .filter((p) => p.place !== p.address);
            return new VillageState(destination, parcels);
          }
        }
      }

Immutable & persistent values

  • const with primitive value
  • Object.freeze() can prevent Object from mutation, but
  1. Strict Mode is Essential
  2. Only performs Shallow freeze, but any nested object or array are not freeze.

上一篇
Chapter 7 實作專案-1-day22
下一篇
Chapter 7 實作專案-3-待更新-day24
系列文
溫故而知新:Eloquent Javascript 閱讀筆記25
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言