Skip to content

Instantly share code, notes, and snippets.

@shuizhongyueming
Last active December 17, 2018 04:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shuizhongyueming/3e63ec67fe3b418b678501679d3c5859 to your computer and use it in GitHub Desktop.
Save shuizhongyueming/3e63ec67fe3b418b678501679d3c5859 to your computer and use it in GitHub Desktop.
simple achievement of javascript for statement
function forFunc(curr, compare, changer, actions) {
if (compare(curr)) {
actions(curr);
return forFunc(changer(curr), compare, changer, actions);
}
}
function iterateArr(arr, actions) {
forFunc(0, i => i < arr.length, i => i+1, i => actions(arr[i], i));
}
function iterateArrReverse(arr, actions) {
forFunc(arr.length - 1, i => i >= 0, i => i-1, i => actions(arr[i], i));
}
// use demo
forFunc(0, i => i < arr.length, i => i+1, i => console.log(i, arr[i])); // 0 1, 1 2, ...
iterateArr([1,2,3,4,5], (i, n) => console.log(i, n)); // 0 1, 1 2, ...
iterateArrReverse([1,2,3,4,5], (i, n) => console.log(i, n)); // 4 5, 3 4, ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment