Skip to content

Instantly share code, notes, and snippets.

@moshmage
Created October 16, 2018 21:56
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save moshmage/fbfaf27547758b5536eee2abb29122ec to your computer and use it in GitHub Desktop.
force a variable to follow the value of a model
const isObject = (o) => (o instanceof Object && !Array.isArray(o));
const areObjects = (...o) => !o.some(oo => !isObject(oo));
const areArrays = (...a) => !a.some(aa => !Array.isArray(aa));
function typeCheck(source, mock) {
if (areArrays(source, mock)) {
if (!source.length) return true;
return !mock.some((v, i) => !typeCheck(source[i], v))
}
if (areObjects(source, mock)) {
return !Object.keys(mock).some(k => !typeCheck(source[k], mock[k]))
}
return (!isObject(source) && !isObject(mock)) &&
(!Array.isArray(source) && !Array.isArray(mock)) &&
typeof source === typeof mock;
}
console.log('TypeCheck (simple)\n');
console.log(typeCheck(1,1), 'number, number');
console.log(typeCheck({hello: 'world'}, {hello: ''}), 'object, key: string')
console.log(typeCheck([1], [1]), 'array, numbers');
console.log(typeCheck([], [1]), 'array, empty source');
// console.log('--- fails ---')
// console.log(typeCheck({hello: []}, {hello: {}}), 'object, array vs object');
// console.log(typeCheck({keys: 'matter'}, {matter: 'keys'}), 'object, wrong keys');
function forceType(source, model) {
if (areArrays(source, model) || !source && Array.isArray(model)) {
if (!source || !source.length) {
source = [];
return source;
}
if (!model.length || !model) return model = source;
model.forEach((v, i) => source[i] = forceType(source[i], model[i]))
}
if (areObjects(source, model) || !source && isObject(model)) {
if (!source) source = {}
Object.keys(model).forEach(k => source[k] = forceType(source[k], model[k]))
}
if (!source && model) source = model;
return typeCheck(source, model) ? source : model;
}
console.log('\nForceType (simple)\n')
console.log(forceType({hello: 1}, {world: 2}), 'force world into object')
console.log(forceType([2], [1]), 'primitives inside array arent mutated');
console.log(forceType([], [{world: 2}]), 'empty arrays arent mutated');
console.log(forceType([{}], [{world: 2}]), 'arrays with objects are');
console.log(forceType({}, {world: 1}), 'existing objects in model are mandatory')
console.log(forceType(null, {world: 1}), 'falsy values will be modeled')
console.log(forceType({world: null, hello: false}, {world: 1, hello: []}), 'falsy prop values will be mutated match the model');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment