Aaron Ransley

Aaron Ransley

Say you have a long list, maybe filled with some simple objects with key and val fields. Imaginary you wants to:

  1. Know if any items in the list contain the value 'value 1'
  2. Run some additional methods if the item exists in the list
  3. Save a reference to a particular value from the item
  4. Stop the search early

While this is achievable with Array.find(), that's just no fun. You see, Array.find() is not Array.some(), and so it's missing that subtle feeling being "just right" for the occasion.

So, how about some code. Using the steps above, let's implement a solution. First, some top level bits to give us context:

// AKA: myHugeListIDontWantToIterateOverEntirely
const bigListBigDeal = [
  { key: 'one', val: 'value 1' },
  { key: 'two', val: 'value 2' },
  { key: 'three', val: 'value 3' },
  // + 5000 more entries...
]

// We'll use this highly imaginary code in just a moment
function specialSideEffect(val) {
  const dbClient = require('db').connect()

  return {
    operationStatus: dbClient.commitSuperImportantThing({ importantOption: val })
  }
}

Next, let's put Array.some() to work, implementing our outline from above:

// 0a) Somewhere to store our return value
// 0b) What we're looking for
let returnVal = null
const searchVal = 'value 1'

// 1) Ask if any items in the list contains the value `"value 1"`
bigListBigDeal.some(item => {
  if (item.val == searchVal) {
    // 2) Run some additional methods if the item exists in the list
    // 3) Save a reference to a particular value from the item
    returnVal = specialSideEffect(item.val)
    // 4) Stop the search early by returning true from Array.some()
    return true
  }
})

// 5) Extra bonus: robust & full-flavored error handling
if (returnVal === null) {
  throw new Error(`Could not find ${searchVal}, even in the biggest of lists`)
}

There we have it! A wonderfully contrived snippet of code, created with the singular goal of showcasing my love for Array.some().