This repository was created to write various interesting functions/classes to improve my hard skills. So far, this will be a collection of little-related things. To write them, I use different ideas from different libraries (I will add links to the libraries that inspired me) and write my own implementations based on them.
Implementation of JSON.stringify.
- symbol supports
- cycle reference save
- stable key order for deterministic result (except symbols because they may have same names)
- well configurable indent
- more functionality replacer
API
example:const stringify = require('bunny-utils').stringify;
const result = stringify({b: 123, a: {}}, {newLine: true, indend: 2, keyValueIndent: 1});
/*
{
"a": {},
"b": 123
}
*/
stringify()
takes two parameters: value to stringify and options.
Options are optionals. Result always is a string unlike JSON.stringify()
can return undefined
. Value is any. Options should be an object with optional properties:
replacer
- function, defaultnull
. This function will be called for every value during stringify recursively. Should return an object with propertieskey
andvalue
that will be used as new key and value for stringify. If there is an array - key will benull
and returning key will be ignored. Default isnull
comparator
- boolean or function, defaulttrue
. In case if boolean: true - use default comparator that uselocaleCompare
of string, false - don't use comparison. If function - it will be passed as callback toArray.sort()
, so it takes two arguments string or symbol and return number. If number > 0 - first element after second, if number < 0 - second element after first, if number = 0 - ignore element ordernewLine
- boolean, defaultfalse
. If true - pretty json with line breaksindent
- number, default0
. Specify indent for every new nesting levelkeyValueIndent
- number, default0
. Specify indent between key and value. For example common pretty json has 1ignoreCycles
- boolean, defaulttrue
. Iftrue
- every cycle will be replaced with string "__cycle__" iffalse
- throw error for first cycle. Consider that for avoiding infinite loop we mast track cycles, so set this option tofalse
doesn't increase performanceignoreSymbols
- boolean, defaultfalse
. Iffalse
- also stringify symbols by usingsymbol.toString()
. Iftrue
- ignore symbol keys
- https://github.com/ljharb/json-stable-stringify
- https://github.com/ljharb/jsonify
- https://github.com/BridgeAR/safe-stable-stringify
Implementation of lru-cache using doubly linked list. Memory: O(n), set/get/has/delete: O(1) where n - count of elements Inspired libraries:
- https://github.com/rsms/js-lru (main idea)