Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save PieterScheffers/37bbebb88189ab7cea76 to your computer and use it in GitHub Desktop.
Save PieterScheffers/37bbebb88189ab7cea76 to your computer and use it in GitHub Desktop.
Javascript - functional functions
function arrayEach(arr, callback) {
for (var i = 0; i < arr.length; i++) {
callback(arr[i], i);
}
}
function arraySelect(arr, callback) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
if( callback(arr[i], i) ) {
newArr.push(arr[i]);
}
}
return newArr;
}
function arraySelectFirst(arr, callback) {
for (var i = 0; i < arr.length; i++) {
if( callback(arr[i], i) ) {
return arr[i];
}
}
return null;
}
function arrayMap(arr, callback) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
newArr.push( callback(arr[i], i) );
}
return newArr;
}
function arrayReduce(arr, callback, alt) {
var total = def(alt, 0);
for (var i = 0; i < arr.length; i++) {
total = callback(total, arr[i], i, arr);
}
return total;
}
function objectEach(obj, callback) {
for (var key in obj) {
if( obj.hasOwnProperty(key) ) {
callback(obj[key], key);
}
}
}
function objectMap(obj, callback) {
var newObj = {};
objectEach(obj, function(value, key) {
newObj[key] = callback(value, key);
});
return newObj;
}
function objectSelect(obj, callback) {
var newObj = {};
objectEach(obj, function(value, key) {
if( callback(value, key) ) {
newObj[key] = value;
}
});
return newObj;
}
function objectReduce(obj, callback, alt) {
var total = def(alt, 0);
objectEach(obj, function(key, value) {
total = callback(total, value, key, obj);
});
return total;
}
function each(obj, callback) {
if( isObject(obj) ) {
objectEach(obj, callback);
} else if( isArray(obj) ) {
arrayEach(obj, callback);
} else {
arrayEach([ obj ], callback);
}
}
function newObj(obj) {
if( isObject(obj) ) {
return {};
} else {
return [];
}
}
function appendObj(newObj, value, key) {
if( isObject(newObj) ) {
newObj[key] = value;
} else if( isArray(newObj) ) {
newObj.push(value);
} else {
newObj = [ value ];
}
}
function map(obj, callback) {
var n = newObj(obj);
each(obj, function(value, key) {
appendObj(n, callback(value, key), key);
});
return n;
}
function select(obj, callback) {
var n = newObj(obj);
each(obj, function(value, key) {
if( callback(value, key) ) {
appendObj(n, value, key);
}
});
return n;
}
function reduce(obj, callback, alt) {
var total = def(alt, 0);
each(obj, function(value, key) {
total = callback(total, value, key, obj);
});
return total;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment