2017-08-18 87 views
0

我試圖建立一個模塊包裝集合失敗ES2015初始化不工作

我有類似:

// topic: chess gaming 
// file: src/core/Refs.js 

const COLS = 'abcdefgh'.split('') 
const ROWS = '12345678'.split('') 
const ALL = new Map() 

class Ref { 
    constructor (col, row) { 
    this.col = col 
    this.row = row 
    this.key = String(col + row) 
    } 

    // translate to ref to obtain another 
    // or null, if off-board 
    // 
    // ref.translate(0, 0) === ref (ok ?) 
    // 
    translate (dcol, drow) { 
    // compute something for dcol and drow 
    // ... 
    return ALL.get(COLS[colIdx] + ROWS[rowIdx]) 
    } 
} 

// the code which seems to not work propertly 
for(let c of COLS) { 
    for(let r of ROWS) { 
    ALL.set(String(c + r), new Ref(c, r)) 
    } 
} 

export default { 
    COLS, ROWS, ALL, 

    has (ref) { 
    return ALL.has(ref) 
    }, 

    get (ref) { 
    return ALL.get(ref) 
    }, 

    // trying to grant/warrant "immutability" 
    // for the "ALL" collection inside the module 
    keys() { 
    return [...ALL.keys()] 
    } 
} 

我complie與佈雷與正確的標誌(dangerousForOf模塊後,。 。)和objectAssign

然後我與因緣+茉莉,第一測試測試:

it ('should be 64-length array', function() { 
    expect (Refs.keys().length).toEqual(64) 
}) 

將用'期望1到等於64'來表示,並且Refs.ALL的日誌似乎顯示空的Map 其他Refs.COLS和Refs.ROWS已正確初始化。

發生了什麼事以及如何解決?

編輯:

@Bergi:當然,露出Refs.ALL打破不變性,這是相當用於調試

我不完全知道如何捕捉測試包輸出,但看着吞+彙總DEVELOPPEMENT束,該方法密鑰()線:

return [...ALL.keys()] 

改爲:

return [].concat(ALL.keys()) 

它產生一個包含MapIterator的1元素數組,這個破解測試。把類似的東西:

return Array.from(ALL.keys()) 

將解決這個問題,但風險不會在傳統瀏覽器工作uniqueky!

我都推在我的回購代碼:https://github.com/hefeust/colorchess-v2

希望這可以幫助修復bug:如何傳播(...)運營商轉換源代碼中有一個與正確Object.assign捆綁polyfill?

+0

嘗試在設置值的循環中記錄'String(c + r)'的值? – Ryan

+0

*用buble *編譯? –

+0

c + r給我「a1」至「h8」,當然...我想說的是,Buble和我的意思是,用012p來傳譯。從ES2015 +階段2經典瀏覽器JS,採用因果報應,並彙總 - 插件 - 佈雷(不通天)轉換,因爲佈雷的速度 – Hefeust

回答

1

Bublé does not support iterators,這就是爲什麼它使用擴展語法將數組文字轉換爲連接。改爲使用Array.from(無論如何,這更具描述性)。

return Array.from(ALL.keys())將解決問題,但風險不能在傳統瀏覽器中正常工作!

這應該是不關心的 - 你正在使用Map對象及其keys()方法返回一個迭代器,它不會在傳統的瀏覽器工作,要麼。如果您打算支持它們,則無論如何您都必須使用polyfill - 並且您只需要爲Array.from獲得polyfill。