Skip to content

Instantly share code, notes, and snippets.

@isabellachen
Last active February 23, 2018 12:13
Show Gist options
  • Save isabellachen/05ccc7414ccc93fbe7d35879b4e9df28 to your computer and use it in GitHub Desktop.
Save isabellachen/05ccc7414ccc93fbe7d35879b4e9df28 to your computer and use it in GitHub Desktop.
Implementation of underscoreJS every and some functions
const someEven = [1,2,3,4,5]
const allEven = [2,4,6,8,10]
const isEven = (n) => {
if (n % 2 ===0) return true
return false
}
const every = (collection, predicate, context) => {
if (Array.isArray(collection)) {
for (let i=0; i<collection.length; i++) {
if (!predicate.call(context, collection[i], i, collection)) {
//console.log('the element ', collection[i], ' is odd: ', !predicate.call(context, collection[i]))
console.log('the element ', collection[i], ' is even: ', !predicate.call(context, collection[i]))
return false
}
}
} else {
for (let key in collection) {
if (collection.hasOwnProperty(key)){
if (!predicate.call(context, collection[key], key, collection)) return false
}
}
}
return true
}
const some = (collection, predicate, context) => {
//[!predicate]: short circuit when it is even, not odd. [!every]:Every short circuits with false, so turn that value to true.
return !every(collection, (el, key) =>{
return !predicate.call(context, el, key, collection)
})
}
//console.log(every(someEven, isEven))
console.log(some(someEven, isEven))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment