diff --git a/README.md b/README.md index 1d9884b..2c038c3 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,17 @@ # Utileo [![NPM version](https://img.shields.io/npm/v/utileo.svg)](https://www.npmjs.com/package/utileo) [![Downloads](http://img.shields.io/npm/dm/utileo.svg)](https://npmjs.org/package/utileo) -A mini regex library for most commonly used patterns +A JS library for most commonly used utils ![Utileo](/assets/utileo.png) +## Utils + - Currency Utils + - URL Utils + - Common Utils + - Geo Location Utils + - History + - Storage Utils + - Date Utils # Getting Started (Installation) @@ -15,6 +23,137 @@ or npm i utileo --save-dev ``` +-------------------------------------------------------------------------------- +## Currency Formatter Methods + + Method | Params | Description +----------------------------------|------------------|------------------------------------------ + format | amount, isFloat | To display any and all amount-values, if isFloat is true, amount formatted to 2 decimal places + parse | amount | To parse amount-value back to number-only + beforeAPIRequest | amount | Before-submitting on any API-requests + +## Common Util Methods + + Method | Params | Description +------------------------------------|------------------|--------------------------------------------------------------- + validateName | string | Check if all characters in the string are alphabets + validateOnlyNumber | string/number | Check if it is a number + titleCase | string | Convert a string to title case + camelize | string | Convert hello-world style strings to helloWorld style strings + removeSpacesAndLowerCase | string | Converting to lower case and remove spaces in a string. Ex:My Name - myname + replaceSpaceWithUnderscore | string | Converting space to underscore in a string. Ex:My Name - My_Name + replaceSpecialCharsWithUnderscore | string | Replace special chars like @,$ to _ . Ex:abc@123%a$ - abc_123_a_ + addKeyToObject | object | Adds key to objects + getIndex | arr,object | Find index of an Item from Array of objects. + toNumber | value | Convert a string to number + partition | arr, criteria | Partition array into two arrays based on criteria + isArray | value | Check for an Array + isObject | value | Check for an Object + isFunction | value | Check for a function + +## Storage Util Methods + + Method | Params | Description +----------------------------------|------------------|----------------------------------------- + get | key | Get value from localstorage by key name + set | key, value | Set value to localstorage + has | key | Check key available in localstorage + remove | key | Remove key from localstorage + removeAll | - | Remove all items from localstorage + +## Geo Location Util Method + + Method | Params | Description +----------------------------------|------------------|---------------------------- + getLatLong | timeout | get lat and long + +## URL Parameter Method + + Method | Params | Description +----------------------------------|----------------------|---------------------------- + getURLParameter | qrString, paramName | get parameter value + +## Date Util Methods + + Method | Params | Description +----------------------------------|------------------|--------------------------------------------------------------------- + formatDate | date | Returns an object of day, month, year + getCurrentDate | - | Returns current date + getDateByDashFormat | date | Returns date with DD-MM-YYYY format + getDateBySlashFormat | date | Returns date with DD/MM/YYYY format + timestampToDate | timestamp | Converting timestamp to date Ex : 1560211200000 to Tue Jun 11 2019 + getDateFromString | string | Converting string to date Ex : '6-11-2019' to Tue Jun 11 2019 + +---------------------------------------------------------------------------------------------------------------------------- + +## Usage +```javascript +import { CurrencyUtils, CommonUtils, StorageUtils, GeoLocationUtils, URLUtils, History, DateUtils } from 'utileo'; + +//---------------------------------- Currency Utils -------------------------// +CurrencyUtils.format('10000') // 10,000 +CurrencyUtils.format('10000.1234',true) // 10,000.12 +CurrencyUtils.parse('1,00,000') // 100000 + +//---------------------------------- Common Utils -------------------------------------// +CommonUtils.validateName('only alphabets')// true +CommonUtils.validateOnlyNumber('1233')// true +CommonUtils.titleCase('main menu')// Main Menu +CommonUtils.camelize('main-menu')// mainMenu +CommonUtils.toNumber('1234')// 1234 +CommonUtils.isArray([1,2,3]);// true +CommonUtils.isObject({"name": "abc", "age": 12})// true +CommonUtils.isFunction(CommonUtils.isObject);// true + +var users = [ + {'user': 'barney', 'age': 36, 'active': false}, + {'user': 'fred', 'age': 40, 'active': true}, + {'user': 'pebbles', 'age': 1, 'active': false} +]; + +var groups = CommonUtils.partition(users, function (user) { + return user.active; +}); +// groups[0] has [{'user':'fred', 'age': 40, 'active': true}] +// groups[1] has [{'user':'barney', 'age': 36, 'active': false}, {'user': 'pebbles', 'age': 1, 'active': false}] + +CommonUtils.getIndex(users,{'user': 'barney', 'age': 36, 'active': false});// 0 + +CommonUtils.addKeyToObject(users);// key(type) will be added +// [{type: "0", user: "barney", age: 36, active: false} +// {type: "1", user: "fred", age: 40, active: true} +// {type: "2", user: "pebbles", age: 1, active: false}] + +//------------------------ Storage Utils -----------------------------// +StorageUtils.get('phoneNumber')// 9899224433 +StorageUtils.set('phoneNumber',9899224433) +StorageUtils.has('phoneNumber')// true +StorageUtils.remove('token') +StorageUtils.removeAll() + +//----------------------- Geo Location ----------------------------// +let latLong = GeoLocationUtils.getLatLong()// value of lat long +let latitude = latLong.lat +let longitude = latLong.long + +//--------------------------------- URL Parameter ---------------------------------------// +var appVisa = URLUtils.getURLParameter(window.location.href, 'visa')// 12n23be3h3bhbbh34 + +//--------- History --------// +History.replace("/") +History.goBack() +History.push("/") + +//------------------------------------------ Date Utils ------------------------------------------------// +const currDate = DateUtils.getCurrentDate();// Wed Jul 14 2020 13:07:57 GMT+0530 (India Standard Time) +const dateObj = DateUtils.formatDate(currDate);// {day: 14, month: 6, year: 2020} +DateUtils.getDateByDashFormat(currDate);// 14-07-2020 +DateUtils.getDateBySlashFormat(currDate);// 14/07/2020 +DateUtils.timestampToDate(1560211200000);// Tue Jun 11 2019 05:30:00 GMT+0530 (India Standard Time) +DateUtils.getDateFromString('2/10/2017');// Sat Feb 10 2017 00:00:00 GMT+0530 (India Standard Time) + +``` + ## Contributors Here [Contributors](https://github.com/bharatpe/utileo/graphs/contributors) diff --git a/dist/lib.js b/dist/lib.js index f5bd7c1..73843da 100644 --- a/dist/lib.js +++ b/dist/lib.js @@ -1 +1 @@ -module.exports=function(o){var r={};function n(e){if(r[e])return r[e].exports;var t=r[e]={i:e,l:!1,exports:{}};return o[e].call(t.exports,t,t.exports,n),t.l=!0,t.exports}return n.m=o,n.c=r,n.d=function(e,t,o){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:o})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var o=Object.create(null);if(n.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var r in t)n.d(o,r,function(e){return t[e]}.bind(null,r));return o},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=0)}([function(e,t,o){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DateUtils=t.StorageUtils=void 0;var r=u(o(1)),n=u(o(2));function u(e){return e&&e.__esModule?e:{default:e}}t.StorageUtils=r.default,t.DateUtils=n.default},function(e,t,o){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r="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},n={};t.default={get:function(e){var t=n[e]||window.localStorage.getItem(e);return function(t){try{return JSON.parse(t)}catch(e){return t}}(t)},set:function(t,o){"object"===(void 0===o?"undefined":r(o))&&(o=JSON.stringify(o));try{window.localStorage.setItem(t,o)}catch(e){n[t]=o}},has:function(e){return n.hasOwnProperty(e)||null!==window.localStorage.getItem(e)},remove:function(e){window.localStorage.removeItem(e),delete n[e]},removeAll:function(){n={},window.localStorage.clear()}}},function(e,t,o){}]); \ No newline at end of file +module.exports=function(n){var r={};function o(t){if(r[t])return r[t].exports;var e=r[t]={i:t,l:!1,exports:{}};return n[t].call(e.exports,e,e.exports,o),e.l=!0,e.exports}return o.m=n,o.c=r,o.d=function(t,e,n){o.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},o.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},o.t=function(e,t){if(1&t&&(e=o(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(o.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)o.d(n,r,function(t){return e[t]}.bind(null,r));return n},o.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return o.d(e,"a",e),e},o.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},o.p="",o(o.s=0)}([function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.CurrencyUtils=e.GeoLocationUtils=e.URLUtils=e.History=e.CommonUtils=e.DateUtils=e.StorageUtils=void 0;var r=f(n(1)),o=f(n(2)),u=f(n(3)),a=f(n(4)),i=f(n(5)),c=f(n(6)),l=f(n(7));function f(t){return t&&t.__esModule?t:{default:t}}e.StorageUtils=r.default,e.DateUtils=o.default,e.CommonUtils=u.default,e.History=a.default,e.URLUtils=i.default,e.GeoLocationUtils=c.default,e.CurrencyUtils=l.default},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},o={};e.default={get:function(t){var e=o[t]||window.localStorage.getItem(t);return function(e){try{return JSON.parse(e)}catch(t){return e}}(e)},set:function(e,n){"object"===(void 0===n?"undefined":r(n))&&(n=JSON.stringify(n));try{window.localStorage.setItem(e,n)}catch(t){o[e]=n}},has:function(t){return o.hasOwnProperty(t)||null!==window.localStorage.getItem(t)},remove:function(t){window.localStorage.removeItem(t),delete o[t]},removeAll:function(){o={},window.localStorage.clear()}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default={formatDate:function(t){return"[object Date]"===Object.prototype.toString.call(t)?{day:t.getDate(),month:t.getMonth(),year:t.getFullYear()}:t},getCurrentDate:function(){return new Date},getDateByDashFormat:function(t){if("[object Date]"!==Object.prototype.toString.call(t))return t;var e=new Date(t),n=(n=e.getDate())<10?"0"+n:n,r=e.getMonth()+1;return n+"-"+(r=r<10?"0"+r:r)+"-"+e.getFullYear()},getDateBySlashFormat:function(t){if("[object Date]"!==Object.prototype.toString.call(t))return t;var e=new Date(t),n=(n=e.getDate())<10?"0"+n:n,r=e.getMonth()+1;return n+"/"+(r=r<10?"0"+r:r)+"/"+e.getFullYear()},timestampToDate:function(t){return"number"==typeof t?new Date(t):t},getDateFromString:function(t){var e=t.split("/");return e.length<3?"Invalid date":new Date(e[1]+"/"+e[0]+"/"+e[2])}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});function r(t){return Array.isArray(t)}var o=Object.assign||function(t){for(var e=1;e { + if (typeof str === "string") { + return ONLY_APLHABETS_REGEX.test(str); + } + return str; +}; + +/** + * @function _validateOnlyNumber + * @param {string,number} str + * @description Check if it is a number + */ +const _validateOnlyNumber = str => { + if (typeof str === "string" || typeof str === "number") { + return ONLY_NUMBER_REGEX.test(str); + } + return str; +}; + +/** + * @function _titleCase + * @param {string} str + * @description convert a string to title case + */ +const _titleCase = str => { + if (typeof str === "string") { + return str.toLowerCase().split(' ').map(function(word) { + return (word.charAt(0).toUpperCase() + word.slice(1)); + }).join(' '); + } + return str; +}; + +/** + * @function _camelize + * @param {string} str + * @description Converting hello-world style strings to helloWorld style strings + */ +const _camelize = str => { + const camelizeRE = /-(\w)/g; + if (typeof str === "string") { + return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : ''); + } + return str; +}; + +/** + * @function _removeSpacesAndLowerCase + * @param {string} str + * @description Converting to lower case and remove spaces in a string + */ +const _removeSpacesAndLowerCase = str => { + if (typeof str === "string") { + return str.toLowerCase().replace(' ', ''); + } + return str; + }; + +/** + * @function _replaceSpaceWithUnderscore + * @param {string} str + * @description Converting space to underscore in a string + */ +const _replaceSpaceWithUnderscore = str => { + if (typeof str === "string") { + return str && str.replace(' ', '_').toLowerCase(); + } + return str; +}; + +/** + * @function _replaceSpecialCharsWithUnderscore + * @param {string} str + * @description Replace special chars like @,$ to _ + */ +const _replaceSpecialCharsWithUnderscore = str => { + if (typeof str === "string") { + return str && str.replace(/[^A-Z0-9]+/gi, '_').toLowerCase(); + } + return str; +}; + +/** + * @function _addKeyToObject + * @param {*} object + * @description Add type key to objects + */ +const _addKeyToObject = object => { + if (!object) { + return []; + } + + const keys = Object.keys(object); + + return keys.map(item => { + return { + type: item, + ...object[item], + }; + }); +}; + +/** + * @function _getIndex + * @param {Array} inputArr + * @param {Object} needleObj + * @description Returns index of needleObj in an array of objects inputArr + */ +const _getIndex = (inputArr, needleObj) => { + if (Object.prototype.toString.call(needleObj) !== '[object Object]') { + return "Not a valid needle(object)" + } + if (Object.prototype.toString.call(inputArr) !== '[object Array]') { + return "Not a valid array"; + } + let idx = -1; + let needleKey = Object.keys(needleObj)[0]; + let needleValue = needleObj[needleKey]; + for (let i = 0; i < inputArr.length; i++) { + const val = inputArr[i]; + if (val[needleKey] == needleValue) { + idx = i; + break; + } + } + return idx; +} + +/** + * @function _toNumber + * @param {string} value + * @description convert a string to number + */ +const _toNumber = value => { + if(value != undefined){ + return Number(value); + } + return value; +}; + +/** + * @function _partition + * @param {array} arr + * @param {function} criteria + * @description splits an array into two groups - one that match criteria and one that don't + */ +var _partition = function (arr, criteria) { + if (_isArray(arr)) { + return [ + arr.filter(function (item) { + return criteria(item); + }), + arr.filter(function (item) { + return !criteria(item); + }), + ]; + } + return arr; +}; + +/** + * @function _isArray + * @param {*} arr + * @description Check for an Array + */ +const _isArray = arr => { + return Array.isArray(arr); ; +}; + +/** + * @function _isObject + * @param {*} obj + * @description Check for an Object + */ +const _isObject = obj => { + return Object.prototype.toString.call(obj) === "[object Object]"; +}; + +/** + * @function _isFunction + * @param {*} func + * @description Check for a function + */ +const _isFunction = func => { + return typeof func === 'function'; +}; + +export default { + validateName: _validateName, + validateOnlyNumber: _validateOnlyNumber, + titleCase: _titleCase, + camelize: _camelize, + removeSpacesAndLowerCase: _removeSpacesAndLowerCase, + replaceSpaceWithUnderscore: _replaceSpaceWithUnderscore, + replaceSpecialCharsWithUnderscore: _replaceSpecialCharsWithUnderscore, + addKeyToObject: _addKeyToObject, + getIndex: _getIndex, + toNumber: _toNumber, + partition: _partition, + isArray: _isArray, + isObject: _isObject, + isFunction: _isFunction, +}; \ No newline at end of file diff --git a/src/CurrencyUtils.js b/src/CurrencyUtils.js new file mode 100644 index 0000000..756e61c --- /dev/null +++ b/src/CurrencyUtils.js @@ -0,0 +1,49 @@ +var CurrencyUtils = { + /** + * use this method to display any and all amount-values + * @param {[number, boolean]} amount [200000] + * @return {[string]} [2,00,000] + */ + format: function (amount, isFloat) { + if (typeof amount === "string" || typeof amount === "number") { + if (isFloat) { + const num = Number(Number(amount).toFixed(2)).toString(); + const floatFormatted = num.indexOf('.') > -1 ? num.replace(/(\d)(?=(\d{2})+\d\.)/g, '$1,') : null; + + if (floatFormatted !== null) { + return floatFormatted.slice(0, floatFormatted.length); + } + } + + const formatted = parseInt(amount).toFixed(1).replace(/(\d)(?=(\d{2})+\d\.)/g, '$1,'); + return formatted.slice(0, formatted.length - 2); + } + return amount; + }, + + /** + * use this method to parse amount-value back to number-only + * @param {[string]} amount [2,00,000] + * @return {[number]} [200000] + */ + parse: function (amount) { + if (typeof amount === "string") { + return parseInt(amount.split(",").join("")); + } + return amount; + }, + + /** + * use this method before-submitting on any API-requests + * @param {[string]} amount + * @return {[number]} + */ + beforeAPIRequest: function (amount) { + if (typeof amount === "string") { + return this.parse(amount); + } + return amount; + } +}; + +export default CurrencyUtils; \ No newline at end of file diff --git a/src/DateUtils.js b/src/DateUtils.js index e69de29..dd04e38 100644 --- a/src/DateUtils.js +++ b/src/DateUtils.js @@ -0,0 +1,95 @@ +/** + * @name _formatDate + * @param {*} date + * @returns {Object} + * @description Date formatting and sending an object of day, month, year + */ +const _formatDate = date => { + if (Object.prototype.toString.call(date) === '[object Date]') { + return { + day: date.getDate(), + month: date.getMonth(), + year: date.getFullYear(), + }; + } + return date; +}; + +/** + * @name _getCurrentDate + * @returns {date} + * @description Sending current date + */ +const _getCurrentDate = () => new Date(); + +/** + * @name _getDateByDashFormat + * @param {*} date + * @returns {string} + * @description Converting date to DD-MM-YYYY format Ex : 18-11-2020 + */ +const _getDateByDashFormat = date => { + if (Object.prototype.toString.call(date) === '[object Date]') { + const formatDate = new Date(date); + var day = formatDate.getDate(); + day = day < 10 ? (`0${day}`) : day; + var month = formatDate.getMonth() + 1; + month = month < 10 ? (`0${month}`) : month; + return `${day}-${month}-${formatDate.getFullYear()}`; + } + return date; +}; + +/** + * @name _getDateBySlashFormat + * @param {*} date + * @returns {string} + * @description Converting date to DD/MM/YYYY format Ex : 18/11/2020 + */ +const _getDateBySlashFormat = date => { + if (Object.prototype.toString.call(date) === '[object Date]') { + const formatDate = new Date(date); + var day = formatDate.getDate(); + day = day < 10 ? (`0${day}`) : day; + var month = formatDate.getMonth() + 1; + month = month < 10 ? (`0${month}`) : month; + return `${day}/${month}/${formatDate.getFullYear()}`; + } + return date; +}; + +/** + * @name _timestampToDate + * @param {number} timestamp + * @returns {date} + * @description Converting timestamp to date Ex : 1560211200000 to + * Tue Jun 11 2019 05:30:00 GMT+0530 (India Standard Time) + */ +const _timestampToDate = timestamp => { + if (typeof timestamp === "number") { + return new Date(timestamp); + } + return timestamp; +}; + +/** + * @name _getDateFromString + * @param {string} value + * @returns {date} + * @description Converting string to date Ex : '2/10/2017' to + * Sat Feb 10 2017 00:00:00 GMT+0530 (India Standard Time) + */ +const _getDateFromString = value => { + const dateSplit = value.split("/"); + if (dateSplit.length < 3) return "Invalid date"; + return new Date(`${dateSplit[1]}/${dateSplit[0]}/${dateSplit[2]}`) +}; + +export default { + formatDate: _formatDate, + getCurrentDate: _getCurrentDate, + getDateByDashFormat: _getDateByDashFormat, + getDateBySlashFormat: _getDateBySlashFormat, + timestampToDate: _timestampToDate, + getDateFromString:_getDateFromString, +}; \ No newline at end of file diff --git a/src/geolocation.js b/src/geolocation.js new file mode 100644 index 0000000..3db147e --- /dev/null +++ b/src/geolocation.js @@ -0,0 +1,105 @@ +/* eslint-disable no-case-declarations */ +// check permissions +function checkPermission() { + if (navigator && navigator.permissions) { + return navigator.permissions.query({name:'geolocation'}); + } else { + return { + state: 'prompt' + } + } +} + +// return timeout promise +function getTimeoutPromise(timeout = 10000, rejectParams = {}) { + let timeoutRef = null; + const timeoutPromise = new Promise((resolve, reject) => { + timeoutRef = setTimeout(() => { + resolve({...{ + status: 'timeout', + value: timeout + }, ...rejectParams}); + console.error('timeout on fetch User Latitude and Longitude'); + }, timeout); + }); + + // bind method for cancel existing timeout + timeoutPromise.cancelTimeout = function() { + clearTimeout(timeoutRef); + } + return timeoutPromise; +} + +// get current geo lat long +function getCurrentLatLong(timeout) { + const racePromiseList = []; + let timeoutPromise = null; + + // check need of timeout promise or not + if (timeout !== undefined) { + timeoutPromise = getTimeoutPromise(timeout, {latitude: null, longitude: null}); + racePromiseList.push(timeoutPromise); + } + + // create lag long promise + const langLongPromise = new Promise((resolve, reject) => { + navigator.geolocation.getCurrentPosition(function(position) { + const { coords } = position; + // cancel timeout of timeout promise + if (timeoutPromise) { + timeoutPromise.cancelTimeout(); + } + resolve({ + latitude: coords.latitude.toFixed(2), + longitude: coords.longitude.toFixed(2) + }); + }, function() { + // cancel timeout of timeout promise + if (timeoutPromise) { + timeoutPromise.cancelTimeout(); + } + + resolve({ + latitude: null, + longitude: null + }); + }); + }); + + racePromiseList.push(langLongPromise); + return Promise.race(racePromiseList); +} + +/** + * @function _getLatLong + * @param {number} timeout + * @description get lat and long + */ +async function _getLatLong(timeout) { + const latLong = { + lat: 0, + long: 0 + }; + if (navigator.geolocation) { + const result = await checkPermission(); + switch (result.state) { + case 'granted': + case 'prompt': + const { latitude, longitude } = await getCurrentLatLong(timeout); + latLong.lat = latitude; + latLong.long = longitude; + break; + case 'denied': + latLong.lat = null; + latLong.long = null; + break; + } + } else { + console.log('geolocation not supported!!!!'); + } + return latLong; +} + +export default { + getLatLong: _getLatLong, + }; \ No newline at end of file diff --git a/src/history.js b/src/history.js new file mode 100644 index 0000000..f6a19c6 --- /dev/null +++ b/src/history.js @@ -0,0 +1,8 @@ +import { createHashHistory } from 'history'; + +const history = createHashHistory(); +history.listen(_ => { + window.scrollTo(0, 0) +}) + +export default history; \ No newline at end of file diff --git a/src/index.js b/src/index.js index d22a8fa..712486c 100644 --- a/src/index.js +++ b/src/index.js @@ -1,7 +1,17 @@ import StorageUtils from './StorageUtils'; import DateUtils from './DateUtils'; +import CommonUtils from './CommonUtils'; +import History from './history'; +import URLUtils from './urlParameter'; +import GeoLocationUtils from './geolocation'; +import CurrencyUtils from './CurrencyUtils'; export { StorageUtils, - DateUtils + DateUtils, + CommonUtils, + History, + URLUtils, + GeoLocationUtils, + CurrencyUtils, }; diff --git a/src/urlParameter.js b/src/urlParameter.js new file mode 100644 index 0000000..954bfb9 --- /dev/null +++ b/src/urlParameter.js @@ -0,0 +1,25 @@ +/** + * @function _getURLParameter + * @param {string} qrString + * @param {string} paramName + * @description get value of param from URL + */ +const _getURLParameter = (qrString, paramName) => { + if (typeof qrString === "string" && typeof paramName === "string") { + qrString = qrString.replace(/[\[]/,'\\[').replace(/[\]]/,'\\]'); + var regex = new RegExp('[\\?&]' + paramName + '=([^&#]*)'); + var results = regex.exec(qrString); + + + if (results && results.length > 0) { + return decodeURIComponent(results[1].replace(/\+/g, ' ')); + } else { + return ''; + } + } + return ''; +} + +export default { + getURLParameter: _getURLParameter, +}; \ No newline at end of file diff --git a/yarn.lock b/yarn.lock index 247563d..83bd1bb 100644 --- a/yarn.lock +++ b/yarn.lock @@ -61,6 +61,13 @@ resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.10.2.tgz#871807f10442b92ff97e4783b9b54f6a0ca812d0" integrity sha512-PApSXlNMJyB4JiGVhCOlzKIif+TKFTvu0aQAhnTvfP/z3vVSN6ZypH5bfUNwFXXjRQtUEBNFd2PtmCmG2Py3qQ== +"@babel/runtime@^7.7.6": + version "7.10.5" + resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.10.5.tgz#303d8bd440ecd5a491eae6117fd3367698674c5c" + integrity sha512-otddXKhdNn7d0ptoFRHtMLa8LqDxLYwTjB4nYgM1yy5N6gU/MUf8zqyyLltCH3yAVitBzmwK4us+DD0l/MauAg== + dependencies: + regenerator-runtime "^0.13.4" + "@babel/template@^7.10.1": version "7.10.1" resolved "https://registry.yarnpkg.com/@babel/template/-/template-7.10.1.tgz#e167154a94cb5f14b28dc58f5356d2162f539811" @@ -2688,6 +2695,13 @@ hash.js@^1.0.0, hash.js@^1.0.3: inherits "^2.0.3" minimalistic-assert "^1.0.1" +history@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/history/-/history-5.0.0.tgz#0cabbb6c4bbf835addb874f8259f6d25101efd08" + integrity sha512-3NyRMKIiFSJmIPdq7FxkNMJkQ7ZEtVblOQ38VtKaA0zZMW1Eo6Q6W8oDKEflr1kNNTItSnk4JMCO1deeSgbLLg== + dependencies: + "@babel/runtime" "^7.7.6" + hmac-drbg@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/hmac-drbg/-/hmac-drbg-1.0.1.tgz#d2745701025a6c775a6c545793ed502fc0c649a1" @@ -4208,6 +4222,11 @@ regenerator-runtime@^0.11.0: resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz#be05ad7f9bf7d22e056f9726cee5017fbf19e2e9" integrity sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg== +regenerator-runtime@^0.13.4: + version "0.13.7" + resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.13.7.tgz#cac2dacc8a1ea675feaabaeb8ae833898ae46f55" + integrity sha512-a54FxoJDIr27pgf7IgeQGxmqUNYrcV338lf/6gH456HZ/PhX+5BcwHXG9ajESmwe6WRO0tAzRUrRmNONWgkrew== + regenerator-transform@^0.10.0: version "0.10.1" resolved "https://registry.yarnpkg.com/regenerator-transform/-/regenerator-transform-0.10.1.tgz#1e4996837231da8b7f3cf4114d71b5691a0680dd"