loopable
v1.0.7
Published
Wrap a list to reduce loops with multiple customizations of the items
Downloads
4
Maintainers
Readme
Loopable
- Wrap a list then able to add multiple modifiers the items with a single loop
- Discuss: https://mrbaobao.medium.com/one-time-array-loop-ec8cf8089c60
- Git sample: https://gitlab.com/mrbaobao/test-loopable
- CommonJS
const { make, Loopable } = require("loopable")
const arrUsers = [
{ name: "Iron Man" },
{ name: "Black Widow" },
{ name: "Captain America" },
{ name: "Peter Parker" },
]
//Log initial
console.log(arrUsers)
/*
[
{ name: 'Iron Man' },
{ name: 'Black Widow' },
{ name: 'Captain America' },
{ name: 'Peter Parker' }
]
*/
//Make it loopable
const loopableList = make(arrUsers)
//Add modifier
loopableList
.add((item, index) => {
item.name = "I am " + item.name
})
.add((item, index) => {
item.age = 28 - index * 2
})
//Loop one time
const output = loopableList.loop((item, index) => {
item.is_woman = index == 1
})
console.log(output)
/*
[
'1.I am Iron Man, 28, false',
'2.I am Black Widow, 26, true',
'3.I am Captain America, 24, false',
'4.I am Peter Parker, 22, false'
]
*/
console.log(arrUsers)
/*
[
{ name: 'I am Iron Man', age: 28, is_woman: false },
{ name: 'I am Black Widow', age: 26, is_woman: true },
{ name: 'I am Captain America', age: 24, is_woman: false },
{ name: 'I am Peter Parker', age: 22, is_woman: false }
]
*/
- Api
- make(list): Loopable
- Loopable
- add(modifier: Modifier): Loopable
- loop(modifier?: Modifier): any[] //Return the list after modified