Skip to content

Instantly share code, notes, and snippets.

@zhibirc
Last active March 19, 2021 12:46
Show Gist options
  • Save zhibirc/892483721dbf55ef2c28949b930e3167 to your computer and use it in GitHub Desktop.
Save zhibirc/892483721dbf55ef2c28949b930e3167 to your computer and use it in GitHub Desktop.
Recursive one-liners (or a bit more) for popular tasks
/** @see {@link https://en.wikipedia.org/wiki/Digit_sum} */
const dsum = n => n < 10 ? n : n % 10 + dsum(n / 10 | 0);
/** @see {@link https://encyclopediaofmath.org/wiki/Factorial} */
const fact = n => n ? n * fact(n - 1) : 1;
/** @see {@link https://encyclopediaofmath.org/wiki/Greatest_common_divisor} */
const gcd = (a, b) => b ? gcd(b, a % b) : a;
/** @see {@link https://encyclopediaofmath.org/wiki/Power|Fast algorithm} */
const pow = (m, n) => n ? n % 2 ? m * pow(m, n - 1) : pow(m * m, n / 2) : 1;
/** @see {@link https://encyclopediaofmath.org/wiki/Fibonacci_numbers} */
const fib = n => n < 2 ? n : fib(n - 1) + fib(n - 2);
/** @see {@link https://www.wolframalpha.com/input/?i=binary+search|Binary search} */
const bin = (lst, n, i) => (i = ~~(lst.length / 2)) ? n === lst[i] ? !0 : n < lst[i] ? bin(lst.slice(0, i), n) : bin(lst.slice(i), n) : n === lst[i];
/** @see {@link https://www.wolframalpha.com/input/?i=call+stack|Estimate call stack size (approximately)} */
const lim1 = n => { try { return lim1(++n) } catch ( RangeError ) { return n } };
const lim2 = () => { try { return 1 + lim2() } catch ( RangeError ) { return 1 } };
/** @see {@link https://encyclopediaofmath.org/wiki/Addition|Add integers from 1 to N} */
const add1 = n => n ? n + add1(n - 1) : 0;
const add2 = (n, acc = 0) => !n ? acc : add2(n - 1, acc + n);
/** @see {@link https://www.cs.utexas.edu/~mitra/csFall2017/cs303/lectures/basic_algo.html|Find maximum} */
const max = (lst, n = -Infinity) => lst.length ? lst[0] > n ? (n = lst[0], max(lst.slice(1), n)) : max(lst.slice(1), n) : n;
const min = (lst, n = +Infinity) => lst.length ? lst[0] < n ? (n = lst[0], min(lst.slice(1), n)) : min(lst.slice(1), n) : n;
/** @see {@link http://db.cs.duke.edu/courses/cps006g/fall04/notes/week15-4up.pdf} */
const find = (dir, ext, out = [], fs = require('fs'), path = require('path')) => {
fs.readdirSync(dir).forEach((file, i) => {
file = dir + path.sep + file, i = fs.statSync(file);
if ( i && i.isDirectory() ) out = out.concat(find(file, ext));
else if ( path.extname(file) === ext ) out.push(file);
});
return out;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment