Created
July 30, 2018 03:05
-
-
Save morgan3d/86c54369392a0654e6fd850c06aa43f9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| /* | |
| Applies arithmetic vector op to all elements of a and b. | |
| If one is an object, then the result is also an object | |
| */ | |
| function _ch_vecApply(opname, op, a, b) { | |
| var c, i, p; | |
| var noB = arguments.length <= 3; | |
| if (isNumber(a)) { | |
| if (noB || isNumber(b)) { | |
| c = op(a, b); | |
| } else if (isArray(b)) { | |
| // scalar + array | |
| c = []; | |
| for (i = 0; i < b.length; ++i) c[i] = op(a, b[i]); | |
| } else { | |
| // scalar + object | |
| c = Object.create(Object.getPrototypeOf(b)); | |
| for (p in b) if (b.hasOwnProperty(p)) c[p] = op(a, b[p]); | |
| } | |
| } else if (! noB && isNumber(b)) { | |
| if (isArray(a)) { | |
| c = []; | |
| for (i = 0; i < a.length; ++i) c[i] = op(a[i], b); | |
| } else { | |
| // object + scalar | |
| c = Object.create(Object.getPrototypeOf(a)); | |
| for (p in a) if (a.hasOwnProperty(p)) c[p] = op(a[p], b); | |
| } | |
| } else if (isArray(a)) { | |
| if (noB) { | |
| c = []; | |
| for (i = 0; i < a.length; ++i) c[i] = op(a[i]); | |
| } else { | |
| // array + array | |
| if (! noB && ! isArray(b)) _ch_error('Cannot apply ' + opname + ' an array and an object'); | |
| if (! noB && (a.length !== b.length)) _ch_error('Cannot apply ' + opname + ' to arrays of different lengths'); | |
| c = []; | |
| for (i = 0; i < a.length; ++i) c[i] = op(a[i], b[i]); | |
| } | |
| } else if (noB) { | |
| c = Object.create(Object.getPrototypeOf(a)); | |
| for (p in a) if (a.hasOwnProperty(p)) c[p] = op(a[p]); | |
| } else { | |
| // object + object | |
| if (isArray(b)) _ch_error('Cannot apply ' + opname + ' an object and an array'); | |
| p = Object.getPrototypeOf(a); | |
| if ((p !== Object.getPrototypeOf(b))) _ch_error('Cannot apply ' + opname + ' to ' + a + ' and ' + b + ' because they have different protot$ | |
| c = Object.create(p); | |
| for (p in a) if (a.hasOwnProperty(p)) c[p] = op(a[p], b[p]); | |
| } | |
| return c; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment