Skip to content

Instantly share code, notes, and snippets.

@ppeeou
Last active August 11, 2017 14:09
Show Gist options
  • Save ppeeou/980c6ab5aec2b93d0b0d6f3579cb295d to your computer and use it in GitHub Desktop.
Save ppeeou/980c6ab5aec2b93d0b0d6f3579cb295d to your computer and use it in GitHub Desktop.
functional
var _ = {};
var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
function getLength(array) {
return array == null ? void 0 : array.length;
}
function isArrayLike(array) {
var length = getLength(array);
return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
}
_.each = function (datas, iter) {
if (isArrayLike(datas)) {
for (var i = 0, len = datas.length; i < len; i++) {
iter(datas[i], i, datas);
}
} else {
for (var key in datas) {
if (datas.hasOwnProperty(key)) {
iter(datas[key], key, datas);
}
}
}
}
var curryr = function (func) {
return function (a) {
if (arguments.length > 1) {
return func.apply(null, arguments);
}
return function (b) {
return func.call(null, b, a);
}
}
}
var _filter = curryr(function (data, iter) {
var new_data = [];
_.each(data, function (v) {
if (iter(v)) {
new_data.push(v);
}
})
return new_data;
});
_.reduce = function (datas, iter, memo) {
_.each(datas, function (data, i, datas) {
memo = iter(memo, data, i, datas);
});
return memo;
}
_.groupBy = function (datas, iter) {
return _.reduce(datas, function (grouped, data, i, datas) {
var key = iter(data, i, datas);
grouped.hasOwnProperty(key) ? grouped.push(data[key]) : grouped[key] = [data[key]];
return grouped
}, {})
}
_.compose = function () {
var func = arguments;
var start = func.length - 1;
return function () {
var result = func[start].apply(this, arguments);
while (start--) result = func[start].call(this, result);
return result;
}
}
_.pipe = function () {
var func = arguments;
return function (seed) {
return _.reduce(func, function (l, r) {
return r(l);
}, seed);
}
}
_.rest = function (args, num) {
return Array.prototype.slice.call(args, (num || 1));
}
_.go = function () {
var funs = _.rest(arguments);
return _.pipe.apply(null,funs)(arguments[0]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment