Created
August 6, 2022 14:56
-
-
Save notzheng/0f2c055a0103f0ce1f741128ea6648a2 to your computer and use it in GitHub Desktop.
Javascript Range Syntax
This file contains 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 checkValidRangeSyntax = (arr) => { | |
if (arr.length !== 4) { | |
return false; | |
} | |
if (Object.keys(arr).length !== 2) { | |
return false; | |
} | |
const start = arr[0]; | |
const end = arr[3]; | |
if (!Number.isInteger(start) || !Number.isInteger(end)) { | |
return false; | |
} | |
return end > start; | |
}; | |
const makeRangeArray = (arr) => { | |
const start = arr[0]; | |
const end = arr[3]; | |
const result = []; | |
for (let i = start; i < end; i++) { | |
result.push(i); | |
} | |
return result; | |
}; | |
[Symbol.iterator, "map", "forEach"].forEach((name) => { | |
const originMethod = Array.prototype[name]; | |
Array.prototype[name] = function (...args) { | |
const target = checkValidRangeSyntax(this) ? makeRangeArray(this) : this; | |
return originMethod.apply(target, args); | |
}; | |
}); | |
console.log("Normal Array:"); | |
for (let item of [1, 2, 3, 4]) { | |
console.log(item); | |
} | |
console.log([1, 2, 3, 4].map((item) => item)); | |
console.log("Range Array:"); | |
for (let item of [1, , , 5]) { | |
console.log(item); | |
} | |
console.log([1, , , 5].map((item) => item)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment