Last active
March 22, 2020 14:58
-
-
Save matthewstokeley/ba4376c8418fdb043f94f832db6fa880 to your computer and use it in GitHub Desktop.
query dom siblings + sibling children w/o traversal with a function macro pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// an alternative to traversal | |
// https://github.com/matthewstokeley/dom-traversal | |
// @version 0.0.3 | |
_.castArr = function( | |
list: NodeList | |
): Array { | |
return Array.prototype.splice.call( list ) | |
} | |
// provide error handling for unexpected types | |
// too much abstraction? | |
_.propertyExists = ( root: Object, prop: String ) => { | |
function err( val ) { | |
// if in prod, should fail gracefully | |
if ( PROD ) return false | |
// otherwise, throw | |
throw new Error( 'Unexpected Value: ' + val ) | |
} | |
if ( typeof root === 'object' ) { | |
return ( root [ prop ] && root.hasOwnProperty( prop ) ) | |
// | |
? true | |
// throw error | |
: err( root[ prop ] ) | |
} | |
} | |
// `type` obviates the need by throwing the error during compilation | |
type RootObj = { | |
requiredProperty: String | |
} | |
type Node = { | |
nodeType: Integer | |
} | |
type NodeList = { | |
} | |
type HTMLCollection = { | |
} | |
function fn( obj: RootObj ) { | |
console.log( obj.requiredProperty ) | |
} | |
export var findChildWhereMacro = () => { | |
let _arr = _.castArr ( document.querySelectorAll( this ) ) | |
let _el: Node = _arr.filter( ( val ) => node.containsChild( val ) ) | |
return ( _el ) | |
? _el | |
: false | |
} | |
// kind of wonky | |
String.prototype.findChildWhere = findChildWhereMacro | |
// an alternative to prototypal inheritance | |
let _macro = findChildWhereMacro | |
// a composition or a compositional api or something like a higher-order component is probably the correct answer | |
export var findChildWhereParentContainsClass = ( _ ) => { | |
let q = '.active' | |
let res = q.findChildWhere( q, _ ) | |
// @todo macro? name is incorrect | |
let res = _macro.call( q, _ ) | |
} | |
export var classWriter = ( className ) => { | |
( _el.classList ) | |
? _el.classList.add( className ) | |
: _el.className += className | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment