Last active
July 17, 2024 09:46
-
-
Save dtanphat9388/09c42da25563c33fc9bb527bc4c7fc92 to your computer and use it in GitHub Desktop.
mapper object key in javascript
This file contains 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
/* | |
FUNCTION DESIGN | |
Requirement: | |
- not change source object | |
Features: | |
- mapping | |
- include/exclude | |
APIs: | |
let mapped = mapper(src).map().ignoreAll().done() // select mapped keys only | |
let mapped = mapper(src).map().select().done() // select mapped keys & some key | |
let mapped = mapper(src).map().done() // select mapped keys & all other keys | |
*/ | |
// function style | |
function mapper(src = {}) { | |
let _src = { ...src } | |
let dest = {} | |
return { | |
map: function map(from, to) { | |
dest[to] = _src[from] | |
delete _src[from] | |
return this | |
}, | |
select: function select(...keys) { | |
for (let k of keys) { dest[k] = _src[k] } | |
_src = {} | |
return this | |
}, | |
ignore: function ignore(...keys) { | |
for (let k of keys) { | |
delete _src[k] | |
} | |
return this | |
}, | |
ignoreAll: function ignoreAll() { | |
_src = {} | |
return this | |
}, | |
done: function done() { | |
return { ...dest, ..._src } | |
} | |
} | |
} | |
// class style | |
class Mapper { | |
#dest = {} | |
#_src | |
constructor(src) { | |
this.#_src = src | |
} | |
map(from, to) { | |
this.#dest[to] = this.#_src[from] | |
delete this.#_src[from] | |
return this | |
} | |
select(...keys) { | |
for (let k of keys) { this.#dest[k] = this.#_src[k] } | |
this.#_src = {} | |
return this | |
} | |
ignore(...keys) { | |
for (let k of keys) { | |
delete this.#_src[k] | |
} | |
return this | |
} | |
ignoreAll() { | |
this.#_src = {} | |
return this | |
} | |
done() { | |
return { ...this.#dest, ...this.#_src } | |
} | |
} | |
let src = { id: "abc", pwd: "xyz", name: "hello", age: 100, abc: "xxx", xyz: "xxx" } | |
let mappedF = mapper(src) | |
.map("id", "Id") | |
.map("pwd", "password") | |
.ignore("name", "age") | |
.done() | |
let mappedC = new Mapper(src) | |
.map("id", "Id") | |
.map("pwd", "password") | |
.ignore("name", "age") | |
.done() | |
console.log(mappedF) | |
console.log(mappedC) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment