Created
February 8, 2018 11:59
-
-
Save jscMR/8ebd1eab53fddc6175f71e4b4ebdd2cc to your computer and use it in GitHub Desktop.
[ES6 JS Hacks] hacks en JS ES6
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
| //////////////////////////////////////////////////// | |
| // Para acceder al primer elemento del array | |
| //////////////////////////////////////////////////// | |
| const head = ([x]) => x | |
| const array = [1,2,3,4,5] | |
| head(array) // 1 | |
| //////////////////////////////////////////////////// | |
| // Traer todo menos el primer elemento | |
| //////////////////////////////////////////////////// | |
| const tail = ([, ...xs]) => xs | |
| const array = [1,2,3,4,5] | |
| tail(array) // [2,3,4,5] | |
| //////////////////////////////////////////////////// | |
| // Comprobar que el argumento esta definido | |
| //////////////////////////////////////////////////// | |
| const def = x => typeof x !== 'undefined' | |
| //////////////////////////////////////////////////// | |
| // Comprobar que el argumento no esta definido | |
| //////////////////////////////////////////////////// | |
| const undef = x => !def(x) | |
| //////////////////////////////////////////////////// | |
| // Copiar array | |
| //////////////////////////////////////////////////// | |
| const copy = array => [...array] | |
| //////////////////////////////////////////////////// | |
| // Length array | |
| //////////////////////////////////////////////////// | |
| const length = ([x, ...xs], len = 0) => def(x) ? length(xs, len + 1) : len | |
| // alternativa | |
| const length = ([x, ...xs]) => def(x) ? 1 + length(xs) : 0 | |
| //////////////////////////////////////////////////// | |
| // Reverse array | |
| //////////////////////////////////////////////////// | |
| const reverse = ([x, ...xs]) => def(x) ? [...reverse(xs), x] : [] | |
| ////////////////////////////////////////////////////// | |
| // First array - devuelve un array con los n primeros | |
| ////////////////////////////////////////////////////// | |
| const first = ([x, ...xs], n = 1) => def(x) && n ? [x, ...first(xs, n - 1)] : [] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment