UNPKG

rambdax

Version:

Extended version of Rambda - a lightweight, faster alternative to Ramda

113 lines (84 loc) 2.56 kB
import { type } from './type' function parseError(maybeError){ const typeofError = maybeError.__proto__.toString() if (![ 'Error', 'TypeError' ].includes(typeofError)) return [] return [ typeofError, maybeError.message ] } function parseDate(maybeDate){ if (!maybeDate.toDateString) return [ false ] return [ true, maybeDate.getTime() ] } function parseRegex(maybeRegex){ if (maybeRegex.constructor !== RegExp) return [ false ] return [ true, maybeRegex.toString() ] } export function equals(a, b){ if (arguments.length === 1) return _b => equals(a, _b) const aType = type(a) if (aType !== type(b)) return false if (aType === 'Function'){ return a.name === undefined ? false : a.name === b.name } if ([ 'NaN', 'Undefined', 'Null' ].includes(aType)) return true if (aType === 'Number'){ if (Object.is(-0, a) !== Object.is(-0, b)) return false return a.toString() === b.toString() } if ([ 'String', 'Boolean' ].includes(aType)){ return a.toString() === b.toString() } if (aType === 'Array'){ const aClone = Array.from(a) const bClone = Array.from(b) if (aClone.toString() !== bClone.toString()){ return false } let loopArrayFlag = true aClone.forEach((aCloneInstance, aCloneIndex) => { if (loopArrayFlag){ if ( aCloneInstance !== bClone[ aCloneIndex ] && !equals(aCloneInstance, bClone[ aCloneIndex ]) ){ loopArrayFlag = false } } }) return loopArrayFlag } const aRegex = parseRegex(a) const bRegex = parseRegex(b) if (aRegex[ 0 ]){ return bRegex[ 0 ] ? aRegex[ 1 ] === bRegex[ 1 ] : false } else if (bRegex[ 0 ]) return false const aDate = parseDate(a) const bDate = parseDate(b) if (aDate[ 0 ]){ return bDate[ 0 ] ? aDate[ 1 ] === bDate[ 1 ] : false } else if (bDate[ 0 ]) return false const aError = parseError(a) const bError = parseError(b) if (aError[ 0 ]){ return bError[ 0 ] ? aError[ 0 ] === bError[ 0 ] && aError[ 1 ] === bError[ 1 ] : false } if (aType === 'Object'){ const aKeys = Object.keys(a) if (aKeys.length !== Object.keys(b).length){ return false } let loopObjectFlag = true aKeys.forEach(aKeyInstance => { if (loopObjectFlag){ const aValue = a[ aKeyInstance ] const bValue = b[ aKeyInstance ] if (aValue !== bValue && !equals(aValue, bValue)){ loopObjectFlag = false } } }) return loopObjectFlag } return false }