-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathObjFP.js
103 lines (96 loc) · 2.83 KB
/
ObjFP.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// ObjFP Library by Joey Buczek
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof module === 'object' && module.exports) {
module.exports = factory();
} else {
root.ObjFP = factory();
}
}(typeof self !== 'undefined' ? self : this, function () {
// return object for chaining methods
const returnObject = function (obj) {
let objCopy = Object.assign({}, obj);
let api = {
map: function (fn) {
return objectMap(objCopy, fn);
},
filter: function (fn) {
return objectFilter(objCopy, fn);
},
reduce: function (fn, initVal) {
return objectReduce(objCopy, fn, initVal);
},
clean: function () {
let cleanObj = Object.assign({}, objCopy);
delete cleanObj.map;
delete cleanObj.filter;
delete cleanObj.reduce;
return cleanObj;
}
};
let returnObj = Object.assign({}, objCopy, api);
return returnObj;
};
// map method
const objectMap = function (obj, fn) {
let returnObj = {};
if (arguments.length > 1) {
Object.keys(obj).forEach(function (key, index) {
if (typeof fn === 'function') {
returnObj[key] = fn(obj[key], key, index, obj);
} else {
throw new TypeError('Function expected. Received ' + typeof fn);
}
});
} else {
throw new Error('Callback function was not provided');
}
return returnObject(returnObj);
};
// filter method
const objectFilter = function (obj, fn) {
let returnObj = {};
if (arguments.length > 1) {
Object.keys(obj).forEach(function (key, index) {
if (typeof fn === 'function') {
if (fn(obj[key], key, index, obj)) {
returnObj[key] = obj[key];
}
} else {
throw new TypeError('Function expected. Received ' + typeof fn);
}
});
} else {
throw new Error('Callback function was not provided');
}
return returnObject(returnObj);
};
// reduce method
const objectReduce = function (obj, fn, initVal) {
let returnVal = {};
if (arguments.length > 1) {
let keys = Object.keys(obj);
returnVal = initVal || obj[keys.splice(0, 1)];
keys.forEach(function (key, index) {
if (typeof fn === 'function') {
returnVal = fn(returnVal, obj[key], index, obj);
} else {
throw new TypeError('Function expected. Received ' + typeof fn);
}
});
} else {
throw new Error('Callback function was not provided');
}
return (typeof returnVal === 'object' && !Array.isArray(returnVal))
? returnObject(returnVal)
: returnVal;
};
// return api
const publicApi = {
map: objectMap,
filter: objectFilter,
reduce: objectReduce
};
return publicApi;
}));