Skip to content

Instantly share code, notes, and snippets.

@wuliupo
Last active June 12, 2017 10:17
Show Gist options
  • Save wuliupo/75917d3c8518dff967980023ba734e06 to your computer and use it in GitHub Desktop.
Save wuliupo/75917d3c8518dff967980023ba734e06 to your computer and use it in GitHub Desktop.
Functional programming
// the functional programming version
const find2 = (f => f(f))(f =>
(next => (x, y, i = 0) =>
(i >= x.length) ? null :
(x[i] === y) ? i :
next(x, y, i+1))((...args) =>
(f(f))(...args)));
let arr = [0, 1, 2, 3];
console.log(find2(arr, 2));
console.log(find2(arr, 5));
function find3 (arr, x) {
function $find3 (arr, x, i) {
if (i >= array.length) {
return -1;
}
if (arr[i] === x) {
return i;
}
return $find3 (arr, x, i + 1);
}
}
var arr = [0, 1, 2, 3];
console.log(find3(arr, 2));
console.log(find3(arr, 5));
let arr = [0, 1, 2, 3]
// find the first value in array x that equals to y
// return index, or null if not found
const find1 = (x, y) => {
for (let i = 0; i < x.length; i++) {
if (x[i] === y) {
return i;
}
}
return null;
}
console.log(find1(arr, 2));
console.log(find1(arr, 5));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment