1.0.1 • Published 2 years ago

nn-deep-read-write v1.0.1

Weekly downloads
-
License
ISC
Repository
-
Last release
2 years ago

nn-deep-read-write

Read, write, and remove values deep within an object or array.

Reading, Writing, and Removing Values

Reading Values

Reads a value nested deep inside an object. Returns the default value if no value is found.

readValue( data, selector, defaultValue, reader )
  • data: object | array - Container.
  • selector: string - Indicates where to read the value. See Selectors
  • defaultValue: any (Optional) - The default value.
  • reader: Getter( container, identifier ) (Optional) - A getter function for special identifiers. See Special Identifier & Getter for more information.

Getter function

  • container: object | array - Container.
  • identifier: string - This is the special identifier.

Writing Values

Writes a value deep inside an object. Returns true if successful.

writeValue( data, selector, value )
  • data: object | array - Container.
  • selector: string - Indicates where to write the value. See Selectors
  • value: any - The value to write.

Removing Values

Removes a value deep inside an object. Returns true if successful.

removeValue( data, selector )
  • data: object | array - Container.
  • selector: string - Indicates what value to remove. See Selectors

Container

A container is considered any object or array.

Selectors

A selector is a path to a value inside a container and is written as 1 or more identifiers separated by . character. Use a selector to indicate where to read, write, or remove a value. Characters in an identifier can also be encoded. See Encoding And Decoding and Special Identifier & Getter for more information.

Encoding And Decoding

An identifier may need to contain a . or other special characters that are not allowed in the identifier. Identifiers can be escaped using | character and the character code of the character being escaped. For example: some.identifier can be written as some|46|identifier. Text can be encoded or decoded using the functions dotDecode and dotEncode.

dotEncode( 'some.selector' ) // Returns 'some|46|selector'
dotDecode( 'some|46|selector' ) // Returns 'some.selector'

Special Identifier & Getter

A special identifier is an identifier that starts with a # character. Special identifiers can only be used for reading data. To use a special identifier, provide a getter function to the readValue function. The getter function will receive a container object and identifier. For example: the selector a.#key, the identifier #key is a special identifier.

readValue( container, 'a.#key', defaultValue, function ( container, identifier )
{
	// identifier is '#key'

	// Do some logic...

	return 'some value';
} )