Skip to content

Instantly share code, notes, and snippets.

@addityasingh
Last active May 14, 2016 14:40
Show Gist options
  • Save addityasingh/af83cc5037590bd4ca7ad3072342dd83 to your computer and use it in GitHub Desktop.
Save addityasingh/af83cc5037590bd4ca7ad3072342dd83 to your computer and use it in GitHub Desktop.
Pure functions using ES2015 to create common utilities
function forEach(arr, callback, start=0) {
if (0 < start && start < arr.length) {
callback(arr[start], start, arr);
return forEach(arr, callback, start + 1);
}
}
function len([first, ...rest]) {
if (!first) {
return 0
} else {
return 1 + len(rest);
}
}
function map([first, ...rest], f) {
if (!first) {
return [];
} else {
return [f(first), ...map(rest, f)];
}
}
function range (start, end) {
return Array.from({length: (end - start)}, (v, k) => k + start);
}
function replaceString(pattern, replacement, str) {
return str.split(pattern).join(replacement);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment