Skip to content

Instantly share code, notes, and snippets.

@htdangkhoa
Last active May 30, 2021 19:13
Show Gist options
  • Save htdangkhoa/2a7703d66d96eb67de4f218fd2d77592 to your computer and use it in GitHub Desktop.
Save htdangkhoa/2a7703d66d96eb67de4f218fd2d77592 to your computer and use it in GitHub Desktop.
Alternative lodash.js
const chunk = (input, size) => {
return input.reduce((arr, item, idx) => {
return idx % size === 0 ? [...arr, [item]] : [...arr.slice(0, -1), [...arr.slice(-1)[0], item]];
}, []);
};
export default chunk;
const compact = (input) => {
const array = Array.isArray(input) ? input : [];
return array.filter(Boolean);
};
export default compact;
const debounce = (func, wait, immediate) => {
let timeout;
return (...args) => {
const later = () => {
timeout = null;
if (!immediate) func.apply(...args);
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(...args);
};
};
export default debounce;
const first = (input) => {
if (typeof input !== 'string' && !Array.isArray(input)) {
return undefined;
}
return [...input].splice(0, 1)[0];
};
export default first;
export function isEmpty(input) {
let obj = input;
// boolean or number
if (typeof obj === 'boolean' || typeof obj === 'number') return true;
// Set
if (obj instanceof Set) {
if (obj.size === 0) return true;
return false;
}
// Map
if (obj instanceof Map) {
obj = Object.fromEntries(obj);
}
return [Object, Array].includes((obj || {}).constructor) && !Object.entries(obj || {}).length;
}
export default isEmpty;
const isNil = (value) => (value === null || value === undefined);
export default isNil;
const last = (input) => {
if (typeof input !== 'string' && !Array.isArray(input)) {
return undefined;
}
return [...input].splice(-1)[0];
};
export default last;
const flattenKeys = (s) => s.replace(/\[(\w+)\]/g, '.$1').replace(/^\./, '').split('.');
const pick = (object, selectors) => {
let o = { ...object };
let paths = selectors;
if (typeof paths === 'string') {
paths = flattenKeys(paths);
}
paths.forEach((key) => {
if (key in o) {
o = o[key];
return;
}
o = undefined;
});
return o;
};
export default pick;
const flattenKeys = (s) => s.replace(/\[(\w+)\]/g, '.$1').replace(/^\./, '').split('.');
const set = (object, path, value) => {
const obj = object;
let keys = path;
if (typeof keys === 'string') {
keys = flattenKeys(keys);
}
if (keys.length === 1) {
obj[path] = value;
return undefined;
}
return set(obj[keys[0]], keys.slice(1).join('.'), value);
};
export const omit = (object, path) => {
const obj = object;
let keys = path;
if (typeof keys === 'string') {
keys = flattenKeys(keys);
}
if (keys.length === 1) {
delete obj[path];
return undefined;
}
return omit(obj[keys[0]], keys.slice(1).join('.'));
};
export default set;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment