Skip to content

Instantly share code, notes, and snippets.

@mike-at-redspace
Created March 23, 2022 10:31
Show Gist options
  • Save mike-at-redspace/ac69cdda3945ee0bd215e04b8d9e7fd8 to your computer and use it in GitHub Desktop.
Save mike-at-redspace/ac69cdda3945ee0bd215e04b8d9e7fd8 to your computer and use it in GitHub Desktop.
es6 Range
const range = (start, end, step = 1) => {
const forLoop = fn => {
for (let x = start; x <= end; x += step) fn(x)
}
const between = (v, start, end) => v >= start && v <= end
const hasValue = v => between(v, start, end) || between(v, end, start)
const iterate = function* (mapFn) {
for (let x = start; x <= end; x += step) yield mapFn ? mapFn(x) : x
}
const rangeObj = {}
const createProp = v => ({ value: v })
const map = createProp(mapFn => [...iterate(mapFn)])
const forEach = createProp(forLoop)
const includes = createProp(v => {
for (let x = start; x <= end; x += step) {
if (v === x) return true
}
return false
})
const has = createProp(hasValue)
Object.defineProperties(rangeObj, {
map,
forEach,
includes,
has,
})
return rangeObj
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment