Have you ever done this:
array.map(function (obj) {
return obj[key];
});
Or this:
array.filter(function (x) {
return !func(x);
});
Or maybe this:
array.reduce(function (ret, x) {
return ret - x;
});
Those are annoying to do. This module provides you these functions.
Obligatory overly simplistic and contrived example:
var fun = require('funutils');
var arr = [4, 17, 2, 809];
var isEven = function (x) { return !(x % 2); };
arr.filter(fun.not(isEven)) // [17, 809]
.reduce(fun.sub) // -792
$ git clone https://github.com/Zirak/funutils.git
For use as an npm modules, clone it into your node_modules
directory.
For use in a browser, <script src='funutil/fun.js'></script>
I’ll probably publish to npm somewhen.
id(x) -> x
Returns the first argument.
const(c) -> () -> c
Returns a function which returns a constant.
exists(x) -> x !== null && x !== undefined
Returns whether the argument is not null or undefined. Basically, tells us if we can access a property on it safely.
prop(key) -> (obj) -> obj[key]
Returns a function which gets a certain key from the first argument.
var arr ~ ['This is some string', ['oh look', 'an array'], { length : 4 }];
arr.map(fun.prop('length')); //[19, 2, 4]
safeProp(key) -> (obj) -> obj[key] if fun.exists(obj) else obj
We all know that null
that gets in somehow. Yes, we all have that step where we deal with that pesky null
, and we all got mad that our libraries didn’t handle it correctly.
This is a separate method for some reason. Should it be part of prop
? Maybe.
invoke(method, ...args) -> (obj) -> obj[method](...args)
Calls method
on every received object.
var arr ~ ['FOO', 'BAZINGA', 'SoMeThIng'];
arr.map(fun.invoke('toLowerCase')); // ["foo", "bazinga", "something"]
arr.map(fun.invoke('match', /[A-Z]+/g)); // [["FOO"], ["BAZINGA"], ["S","M","T","I"]]
flipArgs(func) -> (...args) -> func.apply(this, ...args.reverse())
Flips the order of arguments around. Useful with sub and the likes.
not(func) -> (...args) -> !func.apply(this, ...args)
Negates the return value of a function call.
and(f, g) -> (...args) -> f.apply(this, ...args) && g.apply(this, ...args)
&&s the result of applying two functions on the arguments.
Support for n-arity is planned if justification is given.
or(f, g) -> (...args) -> f.apply(this, ...args) || g.apply(this, ...args)
You have one guess.
Obligatory.
add(a, b) -> a + b
sub(a, b) -> a - b
mult(a, b) -> a * b
div(a, b) -> a / b
floorDiv(a, b) -> Math.floor(a / b)
Maybe I was too easy. Could’ve been done with .map(fun.div).map(Math.floor)
. Oh well.
mod(a, b) -> a % b
This program is free software. It comes without any warranty, to the extent permitted by applicable law. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
Basically, WTFPL with a no warranty clause. I probably fucked this section up.