Attention, pitfall

image



I just found a very subtle bug in my quartet validation library code , and I want to share it.



Task



Given a list of strings: VALID_STRINGS.

Create a validation function test(x)that should return trueif xis one of the strings in this array.

Scope: x- any Javascript value

Restrictions: Do not use ES6. (Target - old browser)



Solution # 1: A head-on decision



The simplest solution that could be is to go through all the lines in this array and compare.



const VALID_STRINGS = [/* VALID STRINGS */]
function test1(x) {
  for (let i = 0; i < VALID_STRINGS.length; i++) {
    if (VALID_STRINGS[i] === x) return  true
  }
  return false
}


, , . O( VALID_STRINGS)



, (indexOf, includes, some, reduce ...). , .



β„–2:



, .



. . .



const VALID_STRINGS = [/* VALID STRINGS */]
const VALID_STRINGS_DICT = {}
for (let i = 0; i < VALID_STRINGS.length; i++) {
  const validString = VALID_STRINGS[i]
  VALID_STRINGS_DICT[validString ] = true
}
function test2(x) {
  return VALID_STRINGS_DICT[x] === true
}


!



! !



, . , β€” VALID_STRINGS. :



// 
const VALID_STRINGS = ['somestring', 'anotherstring']
//    ,     
const VALID_STRINGS_DICT = { somestring: true, anotherstring: true }

const underwaterRock = ['somestring']

test2(underwaterRock) //  true


underwaterRock β€” true. , test2(x) x .



VALID_STRINGS_DICT[x]


β€” x . β€” . β€” .



['somestring'].toString() === 'somestring'


β„–3:



x



const VALID_STRINGS = [/* VALID STRINGS */]
const VALID_STRINGS_DICT = {}
for (let i = 0; i < VALID_STRINGS.length; i++) {
  const validString = VALID_STRINGS[i]
  VALID_STRINGS_DICT[string] = true
}
function test2(x) {
  return typeof x === 'string' && VALID_STRINGS_DICT[x] === true
}


, .



β„–4: Set



ES6. .



const VALID_STRINGS = [/* VALID STRINGS */]
const validStringsSet = new Set(VALID_STRINGS)

function test4(x) { return validStringsSet.has(x) }




, , .



FAQ:



  1. Typescript: , , API. typescript .

    Typescript. , unknown any. , javascript.
  2. " , , , !"

    β€” )
  3. includes ? , , .
  4. ES6? , , . β„–3 , . β„–4 , . .



All Articles