2017-04-21 93 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