Me and my co-workers sometimes ask one another to show them something cool. This way we share some awesome tips and tricks and other useful and cool stuff. Some examples that have come up includes random javascript/react tips, visual studio code extensions or settings, chrome plugins, mac os tips, guides, cool sites and much more!
So, do you have any cool stuff to share or show to your fellow developers here?
Building low-level helper functions, then creating functionality on top of them with abstractions on top of that can lead to huge instant gains!
For example, in one of the projects I joined midway, my task was to dedup certain REST calls made by different components in the app. There were different helper-functions to connect to a REST API and to fetch resources in existence, however they were all implemented using
XMLHttpRequests directly. Lot's of code repetition, different levels of error handling, and optimizing/coordinating the calls would have been a lot of work. A mess!So I started deleting them all and writing one function, which does the whole calling thing, handling errors and wrapping success/errors into a Promise. On top of that, I implemented functions to fetch resources and make generic REST calls. And on top of them I created methods which would call the API or fetch specific files and do transformations on them for easy usage.
Writing the dedup code was as easy as changing the lowest level function to hash all input arguments and buffer requests in a
Map<HashString, Array<DeferredPromise>>. The speed gain was huge, and I also deduped resource fetches along the way, which wasn't even my task, but would have been necessary at some point anyway.// simplified // low-level const makeCall = function(method, path, query, body, timeout) { // dedup code const callHash = hashStr(JSON.stringify(arguments)); if (makeCall.hashesMap.has(callHash)) { const prom = new DeferredPromise(); makeCall.hashesMap.get(callHash).push(prom); return prom; } const prom = new Promise((res, rej) => { // do a network call here // resolve/reject all promises in map // remove hash from map }); makeCall.hashesMap.set(callHash, [prom]); return prom; }; // functionality, is auto-deduped const makeRestCall = async function(method, node, query, body) { return JSON.parse( await makeCall(method, '/my/path/' + node, query, body, 3000) ); }; // abstraction, is auto-deduped const getUsername = async function() { return (await makeRestCall('GET', 'userinfo')).name; }; // abstraction, is auto-deduped const getPageTitle = async function(pageId) { return (await makeRestCall('GET', 'page/' + pageId)).title; };