Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Friday, 18 January 2019

Sorting a dictionary in javascript

Once time, a user of stackoverflow is asking how to sort a dictionary in javascript. Here I would like to share a simple implementation which will return an array whose each item is an item in the input dictionary and sorted according to sort function. And test code also included.

javascript
var sortDict = function (dict, compare) {
  let keys = Object.keys(dict)
  let sortedKeys = keys.sort(compare)
  result = []
  for (let i in sortedKeys) {
    let aKey = sortedKeys[i]
    let anItem = {}
    anItem[aKey] = dict[aKey]
    result.push(anItem)
  }
  return result
}
var a = {"zabc": 8, "abc": 6, "jabc": 3, 'baaa': '5'}
console.log(JSON.stringify(sortDict(a, function (k1, k2) {
  // return a[k1] > a[k2]
  return k1 > k2
})))

You will see the sorted result printed.


To have different sorting criteria, just have your own compare function implementation. Thank you!

Yorm is a superlight node module to work with mysql

Disclaimer: I am the author of npm yorm.

Yorm version 1.0.2 is published. With only 800 lines and 26KB size, it encapsulates the functionality of reading DB records to objects and synchronize objects to DB but also without loss the flexibility of transaction management and pool connection management.

For person and organization who really want to deploy backend functionality on the basis of mysql compatible databases, this is a super fast and quality assured module since it is super small and its code is open sourced.

Here is the extract from its readme.

Create a db.js in config directory of your root project directory with your DB connection info. Create a table in mysql database.

SQL
create table aa (id1 int, id2 int, va1 varchar(30), primary key (id1, id2));

javascript
var yorm = require('yorm')
  var onerecord = {}
  onerecord.id1 = '1'
  onerecord.id2 = '20'
  onerecord.val1 = 'Testing value'

  var test = function() {
    yorm.saveone('aa', onerecord)
    var records = []
    for (var i = 0; i < 10, i++) {
      for (var j = 0; j < 3, j++ {
        onerecord = {'id1': i, 'id2':j, 'val1': 'value: ' + i + '/' + 'j'}
        records.push(onerecord)
      }
    }
    yorm.savemany('aa', records).then(function() {
      console.log('Table aa had been inserted many records.'
    }
  }

#Now since 1.0.1 have to call bufferinit for first time call. So change setTimeout(test, 1000) to below:
  yorm.bufferinit().then(test)

Hope you enjoy! And if you have any problem, send me an email to consider to hire me!