Obscurejs Save

Code from obscurejavascript.tumblr.com in an easy to download format

Project README

Obscure JavaScript Examples

Code from obscurejavascript.tumblr.com in an easy to download format. All of the code can be run in Node.js and most of it in a browser (what can't is noted below). A few posts require libraries and these are found in the node_modules folder and are specified by packages.json. This is a standard NPM layout.

Just like the blog, there may be some examples that do not good follow JavaScript patterns for demonstration purposes.

Example Explanations

Each example corresponds directly to a blog post:

2020

  • collector.js: How to convert class specific functions into general ones without modifying the original functions or copying any code.
  • immutable.js: How to make objects with objects and related immutable.
  • in.js: How to check for property existence in a consistent way.
  • newTarget.js: What new.target is and why it can be useful.
  • nullishOperator.js: Using a new operator to make default checks handle edge cases while still keeping them simple.
  • optionalChaining: How to quickly use deep property lookups without triggering errors with a simple syntax.
  • optionalFunctionCalls: The new syntax to make a function call only if the property is callable.
  • promiseRace.js: How to get the fastest returned API result or error with Promise.race and a simple example Polyfill for it.
  • privateVariables.js: The new syntax of JavaScript private variables compared to the old one.
  • privateMethods.js: The new syntax of JavaScript private methods compared to the old one leveraging the new private class field support.
  • publicInstanceFields.js: Initialize class fields without constructors.
  • uniqBy.js: How to create unique arrays based on a condition in one line with a helper function.
2019

  • allSettled.js: Creating a Promise.allSettled function that only is fulfilled once all promises run even if there are errors.
  • ansiColors.js: How to use ANSI codes to format CLI text and provide simple UIs like dynamic loading screens. Node.js Only
  • backendImports.mjs: How to do backend imports in Node.js. Node.js Only
  • capitalizeSentence.js: Capitalizing sentences instead of just one word with Lodash.
  • changeObjKeys.js: How to make a function to transform object keys to values in an array of objects.
  • classStatic.js: The new way of declaring static methods in classes.
  • clearAllTimeouts.js: Two tactics to clear all timeouts globally in an application.
  • compact.js: Using a compact function that eliminates falsy values in an array to simplify logic in compination with arrays.
  • consoleStringSubstitute.js: Using console.log's built in formatters and inspector to help with debugging.
  • decimalOperations.js: How decimals operations can be computed correctly.
  • defaultValuesObjectParams.js: How default values can be used for functions taking a single object as configuration instead of a bunch of arguments.
  • exponent.js: A specific syntax for exponents.
  • invert.js: Inverting keys and values for dual purpose lookup objects.
  • keyBy.js: A function to transform arrays of objects into key value pairs for fast searching.
  • mapObject.js: The various ways of mapping JavaScript objects.
  • metaClass.js: How to automate the construction of JS classes.
  • promiseAny.js: How to get the fastest returned API result with Promise.any and a simple example Polyfill for it.
  • replayFunction.js: How to recall functions with the last arguments without external variables or libraries.
  • spreadArrayAdditions.js: Merging arrays with the spread operator.
  • strict.js: An example of why adding 'use strict' to legacy code can cause bugs.
  • stringRepeat.js: How String.repeat can be used to easily create nicely formatted console messages.
  • swap.js: How to swap variables or parts of data structures without temporary variables using assignment destructuring.
  • times.js: How a simple repeater function that accepts a function can be used to simplify nested loops.
  • urlObj.js: How the URL object can be used to greatly simplify URL string operations.
  • varUsage.js: An explanation of why var is still necessary in some cases even though let exists.
  • watchProperties.js: How to watch JS object property changes with code for debugging.
2018

  • addCSSRule.js: An example of adding CSS rules directly via JavaScript to reduce DOM manipulations. Browser Only
  • arrayDelete.js: The most common ways of doing Array deletes in JavaScript along with the advantages/disadvantages of doing each.
  • async.js: How the async function declarations can simplify async code. Node 8+/Modern browsers only
  • asyncAndIf.js: How the async helps with conditional logic in asynchronous requests.
  • asyncAndLoops.js: How the async function can be used in loops.
  • asyncHooks.js: How to track all async operations in Node.js without altering the original code. Node 8+ only
  • autoReloadTester.js: The file used to demonstrate automatic script reloading without a framework for backend code. Node.js Only
  • checkLocalStorageMemory.js: How to check the current webpage local storage usage programmatically.
  • classInheritance.js: How the class syntax simplifies inheritance
  • clearArraySameReference.js: How to clear an array and keep the same reference.
  • computedPropertyNames.js: Examples of how Object Literal Computer Property Names can be useful.
  • conformsTo.js: A generic way to do structured object validation.
  • console.js: The most useful ways the JS console can be used (beyond simple string logging)
  • countBy.js: Generic counting via a simple callback pattern.
  • customArrayOrder.js: How JavaScript's simple object construction and array usage combine to make a very simple custom ordering algorithm.
  • customIterable.js: How custom Iterables are implemented in JavaScript.
  • deepFlatten.js: How to implement deep array flattening in JavaScript.
  • destructParams.js: How destructuring can be used for function parameters to simplify multi value callback returns.
  • duplicateKeyChecks.js: An easy tactic to do duplicate key checks in JS and how to extend that to do duplicate format checks.
  • eNotation.js: JavaScript's Exponential Notation and how it makes reading and working with very large or very small numbers much easier.
  • es6Class.js: A comparison of classes with and without the class keyword in JavaScript.
  • externalLoopExtraction.js: How to extract features in a function that has a loop with passing in a callback.
  • functionName.js: How to get class and function names in JavaScript which is useful for debugging and exploring 3rd party libraries.
  • getFirstKey.js: A quick an efficient way to get the first key of an object in JavaScript.
  • getValue.js: How to get values from complex objects quickly and safely.
  • iifeReplace.js: When and how IIFEs can be replaced by a simple block scope.
  • intersection.js: How to discover common array elements across arrays with objects.
  • intl.js: Formatting numbers in JavaScript via the native Intl object.
  • lockObject.js: The 2 ways of locking objects in JavaScript.
  • lookupTable.js: A simple lookup table used to reduce large nested loop performance issues.
  • lookupTableAbstracted.js: How to abstract the lookup table creation
  • mathMax.js: Math.max and how it can be used to simplify algorithms.
  • memoize.js: How to memoize any function in JavaScript that is determined solely based on its parameters.
  • naturalStringSort.js: A simple way to implement natural looking string sorts.
  • nodeEnvironmentVariables.js: Single setting and config files with Node.js environment variables.
  • noDeletion.js: When variables cannot be removed in JS.
  • once.js: Restricting function calls to once.
  • orderBy.js: Generic multi-property ordering in JavaScript.
  • parallelAsyncAwait.js: How promises can work with parallel async calls.
  • rounding.js: How toFixed can be used to implement rounding and its other uses.
  • setObject.js: How to create objects from property paths.
  • size.js: A generic way to find the size of multiple types.
  • stringNormalize.js: How to deal with string characters that only appear as one character, but count as 2.
  • jsShorthand.js: Shorthand conversion syntaxes and the slightly longer and more consistent versions of them.
  • sleep.js: How to create a non-callback function for doing arbitrary waiting.
  • spreadArgs.js: How the spread operator can be used to simplify dynamic function calls.
  • taggedStringReplace.js: The second argument of String.indexOf and how it is useful beyond performance optimization.
  • uniqify.js: A simple one line method to make arrays unique without libraries.
  • valueOf.js: How any object can act like a number via the valueOf property. Newer syntax added since the 2017 post and a much better introduction.
  • zipObject.js: How Zip Object works and why it is useful for debugging.
2017

  • arrayFrom.js: Array.from and how it simplifies multiple types of array conversions.
  • arrayMove.js: Move elements in arrays without having to create lots of variables and logic.
  • callBind.js: How call and bind can be used to make this based functions easier to work with and can make them borrowable.
  • circularReferenceA.js: How Node.js shows circular references and strategies to deal with them. Node.js Only
  • conditionalToHash.js: Simplify and automating logic with hashes.
  • constructor.js: How the constructor property in ever JS object is useful.
  • defaultFunctionParameters.js: How specifying parameter defaults for functions can significantly reduce needed syntax.
  • destructuringAssignment.js: Assigning to multiple variables by mapping directly to an object.
  • findAsyncInOrder.js: A quick pattern to find a set of async items that can be easily switched to other forms.
  • findIndex.js: How findIndex can be useful compared to find functions in some cases.
  • fluentInterface.js: An explanation of fluent interfaces and how repeater methods can be added to them.
  • forOf.js: What for...of loops are.
  • getterSetterAutomation.js: How to automate getters and setters for functions.
  • getterIssue.js: How assignment operations in JavaScript can fail due to assignment operation overwrites.
  • hasDecimals.js: A quick way to check for decimals for all types.
  • infinity.js: Infinity and JS calculation error handling.
  • import.js: How the ES6 import and export statements work. Browser Only
  • jsonsExtraCharacters.js: How JSON supporting extra characters can mess with JavaScript. JSFiddle here: https://jsfiddle.net/jacobfriesen/cxgv37x4/1/
  • letAndConstUsage.js: When to use let and const in JS.
  • makeImmutable.js: How to make any object in JavaScript immutable.
  • mapObject.js: An example of the Map object and how it can be useful compared to plain objects
  • nodeExec.js Executing external system commands in Node.js. Node.js Only
  • newImplementation.js: Demonstrating how new works with a polyfill-like implementation.
  • notification.js: Demonstrating the Notification API. Browser Only
  • observable1.js: A demonstration of Observable API simplification with a click event. Event is simulated in Node.js.
  • observable2.js: A demonstration of Observable API abstraction centered around click events. Extented from observable1.js. Browser Only
  • partialModuleImports.js: The syntax of the new style of module imports in ES6 and how they can be reduced to standard ES6 syntax. Node.js Only
  • preciseAnimations.js: How to make JS animations precise via self adjusting timers. Browser Only
  • protoVsPrototype.js: The difference between __proto__ and prototype and their usage.
  • promiseAll.js: Easily managing multiple concurrent async requests using Promise.all.
  • promisify.js: How util.promisify can be used to transform async functions into promises.
  • reflect.js: How the ES6 Reflect API can be used as a single interface for many general JS operations.
  • replaceThisParameter.js: How to transform this based interfaces into parameter-only ones. The tactic works in any environment, but the examples are Browser only.
  • restProperties.js: How Rest Properties can be used to simply object operations Node 8+.
  • regex.js: A demonstration of simple regex expressions and combining them.
  • removeWhitespace.js: A demonstration of quick whitespace replacing.
  • ruby.js: How close to Ruby syntax JS can get without parsing a source string. Technically, Node.js only, but just replace global with window and it will work with very modern browsers.
  • setObject.js: How the set object can be useful.
  • splitLimit.js: Split and the usefulness of the limit property.
  • spread.js: The spread syntax in JavaScript and how it simplifies function cals and array operations.
  • templateLiteral.js: An easier way of doing multiple line strings are replaces.
  • throw.js: Examples of throws, Error based objects and how they relate to stack traces.
  • typeCoercion.js: When automatic type coercion can make code more readable.
  • unique.js: How simple unique value checking is implemented in JavaScript including with a callback.
  • valueOf.js: How to specify an Objects value when used in numeric operations and how it can be useful.
  • webWorker.js: A simple example of how Web Workers make interfaces responsive when doing complex operations. Browser Only
2016

  • applyApiCalls.js: How Array.apply can be used as a general pattern to add more functionality to base API calls.

  • assignTo.js: A function to drastically reduce syntax for asynchronous object property updates.

  • at.js: A function to reduce the time to get values from potentially empty deep objects.

  • attempt.js: A function to simplify try and catch. See the corresponding blog post for why this is useful.

  • bitwise.js A simple example of when bitwise operations can lead to large performance advantages.

  • callLater.js: A function to store functions to be called later.

  • callbackWith.js: A way to simplify unit tests by making a function that provides a quick way to mock out functions that call calbacks. Also includes an argsAtSync utility.

  • compose.js: A function used to simplify sequences of functions.

  • curry.js: A function that only gets called when passed all arguments otherwise it returns a curry.

  • extendLodash.js: How to extend Lodash with details for chaining and how it is used across imports.

  • flatMap.js: A map function that allows multiple values or no values to be returned for each array element. Allows returns that are shorter than the original array.

  • functionToString.js: About the Function.toString method and how it can be used for debugging and function regeneration.

  • generator.js: How to significantly reduce the number of callbacks for asynchronous operations by using generators.

  • getPagePosition.js: How to get an HTML elements position in the page no matter where it is. Browser Only

  • getters.js: Getters and Setters similar to other Object Oriented Languages in JavaScript.

  • groupBy.js: An array of object grouping function and what it can be applied to.

  • identity.js: How the identity function can be useful.

  • intersection.js: A function that returns the common elements of 2 array, gives an example of where this is useful.

  • is.js: How a function to check object type is useful.

  • objectTypeAndEquality.js: When objects with identical properties and printouts are not equal.

  • observable.js: How to treat data that arrives over time in an array like fashion.

  • [objectFreeze.js]((http://obscurejavascript.tumblr.com/post/152213315637/constants-and-objectfreeze-in-javascript): How to use const and Object.freeze to create completely immutable objects.

  • objOf.js: A shorthand way to create objects with dynamic property names in pre-es6 JavaScript.

  • oneLineForLoop.js: An explanation of for loop structure by using one line for loops only.

  • mapJoin.js: Using the abstraction of splitting then mapping then joining to simplify string set manipulation.

  • mapValues.js: Object traversal operations (mapValue and mapKeys) that iterate through objects like Array.map.

  • maxDate.js: Using one line of code to find the maximum date.

  • negate.js: How a simple closure based negate function can simplify code.

  • mixins.js: A simple way to implement mixins in JavaScript.

  • nonMutatedLists.js: A simple way to make list operations not mutate their lists.

  • multiLineJoinString.js: Less cumbersome syntax for multi-line strings in ES5 or less environments.

  • lazyObject.js: Creating objects that can create more objects or can just be used with no instantiation.

  • propertyMap.js: A function to group properties from a set of objects. Also has a tactic to avoid array.push in maps.

  • proxy.js: How to change JavaScript syntax on given objects via the Proxy API.

  • proxyNumberValidation.js: How to implement JS type checking without setters by using the Proxy API.

  • publishSubscribeAutomation.js: How to use an abstracted publisher to implement more advanced publish-subscribe patterns.

  • replace3rdArg.js: How to use the little known ability of String.replace to accept callbacks.

  • returnWrap.js: How a return wrapper function can be used to merge objects that chain.

  • reverseLater.js: Return a function that calls the passed in callback with reversed arguments.

  • sealAndPreventExtensions.js: The difference between the various methods to make objects constant in JavaScript.

  • selfRegeneration.js: How an object can regenerate itself. This is useful when the object constructor is lost.

  • seriesGeneration.js: Simplifying series generation via Functional Programming principles.

  • stoppingForEachLoops.js: How to stop forEach loops without using an exception and a better strategy.

  • stub.js: A simple one function method of stubbing functions including asynchronous ones.

  • stringify.js: How to use stringify to pretty print JavaScript objects in a customizable way.

  • tap.js: How to use the tap and thru methods to customize chained behavior and make debugging much easier.

  • timing.js: The various ways of timing function calls in JavaScript. Starting with the oldest methods.

  • quickObj.js: A recursive function to quickly create high depth objects for unit and other tests.

  • void.js: Uses of the void keyword. Best understood in conjunction with the blog post in this case.

  • zipObj.js: A function that maps a list of keys to a list of values. This shows an example of why that is important.

  • argumentParameterBinding.js: A demonstration of a little known arguments object quirk.

  • arrowFunctions.js: How to implement arrow functions in pre ES6 JavaScript.

  • beforeAndAfter.js: A before function with an extension into an after one.

  • bind.js: Bind and an example of it in JavaScript.

  • chainify.js: How to build a generic chaining method that can add chaining to any object.

  • circularReference.js: Circular references and potential issues with them. Does not go into all the details, more of an overview.

  • circularReferencePositives.js: Positives of circular references.

  • class.js: Classes in ES6 and how to create a close equivalent.

  • clone.js: How to deep copy objects in JavaScript.

  • const.js: The const keyword in ES6 and how to create a close equivalent.

  • debounce.js: Create a wrappped function so that the function it wraps is only called after it stops being triggered every n milliseconds.

  • defer.js: Run a function after all processing is done in the current callstack.

  • dependencyInversion.js: Screwed up the monad post. So just the dependency inversion part will be kept.

  • floatingPointArithmetic.js: A simple algorithm strategy for reliably calculating decimal based numbers.

  • flow.js: This is used to string functions that use each others results in a chain.

  • functionDecompilation.js: Function decompilation, Angular.js and simplified dependency injector for it.

  • functionExpressionProperties.js: How properties on object can be used to simplify code. Specifically, with named Function Expressions.

  • generator.js: How to implement a relatively close equivalent of generators in pre ES6 JavaScript.

  • genericChaining.js: An explanation of a simple generic pattern for creating chainable objects.

  • interatedAsyncCalls.js: How to solve a seemingly wierd issue while passing state to multiple asynchronous calls in JavaScript.

  • iterator.js: A simple implementation of the ES6 iterator abstraction in non ES6 JavaScript (without an Iterable implementation).

  • lazyFunctionDefinition.js: Caching values without using conditionals. This is useful for calls that need to be made multiple times.

  • mapObject.js: An implementation of the map object in ES6 in less than ES6 JavaScript.

  • mapOrRemove.js: A function used to filter and modify objects.

  • mapsThirdArgument.js: How the 3rd argument in map() can be used to operate on multiple array elements at once.

  • memoize.js: A way to automatically cache function calls.

  • nonMutatingAssign.js: Showing the implementation of a function similar to Lodash assign and how to not mutate with it.

  • oneLineRandomText.js: How to generate short random text codes in JavaScript in one line using no library functions.

  • sortsAndNan.js: What NaN return values do to JavaScript's default sort.

  • templateStrings.js: Evaluating strings with expressions in JavaScript similar to ES6 templates.

  • let.js: The ES6 let statement and how to emulate close aproximations.

  • monad.js: Defining a chainable specification of operations.

  • multiIf.js: Making complex conditionals more readable by using an expression and chaining conditions.

  • multicore.js: Multicore node.js code. Node.js Only

  • omit.js: Return an object with properties removed with no side effects.

  • primitiveCoercion.js: A brief explanation of automatic primitive coercion in JavaScript.

  • promise.js: Create an object that represents future state.

  • undefined.js: An explanation of the undefined type.

  • repl.js: A REPL of JavaScript in JavaScript using streams. Node.js Only

  • server.js: A 4 line http server using connect.js and serve-static.js Node.js Only

  • setObject.js: An implementation of the set object in ES6 in less than ES6 JavaScript.

  • stream.js: A simple example of streams Node.js Only

  • symbol.js: Implementing ES6 Symbols in pre ES6 syntax.

  • thisKeyword.js: An attempt of defining all the possible ways that the this context is defined.

  • throttle.js: Create a wrappped function so that the function it wraps is called at most every n milliseconds.

  • trim.js: The trim string function and polyfills for trimLeft and trimRight.

  • typedArray.js: A simple demonstration of the differences between Array and a Typed Array.

  • where.js: Code for the JavaScript where function.

  • unionAndIntersection.js: Code for the intersection and union array manipulation functions and the unifyling function.

  • variableChaining.js: How variable chaining can create globals and how global creation can be avoided.

  • zip.js: How to use a function that automatically structures raw array data.

2014

2013

Open Source Agenda is not affiliated with "Obscurejs" Project. README Source: Jacob-Friesen/obscurejs
Stars
63
Open Issues
1
Last Commit
3 years ago
License
MIT

Open Source Agenda Badge

Open Source Agenda Rating