Last active
June 12, 2017 10:17
-
-
Save wuliupo/75917d3c8518dff967980023ba734e06 to your computer and use it in GitHub Desktop.
Functional programming
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
// 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)); |
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 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)); |
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
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