Created
March 23, 2022 10:31
-
-
Save mike-at-redspace/ac69cdda3945ee0bd215e04b8d9e7fd8 to your computer and use it in GitHub Desktop.
es6 Range
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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