2017-08-18 175 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。