2017-04-21 37 views
0

我想知道是否有一种简单的方法来检查不可变映射值是否包含某个字符。检查Immutable.js映射值是否包含char

基本上寻找https://facebook.github.io/immutable-js/docs/#/Map/includes但只匹配值的整个单词。

现在我遍历每个属性并检查值本身。

function mapContains(map, char) { 
    let contains = false; 
    map.forEach((val) => { 
    if(val.includes(char)) { 
     contains = true; 
     return false; //short circuits the foreach 
    } 
    }); 
    return contains; 
} 

感谢您提前回复。

回答

2

我建议使用Map.prototype.some这个。它将短路并尽快返回true为您的拉姆达返回truthy值 - 否则返回false

const { Map } = require('immutable') 

const m = Map({a: 'one', b: 'two', c: 'three'}) 

m.some(v => /t/.test(v)) // true, at least one value has a 't' 
m.some(v => /x/.text(v)) // false, no values contain an 'x' 

// but be careful with automatic string coercion 
/o/.test({}) // true, because String({}), '[object Object]', contains 'o' 

如果你的地图将举行多种价值类型,你将要小心使用String.prototype方法 - 即我会建议对这样的事情

const { Map } = require('immutable') 

// mixed value type Map 
const m = Map({a: 'one', b: 2, c: 3}) 

// CAUTION! 
// reckless assumption that every value is a string (or has a .includes method) 
m.some(v => v.includes('o')) // true, short-circuits on first value 
m.some(v => v.includes('x')) // TypeError: v.includes is not a function 

如果必须使用String.prototype.includes,我会建议你做type首先检查

const { Map } = require('immutable') 

const m = Map({a: 'one', b: 2, c: 3}) 

m.some(v => typeof v === 'string' && v.includes('o')) // true 
m.some(v => typeof v === 'string' && v.includes('x')) // fase 
+0

太棒了!对包含的重要建议。 – Colin