Last active
September 17, 2016 09:59
-
-
Save gaogao-9/2f17797c02ff75ab8745ed8e9bf791ce to your computer and use it in GitHub Desktop.
JSで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
function* range(from, to, _step=1){ | |
const step = ((step)=> { | |
if(typeof(step) === "function") return step; | |
if(!Number.isFinite(step) || !step) return; | |
return _=> step; | |
})(_step); | |
if(!step) return; | |
const isString = (typeof(from) === "string"); | |
const f1 = isString ? (s)=> s.codePointAt(0) : (n)=> n; | |
const f2 = isString ? (s)=> String.fromCodePoint(s) : (n)=> n; | |
if(to == null) [from, to] = [isString ? "\u0000" : 0, from]; | |
if(typeof(from) !== typeof(to)) return; | |
const a = f1(from); | |
const b = f1(to); | |
let i = a; | |
let s = step(i); | |
while(Number.isFinite(s) && (!s || (s>0) ? i<=b : i>=b)){ | |
yield f2(i); | |
s = step(i); | |
i += s; | |
} | |
} |
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
console.log(Array.from(range(1, 10, 2))); // [1, 3, 5, 7, 9] | |
console.log(Array.from(range("a", "c"))); // ["a", "b", "c"] | |
console.log(Array.from(range("z", "x"))); // [] | |
console.log(Array.from(range("z", "x", -1))); // ["z", "y", "x"] | |
console.log(Array.from(range("z", "x", 0))); // [] (これ無限ジェネレータにすべきか悩んでる) | |
console.log(Array.from(range("z", "x", NaN))); // [] | |
console.log(Array.from(range("a"))); // ["", "", ..., "_", "`", "a"] | |
console.log(Array.from(range(0, 20, (i)=> (Math.random()*4|0)))); // [0, 0, 0, 3, 6, 7, 8, 11, 12, 14, 14, 17, 17, 19] (random) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment