diff --git a/dist/_30s.es5.js b/dist/_30s.es5.js index 42e5dd3e8..26030e052 100644 --- a/dist/_30s.es5.js +++ b/dist/_30s.es5.js @@ -2534,14 +2534,25 @@ var validateNumber = function validateNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n; }; + var vectorDistance = function vectorDistance() { + for (var _len53 = arguments.length, coords = new Array(_len53), _key53 = 0; _key53 < _len53; _key53++) { + coords[_key53] = arguments[_key53]; + } + + var pointLength = Math.trunc(coords.length / 2); + var sum = coords.slice(0, pointLength).reduce(function (acc, val, i) { + return acc + Math.pow(val - coords[pointLength + i], 2); + }, 0); + return Math.sqrt(sum); + }; var when = function when(pred, whenTrue) { return function (x) { return pred(x) ? whenTrue(x) : x; }; }; var without = function without(arr) { - for (var _len53 = arguments.length, args = new Array(_len53 > 1 ? _len53 - 1 : 0), _key53 = 1; _key53 < _len53; _key53++) { - args[_key53 - 1] = arguments[_key53]; + for (var _len54 = arguments.length, args = new Array(_len54 > 1 ? _len54 - 1 : 0), _key54 = 1; _key54 < _len54; _key54++) { + args[_key54 - 1] = arguments[_key54]; } return arr.filter(function (v) { @@ -2564,8 +2575,8 @@ return /^(y|yes)$/i.test(val) ? true : /^(n|no)$/i.test(val) ? false : def; }; var zip = function zip() { - for (var _len54 = arguments.length, arrays = new Array(_len54), _key54 = 0; _key54 < _len54; _key54++) { - arrays[_key54] = arguments[_key54]; + for (var _len55 = arguments.length, arrays = new Array(_len55), _key55 = 0; _key55 < _len55; _key55++) { + arrays[_key55] = arguments[_key55]; } var maxLength = Math.max.apply(Math, _toConsumableArray(arrays.map(function (x) { @@ -2587,8 +2598,8 @@ }, {}); }; var zipWith = function zipWith() { - for (var _len55 = arguments.length, array = new Array(_len55), _key55 = 0; _key55 < _len55; _key55++) { - array[_key55] = arguments[_key55]; + for (var _len56 = arguments.length, array = new Array(_len56), _key56 = 0; _key56 < _len56; _key56++) { + array[_key56] = arguments[_key56]; } var fn = typeof array[array.length - 1] === 'function' ? array.pop() : undefined; @@ -2939,6 +2950,7 @@ exports.unzip = unzip; exports.unzipWith = unzipWith; exports.validateNumber = validateNumber; + exports.vectorDistance = vectorDistance; exports.when = when; exports.without = without; exports.words = words; diff --git a/dist/_30s.es5.min.js b/dist/_30s.es5.min.js index eca820697..3e0a95d6e 100644 --- a/dist/_30s.es5.min.js +++ b/dist/_30s.es5.min.js @@ -1 +1 @@ -(function(e,t){'object'==typeof exports&&'undefined'!=typeof module?t(exports):'function'==typeof define&&define.amd?define(['exports'],t):t(e._30s={})})(this,function(e){'use strict';function t(e){return t='function'==typeof Symbol&&'symbol'==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&'function'==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?'symbol':typeof e},t(e)}function n(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e){for(var t=1;t>e/4).toString(16)})},e.UUIDGeneratorNode=function(){return'10000000-1000-4000-8000-100000000000'.replace(/[018]/g,function(e){return(e^x.randomBytes(1)[0]&15>>e/4).toString(16)})},e.all=function(e){var t=1'.concat(e,'')}).join('')}()},e.ary=function(e,t){return function(){for(var n=arguments.length,i=Array(n),r=0;rt||t>e)return 0;if(0===t||t===e)return 1;if(1===t||t===e-1)return e;e-t=(document.documentElement.scrollHeight||document.documentElement.clientHeight)},e.btoa=function(e){return Buffer.from(e,'binary').toString('base64')},e.byteSize=function(e){return new Blob([e]).size},e.call=function(e){for(var t=arguments.length,n=Array(1(n-t)*i?-i:i,o=setInterval(function(){a+=l,document.querySelector(e).innerHTML=a,a>=n&&(document.querySelector(e).innerHTML=n),a>=n&&clearInterval(o)},j(k(r/(n-t))));return o},e.createDirIfNotExists=function(e){return S.existsSync(e)?void 0:S.mkdirSync(e)},e.createElement=function(e){var t=document.createElement('div');return t.innerHTML=e,t.firstElementChild},e.createEventHub=function(){return{hub:Object.create(null),emit:function(e,t){(this.hub[e]||[]).forEach(function(e){return e(t)})},on:function(e,t){this.hub[e]||(this.hub[e]=[]),this.hub[e].push(t)},off:function(e,t){var n=(this.hub[e]||[]).findIndex(function(e){return e===t});-1'"]/g,function(e){return{"&":'&',"<":'<',">":'>',"'":''','"':'"'}[e]||e})},e.escapeRegExp=function(e){return e.replace(/[.*+?^${}()|[\]\\]/g,'\\$&')},e.everyNth=function(e,t){return e.filter(function(n,e){return e%t==t-1})},e.extendHex=function(e){return'#'+e.slice(e.startsWith('#')?1:0).split('').map(function(e){return e+e}).join('')},e.factorial=function e(t){return 0>t?function(){throw new TypeError('Negative numbers are not allowed!')}():1>=t?1:t*e(t-1)},e.fibonacci=function(e){return Array.from({length:e}).reduce(function(e,t,n){return e.concat(1e&&(e=-e);var t={day:k(e/864e5),hour:k(e/36e5)%24,minute:k(e/6e4)%60,second:k(e/1e3)%60,millisecond:k(e)%1e3};return Object.entries(t).filter(function(e){return 0!==e[1]}).map(function(e){var t=r(e,2),n=t[0],i=t[1];return''.concat(i,' ').concat(n).concat(1===i?'':'s')}).join(', ')},e.fromCamelCase=function(e){var t=1e?e%12+'am':e%12+'pm'},e.getScrollPosition=function(){var e=0>>(t?24:16))+', '+((n&(t?16711680:65280))>>>(t?16:8))+', '+((n&(t?65280:255))>>>(t?8:0))+(t?', '.concat(255&n):'')+')'},e.hide=function(){for(var e=arguments.length,t=Array(e),n=0;nn){var i=[t,n];n=i[0],t=i[1]}return null==n?0<=e&&e=t&&et},e.isAnagram=function(e,t){var n=function(e){return e.toLowerCase().replace(/[^a-z0-9]/gi,'').split('').sort().join('')};return n(e)===n(t)},e.isArrayLike=function(e){return null!=e&&'function'==typeof e[Symbol.iterator]},e.isBeforeDate=function(e,t){return ee.length?t:e})},e.lowercaseKeys=function(e){return Object.keys(e).reduce(function(t,n){return t[n.toLowerCase()]=e[n],t},{})},e.luhnCheck=function(e){var t=(e+'').split('').reverse().map(function(e){return parseInt(e)}),n=t.splice(0,1)[0],i=t.reduce(function(e,t,n){return 0==n%2?e+2*t%9||9:e+t},0);return i+=n,0==i%10},e.mapKeys=function(e,t){return Object.keys(e).reduce(function(n,i){return n[t(e[i],i,e)]=e[i],n},{})},e.mapNumRange=function(e,t,n,i,r){return(e-t)*(r-i)/(n-t)+i},e.mapObject=function(e,t){return function(n){return n=[e,e.map(t)],n[0].reduce(function(e,t,i){return e[t]=n[1][i],e},{})}()},e.mapString=function(e,t){return e.split('').map(function(n,r){return t(n,r,e)}).join('')},e.mapValues=function(e,t){return Object.keys(e).reduce(function(n,i){return n[i]=t(e[i],i,e),n},{})},e.mask=function(e){var t=1r-n&&(t='mouse',e(t),document.removeEventListener('mousemove',i)),n=r};document.addEventListener('touchstart',function(){'touch'==t||(t='touch',e(t),document.addEventListener('mousemove',i))})},e.once=function(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,i=Array(n),r=0;rd?1:sj(e))return e+(i?' ':'')+r[0];var a=m(k(Math.log10(0>e?-e:e)/3),r.length-1),l=+((0>e?-e:e)/u(1e3,a)).toPrecision(t);return(0>e?'-':'')+l+(i?' ':'')+r[a]},e.primes=function(e){var t=Array.from({length:e-1}).map(function(e,t){return t+2}),n=k(g(e)),i=Array.from({length:n-1}).map(function(e,t){return t+2});return i.forEach(function(e){return t=t.filter(function(t){return 0!=t%e||t===e})}),t},e.promisify=function(e){return function(){for(var t=arguments.length,n=Array(t),i=0;ie[e.length-1],i=e.findIndex(function(e){return n?t>=e:t<=e});return-1===i?e.length:i},e.sortedIndexBy=function(e,t,n){var i=n(e[0])>n(e[e.length-1]),r=n(t),a=e.findIndex(function(e){return i?r>=n(e):r<=n(e)});return-1===a?e.length:a},e.sortedLastIndex=function(e,t){var n=e[0]>e[e.length-1],i=e.reverse().findIndex(function(e){return n?t<=e:t>=e});return-1===i?0:e.length-i},e.sortedLastIndexBy=function(e,t,n){var i=n(e[0])>n(e[e.length-1]),r=n(t),a=e.map(n).reverse().findIndex(function(e){return i?r<=e:r>=e});return-1===a?0:e.length-a},e.splitLines=function(e){return e.split(/\r?\n/)},e.spreadOver=function(e){return function(t){return e.apply(void 0,o(t))}},e.stableSort=function(e,t){return e.map(function(e,t){return{item:e,index:t}}).sort(function(e,n){return t(e.item,n.item)||e.index-n.index}).map(function(e){var t=e.item;return t})},e.standardDeviation=function(e){var t=!!(1=t.length?2===t.length?[t,t[1]+t[0]]:[t]:t.split('').reduce(function(n,r,a){return n.concat(e(t.slice(0,a)+t.slice(a+1)).map(function(e){return r+e}))},[])},e.stripHTMLTags=function(e){return e.replace(/<[^>]*>/g,'')},e.sum=function(){for(var e=arguments.length,t=Array(e),n=0;n=t&&(e.apply(a,l),r=Date.now())},_(t-(Date.now()-r),0))):(e.apply(a,l),r=Date.now(),n=!0)}},e.timeTaken=function(e){console.time('timeTaken');var t=e();return console.timeEnd('timeTaken'),t},e.times=function(e,t){for(var n=2t?e.slice(0,3r.length)throw new RangeError('Arguments too few!');return n(e)(r.slice(0,t))}},e.unescapeHTML=function(e){return e.replace(/&|<|>|'|"/g,function(e){return{"&":'&',"<":'<',">":'>',"'":'\'',""":'"'}[e]||e})},e.unflattenObject=function(e){return Object.keys(e).reduce(function(t,n){if(-1!==n.indexOf('.')){var r=n.split('.');Object.assign(t,JSON.parse('{'+r.map(function(e,t){return t===r.length-1?'"'.concat(e,'":'):'"'.concat(e,'":{')}).join('')+e[n]+'}'.repeat(r.length)))}else t[n]=e[n];return t},{})},e.unfold=function(e,t){for(var n=[],i=[null,t];i=e(i[1]);)n.push(i[0]);return n},e.union=function(e,t){return Array.from(new Set(o(e).concat(o(t))))},e.unionBy=function(e,t,n){var i=new Set(e.map(n));return Array.from(new Set(o(e).concat(o(t.filter(function(e){return!i.has(n(e))})))))},e.unionWith=function(e,t,n){return Array.from(new Set(o(e).concat(o(t.filter(function(t){return-1===e.findIndex(function(e){return n(t,e)})})))))},e.uniqueElements=function(e){return o(new Set(e))},e.uniqueElementsBy=function(e,t){return e.reduce(function(e,n){return e.some(function(e){return t(n,e)})||e.push(n),e},[])},e.uniqueElementsByRight=function(e,t){return e.reduceRight(function(e,n){return e.some(function(e){return t(n,e)})||e.push(n),e},[])},e.uniqueSymmetricDifference=function(e,t){return o(new Set(o(e.filter(function(e){return!t.includes(e)})).concat(o(t.filter(function(t){return!e.includes(t)})))))},e.untildify=function(e){return e.replace(/^~($|\/|\\)/,''.concat(require('os').homedir(),'$1'))},e.unzip=function(e){return e.reduce(function(e,t){return t.forEach(function(t,n){return e[n].push(t)}),e},Array.from({length:_.apply(Math,o(e.map(function(e){return e.length})))}).map(function(){return[]}))},e.unzipWith=function(e,t){return e.reduce(function(e,t){return t.forEach(function(t,n){return e[n].push(t)}),e},Array.from({length:_.apply(Math,o(e.map(function(e){return e.length})))}).map(function(){return[]})).map(function(e){return t.apply(void 0,o(e))})},e.validateNumber=function(e){return!isNaN(parseFloat(e))&&isFinite(e)&&+e==e},e.when=function(e,t){return function(n){return e(n)?t(n):n}},e.without=function(e){for(var t=arguments.length,n=Array(1>e/4).toString(16)})},e.UUIDGeneratorNode=function(){return'10000000-1000-4000-8000-100000000000'.replace(/[018]/g,function(e){return(e^x.randomBytes(1)[0]&15>>e/4).toString(16)})},e.all=function(e){var t=1'.concat(e,'')}).join('')}()},e.ary=function(e,t){return function(){for(var n=arguments.length,i=Array(n),r=0;rt||t>e)return 0;if(0===t||t===e)return 1;if(1===t||t===e-1)return e;e-t=(document.documentElement.scrollHeight||document.documentElement.clientHeight)},e.btoa=function(e){return Buffer.from(e,'binary').toString('base64')},e.byteSize=function(e){return new Blob([e]).size},e.call=function(e){for(var t=arguments.length,n=Array(1(n-t)*i?-i:i,o=setInterval(function(){a+=l,document.querySelector(e).innerHTML=a,a>=n&&(document.querySelector(e).innerHTML=n),a>=n&&clearInterval(o)},j(k(r/(n-t))));return o},e.createDirIfNotExists=function(e){return S.existsSync(e)?void 0:S.mkdirSync(e)},e.createElement=function(e){var t=document.createElement('div');return t.innerHTML=e,t.firstElementChild},e.createEventHub=function(){return{hub:Object.create(null),emit:function(e,t){(this.hub[e]||[]).forEach(function(e){return e(t)})},on:function(e,t){this.hub[e]||(this.hub[e]=[]),this.hub[e].push(t)},off:function(e,t){var n=(this.hub[e]||[]).findIndex(function(e){return e===t});-1'"]/g,function(e){return{"&":'&',"<":'<',">":'>',"'":''','"':'"'}[e]||e})},e.escapeRegExp=function(e){return e.replace(/[.*+?^${}()|[\]\\]/g,'\\$&')},e.everyNth=function(e,t){return e.filter(function(n,e){return e%t==t-1})},e.extendHex=function(e){return'#'+e.slice(e.startsWith('#')?1:0).split('').map(function(e){return e+e}).join('')},e.factorial=function e(t){return 0>t?function(){throw new TypeError('Negative numbers are not allowed!')}():1>=t?1:t*e(t-1)},e.fibonacci=function(e){return Array.from({length:e}).reduce(function(e,t,n){return e.concat(1e&&(e=-e);var t={day:k(e/864e5),hour:k(e/36e5)%24,minute:k(e/6e4)%60,second:k(e/1e3)%60,millisecond:k(e)%1e3};return Object.entries(t).filter(function(e){return 0!==e[1]}).map(function(e){var t=r(e,2),n=t[0],i=t[1];return''.concat(i,' ').concat(n).concat(1===i?'':'s')}).join(', ')},e.fromCamelCase=function(e){var t=1e?e%12+'am':e%12+'pm'},e.getScrollPosition=function(){var e=0>>(t?24:16))+', '+((n&(t?16711680:65280))>>>(t?16:8))+', '+((n&(t?65280:255))>>>(t?8:0))+(t?', '.concat(255&n):'')+')'},e.hide=function(){for(var e=arguments.length,t=Array(e),n=0;nn){var i=[t,n];n=i[0],t=i[1]}return null==n?0<=e&&e=t&&et},e.isAnagram=function(e,t){var n=function(e){return e.toLowerCase().replace(/[^a-z0-9]/gi,'').split('').sort().join('')};return n(e)===n(t)},e.isArrayLike=function(e){return null!=e&&'function'==typeof e[Symbol.iterator]},e.isBeforeDate=function(e,t){return ee.length?t:e})},e.lowercaseKeys=function(e){return Object.keys(e).reduce(function(t,n){return t[n.toLowerCase()]=e[n],t},{})},e.luhnCheck=function(e){var t=(e+'').split('').reverse().map(function(e){return parseInt(e)}),n=t.splice(0,1)[0],i=t.reduce(function(e,t,n){return 0==n%2?e+2*t%9||9:e+t},0);return i+=n,0==i%10},e.mapKeys=function(e,t){return Object.keys(e).reduce(function(n,i){return n[t(e[i],i,e)]=e[i],n},{})},e.mapNumRange=function(e,t,n,i,r){return(e-t)*(r-i)/(n-t)+i},e.mapObject=function(e,t){return function(n){return n=[e,e.map(t)],n[0].reduce(function(e,t,i){return e[t]=n[1][i],e},{})}()},e.mapString=function(e,t){return e.split('').map(function(n,r){return t(n,r,e)}).join('')},e.mapValues=function(e,t){return Object.keys(e).reduce(function(n,i){return n[i]=t(e[i],i,e),n},{})},e.mask=function(e){var t=1r-n&&(t='mouse',e(t),document.removeEventListener('mousemove',i)),n=r};document.addEventListener('touchstart',function(){'touch'==t||(t='touch',e(t),document.addEventListener('mousemove',i))})},e.once=function(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,i=Array(n),r=0;rd?1:sj(e))return e+(i?' ':'')+r[0];var a=m(k(Math.log10(0>e?-e:e)/3),r.length-1),l=+((0>e?-e:e)/u(1e3,a)).toPrecision(t);return(0>e?'-':'')+l+(i?' ':'')+r[a]},e.primes=function(e){var t=Array.from({length:e-1}).map(function(e,t){return t+2}),n=k(g(e)),i=Array.from({length:n-1}).map(function(e,t){return t+2});return i.forEach(function(e){return t=t.filter(function(t){return 0!=t%e||t===e})}),t},e.promisify=function(e){return function(){for(var t=arguments.length,n=Array(t),i=0;ie[e.length-1],i=e.findIndex(function(e){return n?t>=e:t<=e});return-1===i?e.length:i},e.sortedIndexBy=function(e,t,n){var i=n(e[0])>n(e[e.length-1]),r=n(t),a=e.findIndex(function(e){return i?r>=n(e):r<=n(e)});return-1===a?e.length:a},e.sortedLastIndex=function(e,t){var n=e[0]>e[e.length-1],i=e.reverse().findIndex(function(e){return n?t<=e:t>=e});return-1===i?0:e.length-i},e.sortedLastIndexBy=function(e,t,n){var i=n(e[0])>n(e[e.length-1]),r=n(t),a=e.map(n).reverse().findIndex(function(e){return i?r<=e:r>=e});return-1===a?0:e.length-a},e.splitLines=function(e){return e.split(/\r?\n/)},e.spreadOver=function(e){return function(t){return e.apply(void 0,o(t))}},e.stableSort=function(e,t){return e.map(function(e,t){return{item:e,index:t}}).sort(function(e,n){return t(e.item,n.item)||e.index-n.index}).map(function(e){var t=e.item;return t})},e.standardDeviation=function(e){var t=!!(1=t.length?2===t.length?[t,t[1]+t[0]]:[t]:t.split('').reduce(function(n,r,a){return n.concat(e(t.slice(0,a)+t.slice(a+1)).map(function(e){return r+e}))},[])},e.stripHTMLTags=function(e){return e.replace(/<[^>]*>/g,'')},e.sum=function(){for(var e=arguments.length,t=Array(e),n=0;n=t&&(e.apply(a,l),r=Date.now())},_(t-(Date.now()-r),0))):(e.apply(a,l),r=Date.now(),n=!0)}},e.timeTaken=function(e){console.time('timeTaken');var t=e();return console.timeEnd('timeTaken'),t},e.times=function(e,t){for(var n=2t?e.slice(0,3r.length)throw new RangeError('Arguments too few!');return n(e)(r.slice(0,t))}},e.unescapeHTML=function(e){return e.replace(/&|<|>|'|"/g,function(e){return{"&":'&',"<":'<',">":'>',"'":'\'',""":'"'}[e]||e})},e.unflattenObject=function(e){return Object.keys(e).reduce(function(t,n){if(-1!==n.indexOf('.')){var r=n.split('.');Object.assign(t,JSON.parse('{'+r.map(function(e,t){return t===r.length-1?'"'.concat(e,'":'):'"'.concat(e,'":{')}).join('')+e[n]+'}'.repeat(r.length)))}else t[n]=e[n];return t},{})},e.unfold=function(e,t){for(var n=[],i=[null,t];i=e(i[1]);)n.push(i[0]);return n},e.union=function(e,t){return Array.from(new Set(o(e).concat(o(t))))},e.unionBy=function(e,t,n){var i=new Set(e.map(n));return Array.from(new Set(o(e).concat(o(t.filter(function(e){return!i.has(n(e))})))))},e.unionWith=function(e,t,n){return Array.from(new Set(o(e).concat(o(t.filter(function(t){return-1===e.findIndex(function(e){return n(t,e)})})))))},e.uniqueElements=function(e){return o(new Set(e))},e.uniqueElementsBy=function(e,t){return e.reduce(function(e,n){return e.some(function(e){return t(n,e)})||e.push(n),e},[])},e.uniqueElementsByRight=function(e,t){return e.reduceRight(function(e,n){return e.some(function(e){return t(n,e)})||e.push(n),e},[])},e.uniqueSymmetricDifference=function(e,t){return o(new Set(o(e.filter(function(e){return!t.includes(e)})).concat(o(t.filter(function(t){return!e.includes(t)})))))},e.untildify=function(e){return e.replace(/^~($|\/|\\)/,''.concat(require('os').homedir(),'$1'))},e.unzip=function(e){return e.reduce(function(e,t){return t.forEach(function(t,n){return e[n].push(t)}),e},Array.from({length:_.apply(Math,o(e.map(function(e){return e.length})))}).map(function(){return[]}))},e.unzipWith=function(e,t){return e.reduce(function(e,t){return t.forEach(function(t,n){return e[n].push(t)}),e},Array.from({length:_.apply(Math,o(e.map(function(e){return e.length})))}).map(function(){return[]})).map(function(e){return t.apply(void 0,o(e))})},e.validateNumber=function(e){return!isNaN(parseFloat(e))&&isFinite(e)&&+e==e},e.vectorDistance=function(){for(var e=arguments.length,t=Array(e),n=0;n ? obj.map(val => deepMapKeys(val, f)) : typeof obj === 'object' ? Object.keys(obj).reduce((acc, current) => { - const val = obj[current]; - acc[f(current)] = + const val = obj[current]; + acc[f(current)] = val !== null && typeof val === 'object' ? deepMapKeys(val, f) : (acc[f(current)] = val); - return acc; - }, {}) + return acc; + }, {}) : obj; const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj); const defer = (fn, ...args) => setTimeout(fn, 1, ...args); @@ -264,9 +264,9 @@ const dig = (obj, target) => target in obj ? obj[target] : Object.values(obj).reduce((acc, val) => { - if (acc !== undefined) return acc; - if (typeof val === 'object') return dig(val, target); - }, undefined); + if (acc !== undefined) return acc; + if (typeof val === 'object') return dig(val, target); + }, undefined); const digitize = n => [...`${n}`].map(i => parseInt(i)); const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0); const drop = (arr, n = 1) => arr.slice(n); @@ -338,8 +338,8 @@ const extendHex = shortHex => const factorial = n => n < 0 ? (() => { - throw new TypeError('Negative numbers are not allowed!'); - })() + throw new TypeError('Negative numbers are not allowed!'); + })() : n <= 1 ? 1 : n * factorial(n - 1); @@ -985,9 +985,9 @@ const reject = (pred, array) => array.filter((...args) => !pred(...args)); const remove = (arr, func) => Array.isArray(arr) ? arr.filter(func).reduce((acc, val) => { - arr.splice(arr.indexOf(val), 1); - return acc.concat(val); - }, []) + arr.splice(arr.indexOf(val), 1); + return acc.concat(val); + }, []) : []; const removeNonASCII = str => str.replace(/[^\x20-\x7E]/g, ''); const renameKeys = (keysMap, obj) => @@ -1321,6 +1321,13 @@ const unzipWith = (arr, fn) => ) .map(val => fn(...val)); const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n; +const vectorDistance = (...coords) => { + let pointLength = Math.trunc(coords.length / 2); + let sum = coords + .slice(0, pointLength) + .reduce((acc, val, i) => acc + Math.pow(val - coords[pointLength + i], 2), 0); + return Math.sqrt(sum); +}; const when = (pred, whenTrue) => x => (pred(x) ? whenTrue(x) : x); const without = (arr, ...args) => arr.filter(v => !args.includes(v)); const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean); @@ -1343,4 +1350,4 @@ const zipWith = (...array) => { ); }; -export { CSVToArray, CSVToJSON, JSONToFile, JSONtoCSV, RGBToHex, URLJoin, UUIDGeneratorBrowser, UUIDGeneratorNode, all, allEqual, any, approximatelyEqual, arrayToCSV, arrayToHtmlList, ary, atob, attempt, average, averageBy, bifurcate, bifurcateBy, bind, bindAll, bindKey, binomialCoefficient, bottomVisible, btoa, byteSize, call, capitalize, capitalizeEveryWord, castArray, chainAsync, chunk, clampNumber, cloneRegExp, coalesce, coalesceFactory, collectInto, colorize, compact, compactWhitespace, compose, composeRight, converge, copyToClipboard, countBy, countOccurrences, counter, createDirIfNotExists, createElement, createEventHub, currentURL, curry, dayOfYear, debounce, decapitalize, deepClone, deepFlatten, deepFreeze, deepMapKeys, defaults, defer, degreesToRads, delay, detectDeviceType, difference, differenceBy, differenceWith, dig, digitize, distance, drop, dropRight, dropRightWhile, dropWhile, elementContains, elementIsVisibleInViewport, elo, equals, escapeHTML, escapeRegExp, everyNth, extendHex, factorial, fibonacci, filterFalsy, filterNonUnique, filterNonUniqueBy, findKey, findLast, findLastIndex, findLastKey, flatten, flattenObject, flip, forEachRight, forOwn, forOwnRight, formatDuration, fromCamelCase, functionName, functions, gcd, geometricProgression, get, getColonTimeFromDate, getDaysDiffBetweenDates, getImages, getMeridiemSuffixOfInteger, getScrollPosition, getStyle, getType, getURLParameters, groupBy, hammingDistance, hasClass, hasFlags, hashBrowser, hashNode, head, hexToRGB, hide, httpGet, httpPost, httpsRedirect, hz, inRange, indentString, indexOfAll, initial, initialize2DArray, initializeArrayWithRange, initializeArrayWithRangeRight, initializeArrayWithValues, initializeNDArray, insertAfter, insertBefore, intersection, intersectionBy, intersectionWith, invertKeyValues, is, isAbsoluteURL, isAfterDate, isAnagram, isArrayLike, isBeforeDate, isBoolean, isBrowser, isBrowserTabFocused, isDivisible, isDuplexStream, isEmpty, isEven, isFunction, isLowerCase, isNegativeZero, isNil, isNull, isNumber, isObject, isObjectLike, isPlainObject, isPrime, isPrimitive, isPromiseLike, isReadableStream, isSameDate, isSorted, isStream, isString, isSymbol, isTravisCI, isUndefined, isUpperCase, isValidJSON, isWritableStream, join, last, lcm, longestItem, lowercaseKeys, luhnCheck, mapKeys, mapNumRange, mapObject, mapString, mapValues, mask, matches, matchesWith, maxBy, maxDate, maxN, median, memoize, merge, midpoint, minBy, minDate, minN, mostPerformant, negate, nest, nodeListToArray, none, nthArg, nthElement, objectFromPairs, objectToPairs, observeMutations, off, offset, omit, omitBy, on, onUserInputChange, once, orderBy, over, overArgs, pad, palindrome, parseCookie, partial, partialRight, partition, percentile, permutations, pick, pickBy, pipeAsyncFunctions, pipeFunctions, pluralize, powerset, prefix, prettyBytes, primes, promisify, pull, pullAtIndex, pullAtValue, pullBy, radsToDegrees, randomHexColorCode, randomIntArrayInRange, randomIntegerInRange, randomNumberInRange, readFileLines, rearg, recordAnimationFrames, redirect, reduceSuccessive, reduceWhich, reducedFilter, reject, remove, removeNonASCII, renameKeys, reverseString, round, runAsync, runPromisesInSeries, sample, sampleSize, scrollToTop, sdbm, serializeCookie, setStyle, shallowClone, shank, show, shuffle, similarity, size, sleep, smoothScroll, sortCharactersInString, sortedIndex, sortedIndexBy, sortedLastIndex, sortedLastIndexBy, splitLines, spreadOver, stableSort, standardDeviation, stringPermutations, stripHTMLTags, sum, sumBy, sumPower, symmetricDifference, symmetricDifferenceBy, symmetricDifferenceWith, tail, take, takeRight, takeRightWhile, takeWhile, throttle, timeTaken, times, toCamelCase, toCurrency, toDecimalMark, toHash, toKebabCase, toOrdinalSuffix, toSafeInteger, toSnakeCase, toTitleCase, toggleClass, tomorrow, transform, triggerEvent, truncateString, truthCheckCollection, unary, uncurry, unescapeHTML, unflattenObject, unfold, union, unionBy, unionWith, uniqueElements, uniqueElementsBy, uniqueElementsByRight, uniqueSymmetricDifference, untildify, unzip, unzipWith, validateNumber, when, without, words, xProd, yesNo, zip, zipObject, zipWith }; +export { CSVToArray, CSVToJSON, JSONToFile, JSONtoCSV, RGBToHex, URLJoin, UUIDGeneratorBrowser, UUIDGeneratorNode, all, allEqual, any, approximatelyEqual, arrayToCSV, arrayToHtmlList, ary, atob, attempt, average, averageBy, bifurcate, bifurcateBy, bind, bindAll, bindKey, binomialCoefficient, bottomVisible, btoa, byteSize, call, capitalize, capitalizeEveryWord, castArray, chainAsync, chunk, clampNumber, cloneRegExp, coalesce, coalesceFactory, collectInto, colorize, compact, compactWhitespace, compose, composeRight, converge, copyToClipboard, countBy, countOccurrences, counter, createDirIfNotExists, createElement, createEventHub, currentURL, curry, dayOfYear, debounce, decapitalize, deepClone, deepFlatten, deepFreeze, deepMapKeys, defaults, defer, degreesToRads, delay, detectDeviceType, difference, differenceBy, differenceWith, dig, digitize, distance, drop, dropRight, dropRightWhile, dropWhile, elementContains, elementIsVisibleInViewport, elo, equals, escapeHTML, escapeRegExp, everyNth, extendHex, factorial, fibonacci, filterFalsy, filterNonUnique, filterNonUniqueBy, findKey, findLast, findLastIndex, findLastKey, flatten, flattenObject, flip, forEachRight, forOwn, forOwnRight, formatDuration, fromCamelCase, functionName, functions, gcd, geometricProgression, get, getColonTimeFromDate, getDaysDiffBetweenDates, getImages, getMeridiemSuffixOfInteger, getScrollPosition, getStyle, getType, getURLParameters, groupBy, hammingDistance, hasClass, hasFlags, hashBrowser, hashNode, head, hexToRGB, hide, httpGet, httpPost, httpsRedirect, hz, inRange, indentString, indexOfAll, initial, initialize2DArray, initializeArrayWithRange, initializeArrayWithRangeRight, initializeArrayWithValues, initializeNDArray, insertAfter, insertBefore, intersection, intersectionBy, intersectionWith, invertKeyValues, is, isAbsoluteURL, isAfterDate, isAnagram, isArrayLike, isBeforeDate, isBoolean, isBrowser, isBrowserTabFocused, isDivisible, isDuplexStream, isEmpty, isEven, isFunction, isLowerCase, isNegativeZero, isNil, isNull, isNumber, isObject, isObjectLike, isPlainObject, isPrime, isPrimitive, isPromiseLike, isReadableStream, isSameDate, isSorted, isStream, isString, isSymbol, isTravisCI, isUndefined, isUpperCase, isValidJSON, isWritableStream, join, last, lcm, longestItem, lowercaseKeys, luhnCheck, mapKeys, mapNumRange, mapObject, mapString, mapValues, mask, matches, matchesWith, maxBy, maxDate, maxN, median, memoize, merge, midpoint, minBy, minDate, minN, mostPerformant, negate, nest, nodeListToArray, none, nthArg, nthElement, objectFromPairs, objectToPairs, observeMutations, off, offset, omit, omitBy, on, onUserInputChange, once, orderBy, over, overArgs, pad, palindrome, parseCookie, partial, partialRight, partition, percentile, permutations, pick, pickBy, pipeAsyncFunctions, pipeFunctions, pluralize, powerset, prefix, prettyBytes, primes, promisify, pull, pullAtIndex, pullAtValue, pullBy, radsToDegrees, randomHexColorCode, randomIntArrayInRange, randomIntegerInRange, randomNumberInRange, readFileLines, rearg, recordAnimationFrames, redirect, reduceSuccessive, reduceWhich, reducedFilter, reject, remove, removeNonASCII, renameKeys, reverseString, round, runAsync, runPromisesInSeries, sample, sampleSize, scrollToTop, sdbm, serializeCookie, setStyle, shallowClone, shank, show, shuffle, similarity, size, sleep, smoothScroll, sortCharactersInString, sortedIndex, sortedIndexBy, sortedLastIndex, sortedLastIndexBy, splitLines, spreadOver, stableSort, standardDeviation, stringPermutations, stripHTMLTags, sum, sumBy, sumPower, symmetricDifference, symmetricDifferenceBy, symmetricDifferenceWith, tail, take, takeRight, takeRightWhile, takeWhile, throttle, timeTaken, times, toCamelCase, toCurrency, toDecimalMark, toHash, toKebabCase, toOrdinalSuffix, toSafeInteger, toSnakeCase, toTitleCase, toggleClass, tomorrow, transform, triggerEvent, truncateString, truthCheckCollection, unary, uncurry, unescapeHTML, unflattenObject, unfold, union, unionBy, unionWith, uniqueElements, uniqueElementsBy, uniqueElementsByRight, uniqueSymmetricDifference, untildify, unzip, unzipWith, validateNumber, vectorDistance, when, without, words, xProd, yesNo, zip, zipObject, zipWith }; diff --git a/dist/_30s.js b/dist/_30s.js index 5d041beb9..29a1b3bad 100644 --- a/dist/_30s.js +++ b/dist/_30s.js @@ -243,11 +243,11 @@ ? obj.map(val => deepMapKeys(val, f)) : typeof obj === 'object' ? Object.keys(obj).reduce((acc, current) => { - const val = obj[current]; - acc[f(current)] = + const val = obj[current]; + acc[f(current)] = val !== null && typeof val === 'object' ? deepMapKeys(val, f) : (acc[f(current)] = val); - return acc; - }, {}) + return acc; + }, {}) : obj; const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj); const defer = (fn, ...args) => setTimeout(fn, 1, ...args); @@ -270,9 +270,9 @@ target in obj ? obj[target] : Object.values(obj).reduce((acc, val) => { - if (acc !== undefined) return acc; - if (typeof val === 'object') return dig(val, target); - }, undefined); + if (acc !== undefined) return acc; + if (typeof val === 'object') return dig(val, target); + }, undefined); const digitize = n => [...`${n}`].map(i => parseInt(i)); const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0); const drop = (arr, n = 1) => arr.slice(n); @@ -344,8 +344,8 @@ const factorial = n => n < 0 ? (() => { - throw new TypeError('Negative numbers are not allowed!'); - })() + throw new TypeError('Negative numbers are not allowed!'); + })() : n <= 1 ? 1 : n * factorial(n - 1); @@ -991,9 +991,9 @@ const remove = (arr, func) => Array.isArray(arr) ? arr.filter(func).reduce((acc, val) => { - arr.splice(arr.indexOf(val), 1); - return acc.concat(val); - }, []) + arr.splice(arr.indexOf(val), 1); + return acc.concat(val); + }, []) : []; const removeNonASCII = str => str.replace(/[^\x20-\x7E]/g, ''); const renameKeys = (keysMap, obj) => @@ -1327,6 +1327,13 @@ ) .map(val => fn(...val)); const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n; + const vectorDistance = (...coords) => { + let pointLength = Math.trunc(coords.length / 2); + let sum = coords + .slice(0, pointLength) + .reduce((acc, val, i) => acc + Math.pow(val - coords[pointLength + i], 2), 0); + return Math.sqrt(sum); + }; const when = (pred, whenTrue) => x => (pred(x) ? whenTrue(x) : x); const without = (arr, ...args) => arr.filter(v => !args.includes(v)); const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean); @@ -1683,6 +1690,7 @@ exports.unzip = unzip; exports.unzipWith = unzipWith; exports.validateNumber = validateNumber; + exports.vectorDistance = vectorDistance; exports.when = when; exports.without = without; exports.words = words; diff --git a/snippet_data/snippetList.json b/snippet_data/snippetList.json index 5e214a69d..2df7be50c 100644 --- a/snippet_data/snippetList.json +++ b/snippet_data/snippetList.json @@ -811,7 +811,7 @@ "archived": false }, "meta": { - "hash": "03b2d6752610b5912a1e4019ffc7ef9f199636595ffd8c58b14cdd9ffa0ec28a" + "hash": "e66191a28aba485589b3b06933c13d999962af982b5b7b1b136c10f4d09abd8d" } }, { @@ -941,7 +941,7 @@ "archived": false }, "meta": { - "hash": "f982b4e8e3ec3c8b0c2ef4f19b38dac90df6ebe2dd4daa0126c917ebc07d3e62" + "hash": "828a6f2f3b94cc537ef0ee30c5ebda28fff688fea65030e47d5721831bdb48ce" } }, { @@ -1162,7 +1162,7 @@ "archived": false }, "meta": { - "hash": "319e1a8fb41490965ee6e28db3e139e65c4ea5b7f43e332bc7216cd790e5d409" + "hash": "383ed61e69b8f63ae42d0746a1995057f4f65b4af6ca7778d8f1771144802acd" } }, { @@ -2688,7 +2688,7 @@ "archived": false }, "meta": { - "hash": "41e67e7f95334dcb734cf92acea7e1398540a18c2358d85cde5ff82e6149a44f" + "hash": "493eaac4ff025739014196f024923baf63e6eba5317c7b364166f3e7087f5bf1" } }, { @@ -3391,7 +3391,7 @@ "archived": false }, "meta": { - "hash": "dcdf66e8d0eb4a1761c6b767b8cc350757087ae817ec371436faab0fff7c0051" + "hash": "0b04f5fe668888db0dc360535cd999669258019f0682eb6e4ad3a1164e408d13" } }, { @@ -3763,7 +3763,7 @@ "archived": false }, "meta": { - "hash": "2fd54c9fc1fb5b0a981df69501b518d5830ea77544d4d5290c7cc13745ca00ea" + "hash": "536833a64ce0c000b82327ed1bb9bcb82e35b237f75aefcca0e0d2def4e9cb63" } }, { @@ -4951,6 +4951,20 @@ "hash": "8fb993b0cf78fa83a170aca132bf5eb13430e2cef5ae06f85b9763f286bb792c" } }, + { + "id": "vectorDistance", + "type": "snippetListing", + "attributes": { + "tags": [ + "math", + "beginner" + ], + "archived": false + }, + "meta": { + "hash": "03d98fe59bf128d50085af5f2948009b08f53f53f72f2bff7421c34f70287b63" + } + }, { "id": "when", "type": "snippetListing", diff --git a/snippet_data/snippets.json b/snippet_data/snippets.json index 72694a890..ab9160298 100644 --- a/snippet_data/snippets.json +++ b/snippet_data/snippets.json @@ -1184,7 +1184,7 @@ "fileName": "deepMapKeys.md", "text": "Deep maps an object keys.\n\nCreates an object with the same values as the provided object and keys generated by running the provided function for each key.\n\nUse `Object.keys(obj)` to iterate over the object's keys. \nUse `Array.prototype.reduce()` to create a new object with the same values and mapped keys using `fn`.", "codeBlocks": { - "es6": "const deepMapKeys = (obj, f) =>\n Array.isArray(obj)\n ? obj.map(val => deepMapKeys(val, f))\n : typeof obj === 'object'\n ? Object.keys(obj).reduce((acc, current) => {\n const val = obj[current];\n acc[f(current)] =\n val !== null && typeof val === 'object' ? deepMapKeys(val, f) : (acc[f(current)] = val);\n return acc;\n }, {})\n : obj;", + "es6": "const deepMapKeys = (obj, f) =>\n Array.isArray(obj)\n ? obj.map(val => deepMapKeys(val, f))\n : typeof obj === 'object'\n ? Object.keys(obj).reduce((acc, current) => {\n const val = obj[current];\n acc[f(current)] =\n val !== null && typeof val === 'object' ? deepMapKeys(val, f) : (acc[f(current)] = val);\n return acc;\n }, {})\n : obj;", "es5": "function _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nvar deepMapKeys = function deepMapKeys(obj, f) {\n return Array.isArray(obj) ? obj.map(function (val) {\n return deepMapKeys(val, f);\n }) : _typeof(obj) === 'object' ? Object.keys(obj).reduce(function (acc, current) {\n var val = obj[current];\n acc[f(current)] = val !== null && _typeof(val) === 'object' ? deepMapKeys(val, f) : acc[f(current)] = val;\n return acc;\n }, {}) : obj;\n};", "example": "const obj = {\n foo: '1',\n nested: {\n child: {\n withArray: [\n {\n grandChild: ['hello']\n }\n ]\n }\n }\n};\nconst upperKeysObj = deepMapKeys(obj, key => key.toUpperCase());\n/*\n{\n \"FOO\":\"1\",\n \"NESTED\":{\n \"CHILD\":{\n \"WITHARRAY\":[\n {\n \"GRANDCHILD\":[ 'hello' ]\n }\n ]\n }\n }\n}\n*/" }, @@ -1196,7 +1196,7 @@ }, "meta": { "archived": false, - "hash": "03b2d6752610b5912a1e4019ffc7ef9f199636595ffd8c58b14cdd9ffa0ec28a" + "hash": "e66191a28aba485589b3b06933c13d999962af982b5b7b1b136c10f4d09abd8d" } }, { @@ -1377,7 +1377,7 @@ "fileName": "dig.md", "text": "Returns the target value in a nested JSON object, based on the given key.\n\nUse the `in` operator to check if `target` exists in `obj`.\nIf found, return the value of `obj[target]`, otherwise use `Object.values(obj)` and `Array.prototype.reduce()` to recursively call `dig` on each nested object until the first matching key/value pair is found.", "codeBlocks": { - "es6": "const dig = (obj, target) =>\n target in obj\n ? obj[target]\n : Object.values(obj).reduce((acc, val) => {\n if (acc !== undefined) return acc;\n if (typeof val === 'object') return dig(val, target);\n }, undefined);", + "es6": "const dig = (obj, target) =>\n target in obj\n ? obj[target]\n : Object.values(obj).reduce((acc, val) => {\n if (acc !== undefined) return acc;\n if (typeof val === 'object') return dig(val, target);\n }, undefined);", "es5": "function _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nvar dig = function dig(obj, target) {\n return target in obj ? obj[target] : Object.values(obj).reduce(function (acc, val) {\n if (acc !== undefined) return acc;\n if (_typeof(val) === 'object') return dig(val, target);\n }, undefined);\n};", "example": "const data = {\n level1: {\n level2: {\n level3: 'some data'\n }\n }\n};\ndig(data, 'level3'); // 'some data'\ndig(data, 'level4'); // undefined" }, @@ -1389,7 +1389,7 @@ }, "meta": { "archived": false, - "hash": "f982b4e8e3ec3c8b0c2ef4f19b38dac90df6ebe2dd4daa0126c917ebc07d3e62" + "hash": "828a6f2f3b94cc537ef0ee30c5ebda28fff688fea65030e47d5721831bdb48ce" } }, { @@ -1703,7 +1703,7 @@ "fileName": "factorial.md", "text": "Calculates the factorial of a number.\n\nUse recursion.\nIf `n` is less than or equal to `1`, return `1`.\nOtherwise, return the product of `n` and the factorial of `n - 1`.\nThrows an exception if `n` is a negative number.", "codeBlocks": { - "es6": "const factorial = n =>\n n < 0\n ? (() => {\n throw new TypeError('Negative numbers are not allowed!');\n })()\n : n <= 1\n ? 1\n : n * factorial(n - 1);", + "es6": "const factorial = n =>\n n < 0\n ? (() => {\n throw new TypeError('Negative numbers are not allowed!');\n })()\n : n <= 1\n ? 1\n : n * factorial(n - 1);", "es5": "var factorial = function factorial(n) {\n return n < 0 ? function () {\n throw new TypeError('Negative numbers are not allowed!');\n }() : n <= 1 ? 1 : n * factorial(n - 1);\n};", "example": "factorial(6); // 720" }, @@ -1715,7 +1715,7 @@ }, "meta": { "archived": false, - "hash": "319e1a8fb41490965ee6e28db3e139e65c4ea5b7f43e332bc7216cd790e5d409" + "hash": "383ed61e69b8f63ae42d0746a1995057f4f65b4af6ca7778d8f1771144802acd" } }, { @@ -3962,7 +3962,7 @@ }, "meta": { "archived": false, - "hash": "41e67e7f95334dcb734cf92acea7e1398540a18c2358d85cde5ff82e6149a44f" + "hash": "493eaac4ff025739014196f024923baf63e6eba5317c7b364166f3e7087f5bf1" } }, { @@ -4983,7 +4983,7 @@ "codeBlocks": { "es6": "const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg));", "es5": "var pipeAsyncFunctions = function pipeAsyncFunctions() {\n for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) {\n fns[_key] = arguments[_key];\n }\n\n return function (arg) {\n return fns.reduce(function (p, f) {\n return p.then(f);\n }, Promise.resolve(arg));\n };\n};", - "example": "const sum = pipeAsyncFunctions(\n x => x + 1,\n x => new Promise(resolve => setTimeout(() => resolve(x + 2), 1000)),\n x => x + 3,\n async x => (await x) + 4\n);\n(async () => {\n console.log(await sum(5)); // 15 (after one second)\n})();" + "example": "const sum = pipeAsyncFunctions(\n x => x + 1,\n x => new Promise(resolve => setTimeout(() => resolve(x + 2), 1000)),\n x => x + 3,\n async x => (await x) + 4\n);\n(async() => {\n console.log(await sum(5)); // 15 (after one second)\n})();" }, "tags": [ "adapter", @@ -4994,7 +4994,7 @@ }, "meta": { "archived": false, - "hash": "dcdf66e8d0eb4a1761c6b767b8cc350757087ae817ec371436faab0fff7c0051" + "hash": "0b04f5fe668888db0dc360535cd999669258019f0682eb6e4ad3a1164e408d13" } }, { @@ -5530,7 +5530,7 @@ "fileName": "remove.md", "text": "Removes elements from an array for which the given function returns `false`.\n\nUse `Array.prototype.filter()` to find array elements that return truthy values and `Array.prototype.reduce()` to remove elements using `Array.prototype.splice()`.\nThe `func` is invoked with three arguments (`value, index, array`).", "codeBlocks": { - "es6": "const remove = (arr, func) =>\n Array.isArray(arr)\n ? arr.filter(func).reduce((acc, val) => {\n arr.splice(arr.indexOf(val), 1);\n return acc.concat(val);\n }, [])\n : [];", + "es6": "const remove = (arr, func) =>\n Array.isArray(arr)\n ? arr.filter(func).reduce((acc, val) => {\n arr.splice(arr.indexOf(val), 1);\n return acc.concat(val);\n }, [])\n : [];", "es5": "var remove = function remove(arr, func) {\n return Array.isArray(arr) ? arr.filter(func).reduce(function (acc, val) {\n arr.splice(arr.indexOf(val), 1);\n return acc.concat(val);\n }, []) : [];\n};", "example": "remove([1, 2, 3, 4], n => n % 2 === 0); // [2, 4]" }, @@ -5541,7 +5541,7 @@ }, "meta": { "archived": false, - "hash": "2fd54c9fc1fb5b0a981df69501b518d5830ea77544d4d5290c7cc13745ca00ea" + "hash": "536833a64ce0c000b82327ed1bb9bcb82e35b237f75aefcca0e0d2def4e9cb63" } }, { @@ -7289,6 +7289,27 @@ "hash": "8fb993b0cf78fa83a170aca132bf5eb13430e2cef5ae06f85b9763f286bb792c" } }, + { + "id": "vectorDistance", + "type": "snippet", + "attributes": { + "fileName": "vectorDistance.md", + "text": "Returns the distance between two vectors.\n\nUse `Array.prototype.reduce()`, `Math.pow()` and `Math.sqrt()` to calculate the Euclidean distance between two vectors.", + "codeBlocks": { + "es6": "const vectorDistance = (...coords) => {\n let pointLength = Math.trunc(coords.length / 2);\n let sum = coords\n .slice(0, pointLength)\n .reduce((acc, val, i) => acc + Math.pow(val - coords[pointLength + i], 2), 0);\n return Math.sqrt(sum);\n};", + "es5": "var vectorDistance = function vectorDistance() {\n for (var _len = arguments.length, coords = new Array(_len), _key = 0; _key < _len; _key++) {\n coords[_key] = arguments[_key];\n }\n\n var pointLength = Math.trunc(coords.length / 2);\n var sum = coords.slice(0, pointLength).reduce(function (acc, val, i) {\n return acc + Math.pow(val - coords[pointLength + i], 2);\n }, 0);\n return Math.sqrt(sum);\n};", + "example": "vectorDistance(10, 0, 5, 20, 0, 10); // 11.180339887498949" + }, + "tags": [ + "math", + "beginner" + ] + }, + "meta": { + "archived": false, + "hash": "03d98fe59bf128d50085af5f2948009b08f53f53f72f2bff7421c34f70287b63" + } + }, { "id": "when", "type": "snippet", diff --git a/vscode_snippets/snippets.json b/vscode_snippets/snippets.json index 2fd04d4fa..9e8a22df2 100644 --- a/vscode_snippets/snippets.json +++ b/vscode_snippets/snippets.json @@ -533,11 +533,11 @@ " ? obj.map(val => deepMapKeys(val, f))", " : typeof obj === 'object'", " ? Object.keys(obj).reduce((acc, current) => {", - " const val = obj[current];", - " acc[f(current)] =", + " const val = obj[current];", + " acc[f(current)] =", " val !== null && typeof val === 'object' ? deepMapKeys(val, f) : (acc[f(current)] = val);", - " return acc;", - " }, {})", + " return acc;", + " }, {})", " : obj;" ], "description": "Deep maps an object keys.\n\nCreates an object with the same values as the provided object and keys generated by running the provided function for each key.\n\nUse `Object.keys(obj)` to iterate over the object's keys. \nUse `Array.prototype.reduce()` to create a new object with the same values and mapped keys using `fn`" @@ -614,9 +614,9 @@ " target in obj", " ? obj[target]", " : Object.values(obj).reduce((acc, val) => {", - " if (acc !== undefined) return acc;", - " if (typeof val === 'object') return dig(val, target);", - " }, undefined);" + " if (acc !== undefined) return acc;", + " if (typeof val === 'object') return dig(val, target);", + " }, undefined);" ], "description": "Returns the target value in a nested JSON object, based on the given key.\n\nUse the `in` operator to check if `target` exists in `obj`.\nIf found, return the value of `obj[target]`, otherwise use `Object.values(obj)` and `Array.prototype.reduce()` to recursively call `dig` on each nested object until the first matching key/value pair is found" }, @@ -778,8 +778,8 @@ "const factorial = n =>", " n < 0", " ? (() => {", - " throw new TypeError('Negative numbers are not allowed!');", - " })()", + " throw new TypeError('Negative numbers are not allowed!');", + " })()", " : n <= 1", " ? 1", " : n * factorial(n - 1);" @@ -2490,9 +2490,9 @@ "const remove = (arr, func) =>", " Array.isArray(arr)", " ? arr.filter(func).reduce((acc, val) => {", - " arr.splice(arr.indexOf(val), 1);", - " return acc.concat(val);", - " }, [])", + " arr.splice(arr.indexOf(val), 1);", + " return acc.concat(val);", + " }, [])", " : [];" ], "description": "Removes elements from an array for which the given function returns `false`.\n\nUse `Array.prototype.filter()` to find array elements that return truthy values and `Array.prototype.reduce()` to remove elements using `Array.prototype.splice()`.\nThe `func` is invoked with three arguments (`value, index, array`)" @@ -3328,6 +3328,19 @@ ], "description": "Returns `true` if the given value is a number, `false` otherwise.\n\nUse `!isNaN()` in combination with `parseFloat()` to check if the argument is a number.\nUse `isFinite()` to check if the number is finite.\nUse `Number()` to check if the coercion holds" }, + "vectorDistance": { + "prefix": "30s_vectorDistance", + "body": [ + "const vectorDistance = (...coords) => {", + " let pointLength = Math.trunc(coords.length / 2);", + " let sum = coords", + " .slice(0, pointLength)", + " .reduce((acc, val, i) => acc + Math.pow(val - coords[pointLength + i], 2), 0);", + " return Math.sqrt(sum);", + "};" + ], + "description": "Returns the distance between two vectors.\n\nUse `Array.prototype.reduce()`, `Math.pow()` and `Math.sqrt()` to calculate the Euclidean distance between two vectors" + }, "when": { "prefix": "30s_when", "body": [